1//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for statements.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/ASTDiagnostic.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/CharUnits.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/EvaluatedExprVisitor.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/IgnoreExpr.h"
23#include "clang/AST/RecursiveASTVisitor.h"
24#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/AST/TypeOrdering.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Lex/Preprocessor.h"
30#include "clang/Sema/EnterExpressionEvaluationContext.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Ownership.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ScopeInfo.h"
36#include "clang/Sema/SemaInternal.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/DenseMap.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/SmallPtrSet.h"
41#include "llvm/ADT/SmallString.h"
42#include "llvm/ADT/SmallVector.h"
43#include "llvm/ADT/StringExtras.h"
44
45using namespace clang;
46using namespace sema;
47
48StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) {
49 if (FE.isInvalid())
50 return StmtError();
51
52 FE = ActOnFinishFullExpr(Expr: FE.get(), CC: FE.get()->getExprLoc(), DiscardedValue);
53 if (FE.isInvalid())
54 return StmtError();
55
56 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
57 // void expression for its side effects. Conversion to void allows any
58 // operand, even incomplete types.
59
60 // Same thing in for stmt first clause (when expr) and third clause.
61 return StmtResult(FE.getAs<Stmt>());
62}
63
64
65StmtResult Sema::ActOnExprStmtError() {
66 DiscardCleanupsInEvaluationContext();
67 return StmtError();
68}
69
70StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
71 bool HasLeadingEmptyMacro) {
72 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
73}
74
75StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
76 SourceLocation EndLoc) {
77 DeclGroupRef DG = dg.get();
78
79 // If we have an invalid decl, just return an error.
80 if (DG.isNull()) return StmtError();
81
82 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
83}
84
85void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
86 DeclGroupRef DG = dg.get();
87
88 // If we don't have a declaration, or we have an invalid declaration,
89 // just return.
90 if (DG.isNull() || !DG.isSingleDecl())
91 return;
92
93 Decl *decl = DG.getSingleDecl();
94 if (!decl || decl->isInvalidDecl())
95 return;
96
97 // Only variable declarations are permitted.
98 VarDecl *var = dyn_cast<VarDecl>(Val: decl);
99 if (!var) {
100 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
101 decl->setInvalidDecl();
102 return;
103 }
104
105 // foreach variables are never actually initialized in the way that
106 // the parser came up with.
107 var->setInit(nullptr);
108
109 // In ARC, we don't need to retain the iteration variable of a fast
110 // enumeration loop. Rather than actually trying to catch that
111 // during declaration processing, we remove the consequences here.
112 if (getLangOpts().ObjCAutoRefCount) {
113 QualType type = var->getType();
114
115 // Only do this if we inferred the lifetime. Inferred lifetime
116 // will show up as a local qualifier because explicit lifetime
117 // should have shown up as an AttributedType instead.
118 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
119 // Add 'const' and mark the variable as pseudo-strong.
120 var->setType(type.withConst());
121 var->setARCPseudoStrong(true);
122 }
123 }
124}
125
126/// Diagnose unused comparisons, both builtin and overloaded operators.
127/// For '==' and '!=', suggest fixits for '=' or '|='.
128///
129/// Adding a cast to void (or other expression wrappers) will prevent the
130/// warning from firing.
131static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
132 SourceLocation Loc;
133 bool CanAssign;
134 enum { Equality, Inequality, Relational, ThreeWay } Kind;
135
136 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: E)) {
137 if (!Op->isComparisonOp())
138 return false;
139
140 if (Op->getOpcode() == BO_EQ)
141 Kind = Equality;
142 else if (Op->getOpcode() == BO_NE)
143 Kind = Inequality;
144 else if (Op->getOpcode() == BO_Cmp)
145 Kind = ThreeWay;
146 else {
147 assert(Op->isRelationalOp());
148 Kind = Relational;
149 }
150 Loc = Op->getOperatorLoc();
151 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
152 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
153 switch (Op->getOperator()) {
154 case OO_EqualEqual:
155 Kind = Equality;
156 break;
157 case OO_ExclaimEqual:
158 Kind = Inequality;
159 break;
160 case OO_Less:
161 case OO_Greater:
162 case OO_GreaterEqual:
163 case OO_LessEqual:
164 Kind = Relational;
165 break;
166 case OO_Spaceship:
167 Kind = ThreeWay;
168 break;
169 default:
170 return false;
171 }
172
173 Loc = Op->getOperatorLoc();
174 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
175 } else {
176 // Not a typo-prone comparison.
177 return false;
178 }
179
180 // Suppress warnings when the operator, suspicious as it may be, comes from
181 // a macro expansion.
182 if (S.SourceMgr.isMacroBodyExpansion(Loc))
183 return false;
184
185 S.Diag(Loc, diag::warn_unused_comparison)
186 << (unsigned)Kind << E->getSourceRange();
187
188 // If the LHS is a plausible entity to assign to, provide a fixit hint to
189 // correct common typos.
190 if (CanAssign) {
191 if (Kind == Inequality)
192 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
193 << FixItHint::CreateReplacement(Loc, "|=");
194 else if (Kind == Equality)
195 S.Diag(Loc, diag::note_equality_comparison_to_assign)
196 << FixItHint::CreateReplacement(Loc, "=");
197 }
198
199 return true;
200}
201
202static bool DiagnoseNoDiscard(Sema &S, const WarnUnusedResultAttr *A,
203 SourceLocation Loc, SourceRange R1,
204 SourceRange R2, bool IsCtor) {
205 if (!A)
206 return false;
207 StringRef Msg = A->getMessage();
208
209 if (Msg.empty()) {
210 if (IsCtor)
211 return S.Diag(Loc, diag::warn_unused_constructor) << A << R1 << R2;
212 return S.Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
213 }
214
215 if (IsCtor)
216 return S.Diag(Loc, diag::warn_unused_constructor_msg) << A << Msg << R1
217 << R2;
218 return S.Diag(Loc, diag::warn_unused_result_msg) << A << Msg << R1 << R2;
219}
220
221void Sema::DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID) {
222 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(Val: S))
223 return DiagnoseUnusedExprResult(S: Label->getSubStmt(), DiagID);
224
225 const Expr *E = dyn_cast_or_null<Expr>(Val: S);
226 if (!E)
227 return;
228
229 // If we are in an unevaluated expression context, then there can be no unused
230 // results because the results aren't expected to be used in the first place.
231 if (isUnevaluatedContext())
232 return;
233
234 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
235 // In most cases, we don't want to warn if the expression is written in a
236 // macro body, or if the macro comes from a system header. If the offending
237 // expression is a call to a function with the warn_unused_result attribute,
238 // we warn no matter the location. Because of the order in which the various
239 // checks need to happen, we factor out the macro-related test here.
240 bool ShouldSuppress =
241 SourceMgr.isMacroBodyExpansion(Loc: ExprLoc) ||
242 SourceMgr.isInSystemMacro(loc: ExprLoc);
243
244 const Expr *WarnExpr;
245 SourceLocation Loc;
246 SourceRange R1, R2;
247 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Ctx&: Context))
248 return;
249
250 // If this is a GNU statement expression expanded from a macro, it is probably
251 // unused because it is a function-like macro that can be used as either an
252 // expression or statement. Don't warn, because it is almost certainly a
253 // false positive.
254 if (isa<StmtExpr>(Val: E) && Loc.isMacroID())
255 return;
256
257 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
258 // That macro is frequently used to suppress "unused parameter" warnings,
259 // but its implementation makes clang's -Wunused-value fire. Prevent this.
260 if (isa<ParenExpr>(Val: E->IgnoreImpCasts()) && Loc.isMacroID()) {
261 SourceLocation SpellLoc = Loc;
262 if (findMacroSpelling(loc&: SpellLoc, name: "UNREFERENCED_PARAMETER"))
263 return;
264 }
265
266 // Okay, we have an unused result. Depending on what the base expression is,
267 // we might want to make a more specific diagnostic. Check for one of these
268 // cases now.
269 if (const FullExpr *Temps = dyn_cast<FullExpr>(Val: E))
270 E = Temps->getSubExpr();
271 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(Val: E))
272 E = TempExpr->getSubExpr();
273
274 if (DiagnoseUnusedComparison(S&: *this, E))
275 return;
276
277 E = WarnExpr;
278 if (const auto *Cast = dyn_cast<CastExpr>(Val: E))
279 if (Cast->getCastKind() == CK_NoOp ||
280 Cast->getCastKind() == CK_ConstructorConversion)
281 E = Cast->getSubExpr()->IgnoreImpCasts();
282
283 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
284 if (E->getType()->isVoidType())
285 return;
286
287 if (DiagnoseNoDiscard(*this, cast_or_null<WarnUnusedResultAttr>(
288 CE->getUnusedResultAttr(Context)),
289 Loc, R1, R2, /*isCtor=*/false))
290 return;
291
292 // If the callee has attribute pure, const, or warn_unused_result, warn with
293 // a more specific message to make it clear what is happening. If the call
294 // is written in a macro body, only warn if it has the warn_unused_result
295 // attribute.
296 if (const Decl *FD = CE->getCalleeDecl()) {
297 if (ShouldSuppress)
298 return;
299 if (FD->hasAttr<PureAttr>()) {
300 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
301 return;
302 }
303 if (FD->hasAttr<ConstAttr>()) {
304 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
305 return;
306 }
307 }
308 } else if (const auto *CE = dyn_cast<CXXConstructExpr>(Val: E)) {
309 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
310 const auto *A = Ctor->getAttr<WarnUnusedResultAttr>();
311 A = A ? A : Ctor->getParent()->getAttr<WarnUnusedResultAttr>();
312 if (DiagnoseNoDiscard(*this, A, Loc, R1, R2, /*isCtor=*/true))
313 return;
314 }
315 } else if (const auto *ILE = dyn_cast<InitListExpr>(Val: E)) {
316 if (const TagDecl *TD = ILE->getType()->getAsTagDecl()) {
317
318 if (DiagnoseNoDiscard(*this, TD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
319 R2, /*isCtor=*/false))
320 return;
321 }
322 } else if (ShouldSuppress)
323 return;
324
325 E = WarnExpr;
326 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: E)) {
327 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
328 Diag(Loc, diag::err_arc_unused_init_message) << R1;
329 return;
330 }
331 const ObjCMethodDecl *MD = ME->getMethodDecl();
332 if (MD) {
333 if (DiagnoseNoDiscard(*this, MD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
334 R2, /*isCtor=*/false))
335 return;
336 }
337 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E)) {
338 const Expr *Source = POE->getSyntacticForm();
339 // Handle the actually selected call of an OpenMP specialized call.
340 if (LangOpts.OpenMP && isa<CallExpr>(Val: Source) &&
341 POE->getNumSemanticExprs() == 1 &&
342 isa<CallExpr>(Val: POE->getSemanticExpr(index: 0)))
343 return DiagnoseUnusedExprResult(POE->getSemanticExpr(index: 0), DiagID);
344 if (isa<ObjCSubscriptRefExpr>(Source))
345 DiagID = diag::warn_unused_container_subscript_expr;
346 else if (isa<ObjCPropertyRefExpr>(Source))
347 DiagID = diag::warn_unused_property_expr;
348 } else if (const CXXFunctionalCastExpr *FC
349 = dyn_cast<CXXFunctionalCastExpr>(Val: E)) {
350 const Expr *E = FC->getSubExpr();
351 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(Val: E))
352 E = TE->getSubExpr();
353 if (isa<CXXTemporaryObjectExpr>(Val: E))
354 return;
355 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Val: E))
356 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
357 if (!RD->getAttr<WarnUnusedAttr>())
358 return;
359 }
360 // Diagnose "(void*) blah" as a typo for "(void) blah".
361 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(Val: E)) {
362 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
363 QualType T = TI->getType();
364
365 // We really do want to use the non-canonical type here.
366 if (T == Context.VoidPtrTy) {
367 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
368
369 Diag(Loc, diag::warn_unused_voidptr)
370 << FixItHint::CreateRemoval(TL.getStarLoc());
371 return;
372 }
373 }
374
375 // Tell the user to assign it into a variable to force a volatile load if this
376 // isn't an array.
377 if (E->isGLValue() && E->getType().isVolatileQualified() &&
378 !E->getType()->isArrayType()) {
379 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
380 return;
381 }
382
383 // Do not diagnose use of a comma operator in a SFINAE context because the
384 // type of the left operand could be used for SFINAE, so technically it is
385 // *used*.
386 if (DiagID != diag::warn_unused_comma_left_operand || !isSFINAEContext())
387 DiagIfReachable(Loc, Stmts: S ? llvm::ArrayRef(S) : std::nullopt,
388 PD: PDiag(DiagID) << R1 << R2);
389}
390
391void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
392 PushCompoundScope(IsStmtExpr);
393}
394
395void Sema::ActOnAfterCompoundStatementLeadingPragmas() {
396 if (getCurFPFeatures().isFPConstrained()) {
397 FunctionScopeInfo *FSI = getCurFunction();
398 assert(FSI);
399 FSI->setUsesFPIntrin();
400 }
401}
402
403void Sema::ActOnFinishOfCompoundStmt() {
404 PopCompoundScope();
405}
406
407sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
408 return getCurFunction()->CompoundScopes.back();
409}
410
411StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
412 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
413 const unsigned NumElts = Elts.size();
414
415 // If we're in C mode, check that we don't have any decls after stmts. If
416 // so, emit an extension diagnostic in C89 and potentially a warning in later
417 // versions.
418 const unsigned MixedDeclsCodeID = getLangOpts().C99
419 ? diag::warn_mixed_decls_code
420 : diag::ext_mixed_decls_code;
421 if (!getLangOpts().CPlusPlus && !Diags.isIgnored(DiagID: MixedDeclsCodeID, Loc: L)) {
422 // Note that __extension__ can be around a decl.
423 unsigned i = 0;
424 // Skip over all declarations.
425 for (; i != NumElts && isa<DeclStmt>(Val: Elts[i]); ++i)
426 /*empty*/;
427
428 // We found the end of the list or a statement. Scan for another declstmt.
429 for (; i != NumElts && !isa<DeclStmt>(Val: Elts[i]); ++i)
430 /*empty*/;
431
432 if (i != NumElts) {
433 Decl *D = *cast<DeclStmt>(Val: Elts[i])->decl_begin();
434 Diag(Loc: D->getLocation(), DiagID: MixedDeclsCodeID);
435 }
436 }
437
438 // Check for suspicious empty body (null statement) in `for' and `while'
439 // statements. Don't do anything for template instantiations, this just adds
440 // noise.
441 if (NumElts != 0 && !CurrentInstantiationScope &&
442 getCurCompoundScope().HasEmptyLoopBodies) {
443 for (unsigned i = 0; i != NumElts - 1; ++i)
444 DiagnoseEmptyLoopBody(S: Elts[i], PossibleBody: Elts[i + 1]);
445 }
446
447 // Calculate difference between FP options in this compound statement and in
448 // the enclosing one. If this is a function body, take the difference against
449 // default options. In this case the difference will indicate options that are
450 // changed upon entry to the statement.
451 FPOptions FPO = (getCurFunction()->CompoundScopes.size() == 1)
452 ? FPOptions(getLangOpts())
453 : getCurCompoundScope().InitialFPFeatures;
454 FPOptionsOverride FPDiff = getCurFPFeatures().getChangesFrom(Base: FPO);
455
456 return CompoundStmt::Create(C: Context, Stmts: Elts, FPFeatures: FPDiff, LB: L, RB: R);
457}
458
459ExprResult
460Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
461 if (!Val.get())
462 return Val;
463
464 if (DiagnoseUnexpandedParameterPack(E: Val.get()))
465 return ExprError();
466
467 // If we're not inside a switch, let the 'case' statement handling diagnose
468 // this. Just clean up after the expression as best we can.
469 if (getCurFunction()->SwitchStack.empty())
470 return ActOnFinishFullExpr(Expr: Val.get(), CC: Val.get()->getExprLoc(), DiscardedValue: false,
471 IsConstexpr: getLangOpts().CPlusPlus11);
472
473 Expr *CondExpr =
474 getCurFunction()->SwitchStack.back().getPointer()->getCond();
475 if (!CondExpr)
476 return ExprError();
477 QualType CondType = CondExpr->getType();
478
479 auto CheckAndFinish = [&](Expr *E) {
480 if (CondType->isDependentType() || E->isTypeDependent())
481 return ExprResult(E);
482
483 if (getLangOpts().CPlusPlus11) {
484 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
485 // constant expression of the promoted type of the switch condition.
486 llvm::APSInt TempVal;
487 return CheckConvertedConstantExpression(From: E, T: CondType, Value&: TempVal,
488 CCE: CCEK_CaseValue);
489 }
490
491 ExprResult ER = E;
492 if (!E->isValueDependent())
493 ER = VerifyIntegerConstantExpression(E, CanFold: AllowFold);
494 if (!ER.isInvalid())
495 ER = DefaultLvalueConversion(E: ER.get());
496 if (!ER.isInvalid())
497 ER = ImpCastExprToType(E: ER.get(), Type: CondType, CK: CK_IntegralCast);
498 if (!ER.isInvalid())
499 ER = ActOnFinishFullExpr(Expr: ER.get(), CC: ER.get()->getExprLoc(), DiscardedValue: false);
500 return ER;
501 };
502
503 ExprResult Converted = CorrectDelayedTyposInExpr(
504 ER: Val, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
505 Filter: CheckAndFinish);
506 if (Converted.get() == Val.get())
507 Converted = CheckAndFinish(Val.get());
508 return Converted;
509}
510
511StmtResult
512Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
513 SourceLocation DotDotDotLoc, ExprResult RHSVal,
514 SourceLocation ColonLoc) {
515 assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
516 assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
517 : RHSVal.isInvalid() || RHSVal.get()) &&
518 "missing RHS value");
519
520 if (getCurFunction()->SwitchStack.empty()) {
521 Diag(CaseLoc, diag::err_case_not_in_switch);
522 return StmtError();
523 }
524
525 if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
526 getCurFunction()->SwitchStack.back().setInt(true);
527 return StmtError();
528 }
529
530 auto *CS = CaseStmt::Create(Ctx: Context, lhs: LHSVal.get(), rhs: RHSVal.get(),
531 caseLoc: CaseLoc, ellipsisLoc: DotDotDotLoc, colonLoc: ColonLoc);
532 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
533 return CS;
534}
535
536/// ActOnCaseStmtBody - This installs a statement as the body of a case.
537void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
538 cast<CaseStmt>(Val: S)->setSubStmt(SubStmt);
539}
540
541StmtResult
542Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
543 Stmt *SubStmt, Scope *CurScope) {
544 if (getCurFunction()->SwitchStack.empty()) {
545 Diag(DefaultLoc, diag::err_default_not_in_switch);
546 return SubStmt;
547 }
548
549 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
550 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(SC: DS);
551 return DS;
552}
553
554StmtResult
555Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
556 SourceLocation ColonLoc, Stmt *SubStmt) {
557 // If the label was multiply defined, reject it now.
558 if (TheDecl->getStmt()) {
559 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
560 Diag(TheDecl->getLocation(), diag::note_previous_definition);
561 return SubStmt;
562 }
563
564 ReservedIdentifierStatus Status = TheDecl->isReserved(getLangOpts());
565 if (isReservedInAllContexts(Status) &&
566 !Context.getSourceManager().isInSystemHeader(IdentLoc))
567 Diag(IdentLoc, diag::warn_reserved_extern_symbol)
568 << TheDecl << static_cast<int>(Status);
569
570 // Otherwise, things are good. Fill in the declaration and return it.
571 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
572 TheDecl->setStmt(LS);
573 if (!TheDecl->isGnuLocal()) {
574 TheDecl->setLocStart(IdentLoc);
575 if (!TheDecl->isMSAsmLabel()) {
576 // Don't update the location of MS ASM labels. These will result in
577 // a diagnostic, and changing the location here will mess that up.
578 TheDecl->setLocation(IdentLoc);
579 }
580 }
581 return LS;
582}
583
584StmtResult Sema::BuildAttributedStmt(SourceLocation AttrsLoc,
585 ArrayRef<const Attr *> Attrs,
586 Stmt *SubStmt) {
587 // FIXME: this code should move when a planned refactoring around statement
588 // attributes lands.
589 for (const auto *A : Attrs) {
590 if (A->getKind() == attr::MustTail) {
591 if (!checkAndRewriteMustTailAttr(St: SubStmt, MTA: *A)) {
592 return SubStmt;
593 }
594 setFunctionHasMustTail();
595 }
596 }
597
598 return AttributedStmt::Create(C: Context, Loc: AttrsLoc, Attrs, SubStmt);
599}
600
601StmtResult Sema::ActOnAttributedStmt(const ParsedAttributes &Attrs,
602 Stmt *SubStmt) {
603 SmallVector<const Attr *, 1> SemanticAttrs;
604 ProcessStmtAttributes(Stmt: SubStmt, InAttrs: Attrs, OutAttrs&: SemanticAttrs);
605 if (!SemanticAttrs.empty())
606 return BuildAttributedStmt(AttrsLoc: Attrs.Range.getBegin(), Attrs: SemanticAttrs, SubStmt);
607 // If none of the attributes applied, that's fine, we can recover by
608 // returning the substatement directly instead of making an AttributedStmt
609 // with no attributes on it.
610 return SubStmt;
611}
612
613bool Sema::checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA) {
614 ReturnStmt *R = cast<ReturnStmt>(Val: St);
615 Expr *E = R->getRetValue();
616
617 if (CurContext->isDependentContext() || (E && E->isInstantiationDependent()))
618 // We have to suspend our check until template instantiation time.
619 return true;
620
621 if (!checkMustTailAttr(St, MTA))
622 return false;
623
624 // FIXME: Replace Expr::IgnoreImplicitAsWritten() with this function.
625 // Currently it does not skip implicit constructors in an initialization
626 // context.
627 auto IgnoreImplicitAsWritten = [](Expr *E) -> Expr * {
628 return IgnoreExprNodes(E, Fns&: IgnoreImplicitAsWrittenSingleStep,
629 Fns&: IgnoreElidableImplicitConstructorSingleStep);
630 };
631
632 // Now that we have verified that 'musttail' is valid here, rewrite the
633 // return value to remove all implicit nodes, but retain parentheses.
634 R->setRetValue(IgnoreImplicitAsWritten(E));
635 return true;
636}
637
638bool Sema::checkMustTailAttr(const Stmt *St, const Attr &MTA) {
639 assert(!CurContext->isDependentContext() &&
640 "musttail cannot be checked from a dependent context");
641
642 // FIXME: Add Expr::IgnoreParenImplicitAsWritten() with this definition.
643 auto IgnoreParenImplicitAsWritten = [](const Expr *E) -> const Expr * {
644 return IgnoreExprNodes(E: const_cast<Expr *>(E), Fns&: IgnoreParensSingleStep,
645 Fns&: IgnoreImplicitAsWrittenSingleStep,
646 Fns&: IgnoreElidableImplicitConstructorSingleStep);
647 };
648
649 const Expr *E = cast<ReturnStmt>(Val: St)->getRetValue();
650 const auto *CE = dyn_cast_or_null<CallExpr>(Val: IgnoreParenImplicitAsWritten(E));
651
652 if (!CE) {
653 Diag(St->getBeginLoc(), diag::err_musttail_needs_call) << &MTA;
654 return false;
655 }
656
657 if (const auto *EWC = dyn_cast<ExprWithCleanups>(Val: E)) {
658 if (EWC->cleanupsHaveSideEffects()) {
659 Diag(St->getBeginLoc(), diag::err_musttail_needs_trivial_args) << &MTA;
660 return false;
661 }
662 }
663
664 // We need to determine the full function type (including "this" type, if any)
665 // for both caller and callee.
666 struct FuncType {
667 enum {
668 ft_non_member,
669 ft_static_member,
670 ft_non_static_member,
671 ft_pointer_to_member,
672 } MemberType = ft_non_member;
673
674 QualType This;
675 const FunctionProtoType *Func;
676 const CXXMethodDecl *Method = nullptr;
677 } CallerType, CalleeType;
678
679 auto GetMethodType = [this, St, MTA](const CXXMethodDecl *CMD, FuncType &Type,
680 bool IsCallee) -> bool {
681 if (isa<CXXConstructorDecl, CXXDestructorDecl>(Val: CMD)) {
682 Diag(St->getBeginLoc(), diag::err_musttail_structors_forbidden)
683 << IsCallee << isa<CXXDestructorDecl>(CMD);
684 if (IsCallee)
685 Diag(CMD->getBeginLoc(), diag::note_musttail_structors_forbidden)
686 << isa<CXXDestructorDecl>(CMD);
687 Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
688 return false;
689 }
690 if (CMD->isStatic())
691 Type.MemberType = FuncType::ft_static_member;
692 else {
693 Type.This = CMD->getFunctionObjectParameterType();
694 Type.MemberType = FuncType::ft_non_static_member;
695 }
696 Type.Func = CMD->getType()->castAs<FunctionProtoType>();
697 return true;
698 };
699
700 const auto *CallerDecl = dyn_cast<FunctionDecl>(Val: CurContext);
701
702 // Find caller function signature.
703 if (!CallerDecl) {
704 int ContextType;
705 if (isa<BlockDecl>(Val: CurContext))
706 ContextType = 0;
707 else if (isa<ObjCMethodDecl>(Val: CurContext))
708 ContextType = 1;
709 else
710 ContextType = 2;
711 Diag(St->getBeginLoc(), diag::err_musttail_forbidden_from_this_context)
712 << &MTA << ContextType;
713 return false;
714 } else if (const auto *CMD = dyn_cast<CXXMethodDecl>(Val: CurContext)) {
715 // Caller is a class/struct method.
716 if (!GetMethodType(CMD, CallerType, false))
717 return false;
718 } else {
719 // Caller is a non-method function.
720 CallerType.Func = CallerDecl->getType()->getAs<FunctionProtoType>();
721 }
722
723 const Expr *CalleeExpr = CE->getCallee()->IgnoreParens();
724 const auto *CalleeBinOp = dyn_cast<BinaryOperator>(Val: CalleeExpr);
725 SourceLocation CalleeLoc = CE->getCalleeDecl()
726 ? CE->getCalleeDecl()->getBeginLoc()
727 : St->getBeginLoc();
728
729 // Find callee function signature.
730 if (const CXXMethodDecl *CMD =
731 dyn_cast_or_null<CXXMethodDecl>(Val: CE->getCalleeDecl())) {
732 // Call is: obj.method(), obj->method(), functor(), etc.
733 if (!GetMethodType(CMD, CalleeType, true))
734 return false;
735 } else if (CalleeBinOp && CalleeBinOp->isPtrMemOp()) {
736 // Call is: obj->*method_ptr or obj.*method_ptr
737 const auto *MPT =
738 CalleeBinOp->getRHS()->getType()->castAs<MemberPointerType>();
739 CalleeType.This = QualType(MPT->getClass(), 0);
740 CalleeType.Func = MPT->getPointeeType()->castAs<FunctionProtoType>();
741 CalleeType.MemberType = FuncType::ft_pointer_to_member;
742 } else if (isa<CXXPseudoDestructorExpr>(Val: CalleeExpr)) {
743 Diag(St->getBeginLoc(), diag::err_musttail_structors_forbidden)
744 << /* IsCallee = */ 1 << /* IsDestructor = */ 1;
745 Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
746 return false;
747 } else {
748 // Non-method function.
749 CalleeType.Func =
750 CalleeExpr->getType()->getPointeeType()->getAs<FunctionProtoType>();
751 }
752
753 // Both caller and callee must have a prototype (no K&R declarations).
754 if (!CalleeType.Func || !CallerType.Func) {
755 Diag(St->getBeginLoc(), diag::err_musttail_needs_prototype) << &MTA;
756 if (!CalleeType.Func && CE->getDirectCallee()) {
757 Diag(CE->getDirectCallee()->getBeginLoc(),
758 diag::note_musttail_fix_non_prototype);
759 }
760 if (!CallerType.Func)
761 Diag(CallerDecl->getBeginLoc(), diag::note_musttail_fix_non_prototype);
762 return false;
763 }
764
765 // Caller and callee must have matching calling conventions.
766 //
767 // Some calling conventions are physically capable of supporting tail calls
768 // even if the function types don't perfectly match. LLVM is currently too
769 // strict to allow this, but if LLVM added support for this in the future, we
770 // could exit early here and skip the remaining checks if the functions are
771 // using such a calling convention.
772 if (CallerType.Func->getCallConv() != CalleeType.Func->getCallConv()) {
773 if (const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl()))
774 Diag(St->getBeginLoc(), diag::err_musttail_callconv_mismatch)
775 << true << ND->getDeclName();
776 else
777 Diag(St->getBeginLoc(), diag::err_musttail_callconv_mismatch) << false;
778 Diag(CalleeLoc, diag::note_musttail_callconv_mismatch)
779 << FunctionType::getNameForCallConv(CallerType.Func->getCallConv())
780 << FunctionType::getNameForCallConv(CalleeType.Func->getCallConv());
781 Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
782 return false;
783 }
784
785 if (CalleeType.Func->isVariadic() || CallerType.Func->isVariadic()) {
786 Diag(St->getBeginLoc(), diag::err_musttail_no_variadic) << &MTA;
787 return false;
788 }
789
790 const auto *CalleeDecl = CE->getCalleeDecl();
791 if (CalleeDecl && CalleeDecl->hasAttr<CXX11NoReturnAttr>()) {
792 Diag(St->getBeginLoc(), diag::err_musttail_no_return) << &MTA;
793 return false;
794 }
795
796 // Caller and callee must match in whether they have a "this" parameter.
797 if (CallerType.This.isNull() != CalleeType.This.isNull()) {
798 if (const auto *ND = dyn_cast_or_null<NamedDecl>(Val: CE->getCalleeDecl())) {
799 Diag(St->getBeginLoc(), diag::err_musttail_member_mismatch)
800 << CallerType.MemberType << CalleeType.MemberType << true
801 << ND->getDeclName();
802 Diag(CalleeLoc, diag::note_musttail_callee_defined_here)
803 << ND->getDeclName();
804 } else
805 Diag(St->getBeginLoc(), diag::err_musttail_member_mismatch)
806 << CallerType.MemberType << CalleeType.MemberType << false;
807 Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
808 return false;
809 }
810
811 auto CheckTypesMatch = [this](FuncType CallerType, FuncType CalleeType,
812 PartialDiagnostic &PD) -> bool {
813 enum {
814 ft_different_class,
815 ft_parameter_arity,
816 ft_parameter_mismatch,
817 ft_return_type,
818 };
819
820 auto DoTypesMatch = [this, &PD](QualType A, QualType B,
821 unsigned Select) -> bool {
822 if (!Context.hasSimilarType(T1: A, T2: B)) {
823 PD << Select << A.getUnqualifiedType() << B.getUnqualifiedType();
824 return false;
825 }
826 return true;
827 };
828
829 if (!CallerType.This.isNull() &&
830 !DoTypesMatch(CallerType.This, CalleeType.This, ft_different_class))
831 return false;
832
833 if (!DoTypesMatch(CallerType.Func->getReturnType(),
834 CalleeType.Func->getReturnType(), ft_return_type))
835 return false;
836
837 if (CallerType.Func->getNumParams() != CalleeType.Func->getNumParams()) {
838 PD << ft_parameter_arity << CallerType.Func->getNumParams()
839 << CalleeType.Func->getNumParams();
840 return false;
841 }
842
843 ArrayRef<QualType> CalleeParams = CalleeType.Func->getParamTypes();
844 ArrayRef<QualType> CallerParams = CallerType.Func->getParamTypes();
845 size_t N = CallerType.Func->getNumParams();
846 for (size_t I = 0; I < N; I++) {
847 if (!DoTypesMatch(CalleeParams[I], CallerParams[I],
848 ft_parameter_mismatch)) {
849 PD << static_cast<int>(I) + 1;
850 return false;
851 }
852 }
853
854 return true;
855 };
856
857 PartialDiagnostic PD = PDiag(diag::note_musttail_mismatch);
858 if (!CheckTypesMatch(CallerType, CalleeType, PD)) {
859 if (const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl()))
860 Diag(St->getBeginLoc(), diag::err_musttail_mismatch)
861 << true << ND->getDeclName();
862 else
863 Diag(St->getBeginLoc(), diag::err_musttail_mismatch) << false;
864 Diag(Loc: CalleeLoc, PD);
865 Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
866 return false;
867 }
868
869 return true;
870}
871
872namespace {
873class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
874 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
875 Sema &SemaRef;
876public:
877 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
878 void VisitBinaryOperator(BinaryOperator *E) {
879 if (E->getOpcode() == BO_Comma)
880 SemaRef.DiagnoseCommaOperator(LHS: E->getLHS(), Loc: E->getExprLoc());
881 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
882 }
883};
884}
885
886StmtResult Sema::ActOnIfStmt(SourceLocation IfLoc,
887 IfStatementKind StatementKind,
888 SourceLocation LParenLoc, Stmt *InitStmt,
889 ConditionResult Cond, SourceLocation RParenLoc,
890 Stmt *thenStmt, SourceLocation ElseLoc,
891 Stmt *elseStmt) {
892 if (Cond.isInvalid())
893 return StmtError();
894
895 bool ConstevalOrNegatedConsteval =
896 StatementKind == IfStatementKind::ConstevalNonNegated ||
897 StatementKind == IfStatementKind::ConstevalNegated;
898
899 Expr *CondExpr = Cond.get().second;
900 assert((CondExpr || ConstevalOrNegatedConsteval) &&
901 "If statement: missing condition");
902 // Only call the CommaVisitor when not C89 due to differences in scope flags.
903 if (CondExpr && (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
904 !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
905 CommaVisitor(*this).Visit(CondExpr);
906
907 if (!ConstevalOrNegatedConsteval && !elseStmt)
908 DiagnoseEmptyStmtBody(RParenLoc, thenStmt, diag::warn_empty_if_body);
909
910 if (ConstevalOrNegatedConsteval ||
911 StatementKind == IfStatementKind::Constexpr) {
912 auto DiagnoseLikelihood = [&](const Stmt *S) {
913 if (const Attr *A = Stmt::getLikelihoodAttr(S)) {
914 Diags.Report(A->getLocation(),
915 diag::warn_attribute_has_no_effect_on_compile_time_if)
916 << A << ConstevalOrNegatedConsteval << A->getRange();
917 Diags.Report(IfLoc,
918 diag::note_attribute_has_no_effect_on_compile_time_if_here)
919 << ConstevalOrNegatedConsteval
920 << SourceRange(IfLoc, (ConstevalOrNegatedConsteval
921 ? thenStmt->getBeginLoc()
922 : LParenLoc)
923 .getLocWithOffset(-1));
924 }
925 };
926 DiagnoseLikelihood(thenStmt);
927 DiagnoseLikelihood(elseStmt);
928 } else {
929 std::tuple<bool, const Attr *, const Attr *> LHC =
930 Stmt::determineLikelihoodConflict(Then: thenStmt, Else: elseStmt);
931 if (std::get<0>(t&: LHC)) {
932 const Attr *ThenAttr = std::get<1>(t&: LHC);
933 const Attr *ElseAttr = std::get<2>(t&: LHC);
934 Diags.Report(ThenAttr->getLocation(),
935 diag::warn_attributes_likelihood_ifstmt_conflict)
936 << ThenAttr << ThenAttr->getRange();
937 Diags.Report(ElseAttr->getLocation(), diag::note_conflicting_attribute)
938 << ElseAttr << ElseAttr->getRange();
939 }
940 }
941
942 if (ConstevalOrNegatedConsteval) {
943 bool Immediate = ExprEvalContexts.back().Context ==
944 ExpressionEvaluationContext::ImmediateFunctionContext;
945 if (CurContext->isFunctionOrMethod()) {
946 const auto *FD =
947 dyn_cast<FunctionDecl>(Val: Decl::castFromDeclContext(CurContext));
948 if (FD && FD->isImmediateFunction())
949 Immediate = true;
950 }
951 if (isUnevaluatedContext() || Immediate)
952 Diags.Report(IfLoc, diag::warn_consteval_if_always_true) << Immediate;
953 }
954
955 return BuildIfStmt(IfLoc, StatementKind, LParenLoc, InitStmt, Cond, RParenLoc,
956 ThenVal: thenStmt, ElseLoc, ElseVal: elseStmt);
957}
958
959StmtResult Sema::BuildIfStmt(SourceLocation IfLoc,
960 IfStatementKind StatementKind,
961 SourceLocation LParenLoc, Stmt *InitStmt,
962 ConditionResult Cond, SourceLocation RParenLoc,
963 Stmt *thenStmt, SourceLocation ElseLoc,
964 Stmt *elseStmt) {
965 if (Cond.isInvalid())
966 return StmtError();
967
968 if (StatementKind != IfStatementKind::Ordinary ||
969 isa<ObjCAvailabilityCheckExpr>(Val: Cond.get().second))
970 setFunctionHasBranchProtectedScope();
971
972 return IfStmt::Create(Ctx: Context, IL: IfLoc, Kind: StatementKind, Init: InitStmt,
973 Var: Cond.get().first, Cond: Cond.get().second, LPL: LParenLoc,
974 RPL: RParenLoc, Then: thenStmt, EL: ElseLoc, Else: elseStmt);
975}
976
977namespace {
978 struct CaseCompareFunctor {
979 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
980 const llvm::APSInt &RHS) {
981 return LHS.first < RHS;
982 }
983 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
984 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
985 return LHS.first < RHS.first;
986 }
987 bool operator()(const llvm::APSInt &LHS,
988 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
989 return LHS < RHS.first;
990 }
991 };
992}
993
994/// CmpCaseVals - Comparison predicate for sorting case values.
995///
996static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
997 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
998 if (lhs.first < rhs.first)
999 return true;
1000
1001 if (lhs.first == rhs.first &&
1002 lhs.second->getCaseLoc() < rhs.second->getCaseLoc())
1003 return true;
1004 return false;
1005}
1006
1007/// CmpEnumVals - Comparison predicate for sorting enumeration values.
1008///
1009static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
1010 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
1011{
1012 return lhs.first < rhs.first;
1013}
1014
1015/// EqEnumVals - Comparison preficate for uniqing enumeration values.
1016///
1017static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
1018 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
1019{
1020 return lhs.first == rhs.first;
1021}
1022
1023/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
1024/// potentially integral-promoted expression @p expr.
1025static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
1026 if (const auto *FE = dyn_cast<FullExpr>(Val: E))
1027 E = FE->getSubExpr();
1028 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(Val: E)) {
1029 if (ImpCast->getCastKind() != CK_IntegralCast) break;
1030 E = ImpCast->getSubExpr();
1031 }
1032 return E->getType();
1033}
1034
1035ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
1036 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
1037 Expr *Cond;
1038
1039 public:
1040 SwitchConvertDiagnoser(Expr *Cond)
1041 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
1042 Cond(Cond) {}
1043
1044 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1045 QualType T) override {
1046 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
1047 }
1048
1049 SemaDiagnosticBuilder diagnoseIncomplete(
1050 Sema &S, SourceLocation Loc, QualType T) override {
1051 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
1052 << T << Cond->getSourceRange();
1053 }
1054
1055 SemaDiagnosticBuilder diagnoseExplicitConv(
1056 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1057 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
1058 }
1059
1060 SemaDiagnosticBuilder noteExplicitConv(
1061 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1062 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
1063 << ConvTy->isEnumeralType() << ConvTy;
1064 }
1065
1066 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
1067 QualType T) override {
1068 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
1069 }
1070
1071 SemaDiagnosticBuilder noteAmbiguous(
1072 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1073 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
1074 << ConvTy->isEnumeralType() << ConvTy;
1075 }
1076
1077 SemaDiagnosticBuilder diagnoseConversion(
1078 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1079 llvm_unreachable("conversion functions are permitted");
1080 }
1081 } SwitchDiagnoser(Cond);
1082
1083 ExprResult CondResult =
1084 PerformContextualImplicitConversion(Loc: SwitchLoc, FromE: Cond, Converter&: SwitchDiagnoser);
1085 if (CondResult.isInvalid())
1086 return ExprError();
1087
1088 // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
1089 // failed and produced a diagnostic.
1090 Cond = CondResult.get();
1091 if (!Cond->isTypeDependent() &&
1092 !Cond->getType()->isIntegralOrEnumerationType())
1093 return ExprError();
1094
1095 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
1096 return UsualUnaryConversions(E: Cond);
1097}
1098
1099StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
1100 SourceLocation LParenLoc,
1101 Stmt *InitStmt, ConditionResult Cond,
1102 SourceLocation RParenLoc) {
1103 Expr *CondExpr = Cond.get().second;
1104 assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
1105
1106 if (CondExpr && !CondExpr->isTypeDependent()) {
1107 // We have already converted the expression to an integral or enumeration
1108 // type, when we parsed the switch condition. There are cases where we don't
1109 // have an appropriate type, e.g. a typo-expr Cond was corrected to an
1110 // inappropriate-type expr, we just return an error.
1111 if (!CondExpr->getType()->isIntegralOrEnumerationType())
1112 return StmtError();
1113 if (CondExpr->isKnownToHaveBooleanValue()) {
1114 // switch(bool_expr) {...} is often a programmer error, e.g.
1115 // switch(n && mask) { ... } // Doh - should be "n & mask".
1116 // One can always use an if statement instead of switch(bool_expr).
1117 Diag(SwitchLoc, diag::warn_bool_switch_condition)
1118 << CondExpr->getSourceRange();
1119 }
1120 }
1121
1122 setFunctionHasBranchIntoScope();
1123
1124 auto *SS = SwitchStmt::Create(Ctx: Context, Init: InitStmt, Var: Cond.get().first, Cond: CondExpr,
1125 LParenLoc, RParenLoc);
1126 getCurFunction()->SwitchStack.push_back(
1127 Elt: FunctionScopeInfo::SwitchInfo(SS, false));
1128 return SS;
1129}
1130
1131static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
1132 Val = Val.extOrTrunc(width: BitWidth);
1133 Val.setIsSigned(IsSigned);
1134}
1135
1136/// Check the specified case value is in range for the given unpromoted switch
1137/// type.
1138static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
1139 unsigned UnpromotedWidth, bool UnpromotedSign) {
1140 // In C++11 onwards, this is checked by the language rules.
1141 if (S.getLangOpts().CPlusPlus11)
1142 return;
1143
1144 // If the case value was signed and negative and the switch expression is
1145 // unsigned, don't bother to warn: this is implementation-defined behavior.
1146 // FIXME: Introduce a second, default-ignored warning for this case?
1147 if (UnpromotedWidth < Val.getBitWidth()) {
1148 llvm::APSInt ConvVal(Val);
1149 AdjustAPSInt(Val&: ConvVal, BitWidth: UnpromotedWidth, IsSigned: UnpromotedSign);
1150 AdjustAPSInt(Val&: ConvVal, BitWidth: Val.getBitWidth(), IsSigned: Val.isSigned());
1151 // FIXME: Use different diagnostics for overflow in conversion to promoted
1152 // type versus "switch expression cannot have this value". Use proper
1153 // IntRange checking rather than just looking at the unpromoted type here.
1154 if (ConvVal != Val)
1155 S.Diag(Loc, diag::warn_case_value_overflow) << toString(Val, 10)
1156 << toString(ConvVal, 10);
1157 }
1158}
1159
1160typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
1161
1162/// Returns true if we should emit a diagnostic about this case expression not
1163/// being a part of the enum used in the switch controlling expression.
1164static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
1165 const EnumDecl *ED,
1166 const Expr *CaseExpr,
1167 EnumValsTy::iterator &EI,
1168 EnumValsTy::iterator &EIEnd,
1169 const llvm::APSInt &Val) {
1170 if (!ED->isClosed())
1171 return false;
1172
1173 if (const DeclRefExpr *DRE =
1174 dyn_cast<DeclRefExpr>(Val: CaseExpr->IgnoreParenImpCasts())) {
1175 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: DRE->getDecl())) {
1176 QualType VarType = VD->getType();
1177 QualType EnumType = S.Context.getTypeDeclType(ED);
1178 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
1179 S.Context.hasSameUnqualifiedType(T1: EnumType, T2: VarType))
1180 return false;
1181 }
1182 }
1183
1184 if (ED->hasAttr<FlagEnumAttr>())
1185 return !S.IsValueInFlagEnum(ED, Val, AllowMask: false);
1186
1187 while (EI != EIEnd && EI->first < Val)
1188 EI++;
1189
1190 if (EI != EIEnd && EI->first == Val)
1191 return false;
1192
1193 return true;
1194}
1195
1196static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
1197 const Expr *Case) {
1198 QualType CondType = Cond->getType();
1199 QualType CaseType = Case->getType();
1200
1201 const EnumType *CondEnumType = CondType->getAs<EnumType>();
1202 const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
1203 if (!CondEnumType || !CaseEnumType)
1204 return;
1205
1206 // Ignore anonymous enums.
1207 if (!CondEnumType->getDecl()->getIdentifier() &&
1208 !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
1209 return;
1210 if (!CaseEnumType->getDecl()->getIdentifier() &&
1211 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
1212 return;
1213
1214 if (S.Context.hasSameUnqualifiedType(T1: CondType, T2: CaseType))
1215 return;
1216
1217 S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
1218 << CondType << CaseType << Cond->getSourceRange()
1219 << Case->getSourceRange();
1220}
1221
1222StmtResult
1223Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
1224 Stmt *BodyStmt) {
1225 SwitchStmt *SS = cast<SwitchStmt>(Val: Switch);
1226 bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
1227 assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
1228 "switch stack missing push/pop!");
1229
1230 getCurFunction()->SwitchStack.pop_back();
1231
1232 if (!BodyStmt) return StmtError();
1233 SS->setBody(S: BodyStmt, SL: SwitchLoc);
1234
1235 Expr *CondExpr = SS->getCond();
1236 if (!CondExpr) return StmtError();
1237
1238 QualType CondType = CondExpr->getType();
1239
1240 // C++ 6.4.2.p2:
1241 // Integral promotions are performed (on the switch condition).
1242 //
1243 // A case value unrepresentable by the original switch condition
1244 // type (before the promotion) doesn't make sense, even when it can
1245 // be represented by the promoted type. Therefore we need to find
1246 // the pre-promotion type of the switch condition.
1247 const Expr *CondExprBeforePromotion = CondExpr;
1248 QualType CondTypeBeforePromotion =
1249 GetTypeBeforeIntegralPromotion(E&: CondExprBeforePromotion);
1250
1251 // Get the bitwidth of the switched-on value after promotions. We must
1252 // convert the integer case values to this width before comparison.
1253 bool HasDependentValue
1254 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
1255 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(T: CondType);
1256 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
1257
1258 // Get the width and signedness that the condition might actually have, for
1259 // warning purposes.
1260 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
1261 // type.
1262 unsigned CondWidthBeforePromotion
1263 = HasDependentValue ? 0 : Context.getIntWidth(T: CondTypeBeforePromotion);
1264 bool CondIsSignedBeforePromotion
1265 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
1266
1267 // Accumulate all of the case values in a vector so that we can sort them
1268 // and detect duplicates. This vector contains the APInt for the case after
1269 // it has been converted to the condition type.
1270 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
1271 CaseValsTy CaseVals;
1272
1273 // Keep track of any GNU case ranges we see. The APSInt is the low value.
1274 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
1275 CaseRangesTy CaseRanges;
1276
1277 DefaultStmt *TheDefaultStmt = nullptr;
1278
1279 bool CaseListIsErroneous = false;
1280
1281 // FIXME: We'd better diagnose missing or duplicate default labels even
1282 // in the dependent case. Because default labels themselves are never
1283 // dependent.
1284 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
1285 SC = SC->getNextSwitchCase()) {
1286
1287 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(Val: SC)) {
1288 if (TheDefaultStmt) {
1289 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
1290 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
1291
1292 // FIXME: Remove the default statement from the switch block so that
1293 // we'll return a valid AST. This requires recursing down the AST and
1294 // finding it, not something we are set up to do right now. For now,
1295 // just lop the entire switch stmt out of the AST.
1296 CaseListIsErroneous = true;
1297 }
1298 TheDefaultStmt = DS;
1299
1300 } else {
1301 CaseStmt *CS = cast<CaseStmt>(Val: SC);
1302
1303 Expr *Lo = CS->getLHS();
1304
1305 if (Lo->isValueDependent()) {
1306 HasDependentValue = true;
1307 break;
1308 }
1309
1310 // We already verified that the expression has a constant value;
1311 // get that value (prior to conversions).
1312 const Expr *LoBeforePromotion = Lo;
1313 GetTypeBeforeIntegralPromotion(E&: LoBeforePromotion);
1314 llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Ctx: Context);
1315
1316 // Check the unconverted value is within the range of possible values of
1317 // the switch expression.
1318 checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
1319 CondIsSignedBeforePromotion);
1320
1321 // FIXME: This duplicates the check performed for warn_not_in_enum below.
1322 checkEnumTypesInSwitchStmt(S&: *this, Cond: CondExprBeforePromotion,
1323 Case: LoBeforePromotion);
1324
1325 // Convert the value to the same width/sign as the condition.
1326 AdjustAPSInt(Val&: LoVal, BitWidth: CondWidth, IsSigned: CondIsSigned);
1327
1328 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
1329 if (CS->getRHS()) {
1330 if (CS->getRHS()->isValueDependent()) {
1331 HasDependentValue = true;
1332 break;
1333 }
1334 CaseRanges.push_back(x: std::make_pair(x&: LoVal, y&: CS));
1335 } else
1336 CaseVals.push_back(Elt: std::make_pair(x&: LoVal, y&: CS));
1337 }
1338 }
1339
1340 if (!HasDependentValue) {
1341 // If we don't have a default statement, check whether the
1342 // condition is constant.
1343 llvm::APSInt ConstantCondValue;
1344 bool HasConstantCond = false;
1345 if (!TheDefaultStmt) {
1346 Expr::EvalResult Result;
1347 HasConstantCond = CondExpr->EvaluateAsInt(Result, Ctx: Context,
1348 AllowSideEffects: Expr::SE_AllowSideEffects);
1349 if (Result.Val.isInt())
1350 ConstantCondValue = Result.Val.getInt();
1351 assert(!HasConstantCond ||
1352 (ConstantCondValue.getBitWidth() == CondWidth &&
1353 ConstantCondValue.isSigned() == CondIsSigned));
1354 Diag(SwitchLoc, diag::warn_switch_default);
1355 }
1356 bool ShouldCheckConstantCond = HasConstantCond;
1357
1358 // Sort all the scalar case values so we can easily detect duplicates.
1359 llvm::stable_sort(Range&: CaseVals, C: CmpCaseVals);
1360
1361 if (!CaseVals.empty()) {
1362 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
1363 if (ShouldCheckConstantCond &&
1364 CaseVals[i].first == ConstantCondValue)
1365 ShouldCheckConstantCond = false;
1366
1367 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
1368 // If we have a duplicate, report it.
1369 // First, determine if either case value has a name
1370 StringRef PrevString, CurrString;
1371 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
1372 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
1373 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Val: PrevCase)) {
1374 PrevString = DeclRef->getDecl()->getName();
1375 }
1376 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Val: CurrCase)) {
1377 CurrString = DeclRef->getDecl()->getName();
1378 }
1379 SmallString<16> CaseValStr;
1380 CaseVals[i-1].first.toString(Str&: CaseValStr);
1381
1382 if (PrevString == CurrString)
1383 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
1384 diag::err_duplicate_case)
1385 << (PrevString.empty() ? CaseValStr.str() : PrevString);
1386 else
1387 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
1388 diag::err_duplicate_case_differing_expr)
1389 << (PrevString.empty() ? CaseValStr.str() : PrevString)
1390 << (CurrString.empty() ? CaseValStr.str() : CurrString)
1391 << CaseValStr;
1392
1393 Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
1394 diag::note_duplicate_case_prev);
1395 // FIXME: We really want to remove the bogus case stmt from the
1396 // substmt, but we have no way to do this right now.
1397 CaseListIsErroneous = true;
1398 }
1399 }
1400 }
1401
1402 // Detect duplicate case ranges, which usually don't exist at all in
1403 // the first place.
1404 if (!CaseRanges.empty()) {
1405 // Sort all the case ranges by their low value so we can easily detect
1406 // overlaps between ranges.
1407 llvm::stable_sort(Range&: CaseRanges);
1408
1409 // Scan the ranges, computing the high values and removing empty ranges.
1410 std::vector<llvm::APSInt> HiVals;
1411 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1412 llvm::APSInt &LoVal = CaseRanges[i].first;
1413 CaseStmt *CR = CaseRanges[i].second;
1414 Expr *Hi = CR->getRHS();
1415
1416 const Expr *HiBeforePromotion = Hi;
1417 GetTypeBeforeIntegralPromotion(E&: HiBeforePromotion);
1418 llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Ctx: Context);
1419
1420 // Check the unconverted value is within the range of possible values of
1421 // the switch expression.
1422 checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
1423 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1424
1425 // Convert the value to the same width/sign as the condition.
1426 AdjustAPSInt(Val&: HiVal, BitWidth: CondWidth, IsSigned: CondIsSigned);
1427
1428 // If the low value is bigger than the high value, the case is empty.
1429 if (LoVal > HiVal) {
1430 Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
1431 << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
1432 CaseRanges.erase(position: CaseRanges.begin()+i);
1433 --i;
1434 --e;
1435 continue;
1436 }
1437
1438 if (ShouldCheckConstantCond &&
1439 LoVal <= ConstantCondValue &&
1440 ConstantCondValue <= HiVal)
1441 ShouldCheckConstantCond = false;
1442
1443 HiVals.push_back(x: HiVal);
1444 }
1445
1446 // Rescan the ranges, looking for overlap with singleton values and other
1447 // ranges. Since the range list is sorted, we only need to compare case
1448 // ranges with their neighbors.
1449 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1450 llvm::APSInt &CRLo = CaseRanges[i].first;
1451 llvm::APSInt &CRHi = HiVals[i];
1452 CaseStmt *CR = CaseRanges[i].second;
1453
1454 // Check to see whether the case range overlaps with any
1455 // singleton cases.
1456 CaseStmt *OverlapStmt = nullptr;
1457 llvm::APSInt OverlapVal(32);
1458
1459 // Find the smallest value >= the lower bound. If I is in the
1460 // case range, then we have overlap.
1461 CaseValsTy::iterator I =
1462 llvm::lower_bound(Range&: CaseVals, Value&: CRLo, C: CaseCompareFunctor());
1463 if (I != CaseVals.end() && I->first < CRHi) {
1464 OverlapVal = I->first; // Found overlap with scalar.
1465 OverlapStmt = I->second;
1466 }
1467
1468 // Find the smallest value bigger than the upper bound.
1469 I = std::upper_bound(first: I, last: CaseVals.end(), val: CRHi, comp: CaseCompareFunctor());
1470 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1471 OverlapVal = (I-1)->first; // Found overlap with scalar.
1472 OverlapStmt = (I-1)->second;
1473 }
1474
1475 // Check to see if this case stmt overlaps with the subsequent
1476 // case range.
1477 if (i && CRLo <= HiVals[i-1]) {
1478 OverlapVal = HiVals[i-1]; // Found overlap with range.
1479 OverlapStmt = CaseRanges[i-1].second;
1480 }
1481
1482 if (OverlapStmt) {
1483 // If we have a duplicate, report it.
1484 Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
1485 << toString(OverlapVal, 10);
1486 Diag(OverlapStmt->getLHS()->getBeginLoc(),
1487 diag::note_duplicate_case_prev);
1488 // FIXME: We really want to remove the bogus case stmt from the
1489 // substmt, but we have no way to do this right now.
1490 CaseListIsErroneous = true;
1491 }
1492 }
1493 }
1494
1495 // Complain if we have a constant condition and we didn't find a match.
1496 if (!CaseListIsErroneous && !CaseListIsIncomplete &&
1497 ShouldCheckConstantCond) {
1498 // TODO: it would be nice if we printed enums as enums, chars as
1499 // chars, etc.
1500 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1501 << toString(ConstantCondValue, 10)
1502 << CondExpr->getSourceRange();
1503 }
1504
1505 // Check to see if switch is over an Enum and handles all of its
1506 // values. We only issue a warning if there is not 'default:', but
1507 // we still do the analysis to preserve this information in the AST
1508 // (which can be used by flow-based analyes).
1509 //
1510 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1511
1512 // If switch has default case, then ignore it.
1513 if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
1514 ET && ET->getDecl()->isCompleteDefinition() &&
1515 !ET->getDecl()->enumerators().empty()) {
1516 const EnumDecl *ED = ET->getDecl();
1517 EnumValsTy EnumVals;
1518
1519 // Gather all enum values, set their type and sort them,
1520 // allowing easier comparison with CaseVals.
1521 for (auto *EDI : ED->enumerators()) {
1522 llvm::APSInt Val = EDI->getInitVal();
1523 AdjustAPSInt(Val, BitWidth: CondWidth, IsSigned: CondIsSigned);
1524 EnumVals.push_back(Elt: std::make_pair(x&: Val, y&: EDI));
1525 }
1526 llvm::stable_sort(Range&: EnumVals, C: CmpEnumVals);
1527 auto EI = EnumVals.begin(), EIEnd =
1528 std::unique(first: EnumVals.begin(), last: EnumVals.end(), binary_pred: EqEnumVals);
1529
1530 // See which case values aren't in enum.
1531 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1532 CI != CaseVals.end(); CI++) {
1533 Expr *CaseExpr = CI->second->getLHS();
1534 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1535 CI->first))
1536 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1537 << CondTypeBeforePromotion;
1538 }
1539
1540 // See which of case ranges aren't in enum
1541 EI = EnumVals.begin();
1542 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1543 RI != CaseRanges.end(); RI++) {
1544 Expr *CaseExpr = RI->second->getLHS();
1545 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1546 RI->first))
1547 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1548 << CondTypeBeforePromotion;
1549
1550 llvm::APSInt Hi =
1551 RI->second->getRHS()->EvaluateKnownConstInt(Ctx: Context);
1552 AdjustAPSInt(Val&: Hi, BitWidth: CondWidth, IsSigned: CondIsSigned);
1553
1554 CaseExpr = RI->second->getRHS();
1555 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1556 Hi))
1557 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1558 << CondTypeBeforePromotion;
1559 }
1560
1561 // Check which enum vals aren't in switch
1562 auto CI = CaseVals.begin();
1563 auto RI = CaseRanges.begin();
1564 bool hasCasesNotInSwitch = false;
1565
1566 SmallVector<DeclarationName,8> UnhandledNames;
1567
1568 for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
1569 // Don't warn about omitted unavailable EnumConstantDecls.
1570 switch (EI->second->getAvailability()) {
1571 case AR_Deprecated:
1572 // Omitting a deprecated constant is ok; it should never materialize.
1573 case AR_Unavailable:
1574 continue;
1575
1576 case AR_NotYetIntroduced:
1577 // Partially available enum constants should be present. Note that we
1578 // suppress -Wunguarded-availability diagnostics for such uses.
1579 case AR_Available:
1580 break;
1581 }
1582
1583 if (EI->second->hasAttr<UnusedAttr>())
1584 continue;
1585
1586 // Drop unneeded case values
1587 while (CI != CaseVals.end() && CI->first < EI->first)
1588 CI++;
1589
1590 if (CI != CaseVals.end() && CI->first == EI->first)
1591 continue;
1592
1593 // Drop unneeded case ranges
1594 for (; RI != CaseRanges.end(); RI++) {
1595 llvm::APSInt Hi =
1596 RI->second->getRHS()->EvaluateKnownConstInt(Ctx: Context);
1597 AdjustAPSInt(Val&: Hi, BitWidth: CondWidth, IsSigned: CondIsSigned);
1598 if (EI->first <= Hi)
1599 break;
1600 }
1601
1602 if (RI == CaseRanges.end() || EI->first < RI->first) {
1603 hasCasesNotInSwitch = true;
1604 UnhandledNames.push_back(Elt: EI->second->getDeclName());
1605 }
1606 }
1607
1608 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
1609 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1610
1611 // Produce a nice diagnostic if multiple values aren't handled.
1612 if (!UnhandledNames.empty()) {
1613 auto DB = Diag(CondExpr->getExprLoc(), TheDefaultStmt
1614 ? diag::warn_def_missing_case
1615 : diag::warn_missing_case)
1616 << CondExpr->getSourceRange() << (int)UnhandledNames.size();
1617
1618 for (size_t I = 0, E = std::min(a: UnhandledNames.size(), b: (size_t)3);
1619 I != E; ++I)
1620 DB << UnhandledNames[I];
1621 }
1622
1623 if (!hasCasesNotInSwitch)
1624 SS->setAllEnumCasesCovered();
1625 }
1626 }
1627
1628 if (BodyStmt)
1629 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt,
1630 diag::warn_empty_switch_body);
1631
1632 // FIXME: If the case list was broken is some way, we don't have a good system
1633 // to patch it up. Instead, just return the whole substmt as broken.
1634 if (CaseListIsErroneous)
1635 return StmtError();
1636
1637 return SS;
1638}
1639
1640void
1641Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1642 Expr *SrcExpr) {
1643 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1644 return;
1645
1646 if (const EnumType *ET = DstType->getAs<EnumType>())
1647 if (!Context.hasSameUnqualifiedType(T1: SrcType, T2: DstType) &&
1648 SrcType->isIntegerType()) {
1649 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1650 SrcExpr->isIntegerConstantExpr(Ctx: Context)) {
1651 // Get the bitwidth of the enum value before promotions.
1652 unsigned DstWidth = Context.getIntWidth(T: DstType);
1653 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1654
1655 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Ctx: Context);
1656 AdjustAPSInt(Val&: RhsVal, BitWidth: DstWidth, IsSigned: DstIsSigned);
1657 const EnumDecl *ED = ET->getDecl();
1658
1659 if (!ED->isClosed())
1660 return;
1661
1662 if (ED->hasAttr<FlagEnumAttr>()) {
1663 if (!IsValueInFlagEnum(ED, RhsVal, true))
1664 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1665 << DstType.getUnqualifiedType();
1666 } else {
1667 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1668 EnumValsTy;
1669 EnumValsTy EnumVals;
1670
1671 // Gather all enum values, set their type and sort them,
1672 // allowing easier comparison with rhs constant.
1673 for (auto *EDI : ED->enumerators()) {
1674 llvm::APSInt Val = EDI->getInitVal();
1675 AdjustAPSInt(Val, BitWidth: DstWidth, IsSigned: DstIsSigned);
1676 EnumVals.push_back(Elt: std::make_pair(x&: Val, y&: EDI));
1677 }
1678 if (EnumVals.empty())
1679 return;
1680 llvm::stable_sort(Range&: EnumVals, C: CmpEnumVals);
1681 EnumValsTy::iterator EIend =
1682 std::unique(first: EnumVals.begin(), last: EnumVals.end(), binary_pred: EqEnumVals);
1683
1684 // See which values aren't in the enum.
1685 EnumValsTy::const_iterator EI = EnumVals.begin();
1686 while (EI != EIend && EI->first < RhsVal)
1687 EI++;
1688 if (EI == EIend || EI->first != RhsVal) {
1689 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1690 << DstType.getUnqualifiedType();
1691 }
1692 }
1693 }
1694 }
1695}
1696
1697StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc,
1698 SourceLocation LParenLoc, ConditionResult Cond,
1699 SourceLocation RParenLoc, Stmt *Body) {
1700 if (Cond.isInvalid())
1701 return StmtError();
1702
1703 auto CondVal = Cond.get();
1704 CheckBreakContinueBinding(E: CondVal.second);
1705
1706 if (CondVal.second &&
1707 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1708 CommaVisitor(*this).Visit(CondVal.second);
1709
1710 if (isa<NullStmt>(Val: Body))
1711 getCurCompoundScope().setHasEmptyLoopBodies();
1712
1713 return WhileStmt::Create(Ctx: Context, Var: CondVal.first, Cond: CondVal.second, Body,
1714 WL: WhileLoc, LParenLoc, RParenLoc);
1715}
1716
1717StmtResult
1718Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1719 SourceLocation WhileLoc, SourceLocation CondLParen,
1720 Expr *Cond, SourceLocation CondRParen) {
1721 assert(Cond && "ActOnDoStmt(): missing expression");
1722
1723 CheckBreakContinueBinding(E: Cond);
1724 ExprResult CondResult = CheckBooleanCondition(Loc: DoLoc, E: Cond);
1725 if (CondResult.isInvalid())
1726 return StmtError();
1727 Cond = CondResult.get();
1728
1729 CondResult = ActOnFinishFullExpr(Expr: Cond, CC: DoLoc, /*DiscardedValue*/ false);
1730 if (CondResult.isInvalid())
1731 return StmtError();
1732 Cond = CondResult.get();
1733
1734 // Only call the CommaVisitor for C89 due to differences in scope flags.
1735 if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus &&
1736 !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc()))
1737 CommaVisitor(*this).Visit(Cond);
1738
1739 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1740}
1741
1742namespace {
1743 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1744 using DeclSetVector = llvm::SmallSetVector<VarDecl *, 8>;
1745
1746 // This visitor will traverse a conditional statement and store all
1747 // the evaluated decls into a vector. Simple is set to true if none
1748 // of the excluded constructs are used.
1749 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1750 DeclSetVector &Decls;
1751 SmallVectorImpl<SourceRange> &Ranges;
1752 bool Simple;
1753 public:
1754 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1755
1756 DeclExtractor(Sema &S, DeclSetVector &Decls,
1757 SmallVectorImpl<SourceRange> &Ranges) :
1758 Inherited(S.Context),
1759 Decls(Decls),
1760 Ranges(Ranges),
1761 Simple(true) {}
1762
1763 bool isSimple() { return Simple; }
1764
1765 // Replaces the method in EvaluatedExprVisitor.
1766 void VisitMemberExpr(MemberExpr* E) {
1767 Simple = false;
1768 }
1769
1770 // Any Stmt not explicitly listed will cause the condition to be marked
1771 // complex.
1772 void VisitStmt(Stmt *S) { Simple = false; }
1773
1774 void VisitBinaryOperator(BinaryOperator *E) {
1775 Visit(E->getLHS());
1776 Visit(E->getRHS());
1777 }
1778
1779 void VisitCastExpr(CastExpr *E) {
1780 Visit(E->getSubExpr());
1781 }
1782
1783 void VisitUnaryOperator(UnaryOperator *E) {
1784 // Skip checking conditionals with derefernces.
1785 if (E->getOpcode() == UO_Deref)
1786 Simple = false;
1787 else
1788 Visit(E->getSubExpr());
1789 }
1790
1791 void VisitConditionalOperator(ConditionalOperator *E) {
1792 Visit(E->getCond());
1793 Visit(E->getTrueExpr());
1794 Visit(E->getFalseExpr());
1795 }
1796
1797 void VisitParenExpr(ParenExpr *E) {
1798 Visit(E->getSubExpr());
1799 }
1800
1801 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1802 Visit(E->getOpaqueValue()->getSourceExpr());
1803 Visit(E->getFalseExpr());
1804 }
1805
1806 void VisitIntegerLiteral(IntegerLiteral *E) { }
1807 void VisitFloatingLiteral(FloatingLiteral *E) { }
1808 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1809 void VisitCharacterLiteral(CharacterLiteral *E) { }
1810 void VisitGNUNullExpr(GNUNullExpr *E) { }
1811 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1812
1813 void VisitDeclRefExpr(DeclRefExpr *E) {
1814 VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl());
1815 if (!VD) {
1816 // Don't allow unhandled Decl types.
1817 Simple = false;
1818 return;
1819 }
1820
1821 Ranges.push_back(Elt: E->getSourceRange());
1822
1823 Decls.insert(X: VD);
1824 }
1825
1826 }; // end class DeclExtractor
1827
1828 // DeclMatcher checks to see if the decls are used in a non-evaluated
1829 // context.
1830 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1831 DeclSetVector &Decls;
1832 bool FoundDecl;
1833
1834 public:
1835 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1836
1837 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
1838 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1839 if (!Statement) return;
1840
1841 Visit(S: Statement);
1842 }
1843
1844 void VisitReturnStmt(ReturnStmt *S) {
1845 FoundDecl = true;
1846 }
1847
1848 void VisitBreakStmt(BreakStmt *S) {
1849 FoundDecl = true;
1850 }
1851
1852 void VisitGotoStmt(GotoStmt *S) {
1853 FoundDecl = true;
1854 }
1855
1856 void VisitCastExpr(CastExpr *E) {
1857 if (E->getCastKind() == CK_LValueToRValue)
1858 CheckLValueToRValueCast(E: E->getSubExpr());
1859 else
1860 Visit(E->getSubExpr());
1861 }
1862
1863 void CheckLValueToRValueCast(Expr *E) {
1864 E = E->IgnoreParenImpCasts();
1865
1866 if (isa<DeclRefExpr>(Val: E)) {
1867 return;
1868 }
1869
1870 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
1871 Visit(CO->getCond());
1872 CheckLValueToRValueCast(E: CO->getTrueExpr());
1873 CheckLValueToRValueCast(E: CO->getFalseExpr());
1874 return;
1875 }
1876
1877 if (BinaryConditionalOperator *BCO =
1878 dyn_cast<BinaryConditionalOperator>(Val: E)) {
1879 CheckLValueToRValueCast(E: BCO->getOpaqueValue()->getSourceExpr());
1880 CheckLValueToRValueCast(E: BCO->getFalseExpr());
1881 return;
1882 }
1883
1884 Visit(E);
1885 }
1886
1887 void VisitDeclRefExpr(DeclRefExpr *E) {
1888 if (VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl()))
1889 if (Decls.count(key: VD))
1890 FoundDecl = true;
1891 }
1892
1893 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1894 // Only need to visit the semantics for POE.
1895 // SyntaticForm doesn't really use the Decal.
1896 for (auto *S : POE->semantics()) {
1897 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: S))
1898 // Look past the OVE into the expression it binds.
1899 Visit(OVE->getSourceExpr());
1900 else
1901 Visit(S);
1902 }
1903 }
1904
1905 bool FoundDeclInUse() { return FoundDecl; }
1906
1907 }; // end class DeclMatcher
1908
1909 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1910 Expr *Third, Stmt *Body) {
1911 // Condition is empty
1912 if (!Second) return;
1913
1914 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1915 Second->getBeginLoc()))
1916 return;
1917
1918 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1919 DeclSetVector Decls;
1920 SmallVector<SourceRange, 10> Ranges;
1921 DeclExtractor DE(S, Decls, Ranges);
1922 DE.Visit(Second);
1923
1924 // Don't analyze complex conditionals.
1925 if (!DE.isSimple()) return;
1926
1927 // No decls found.
1928 if (Decls.size() == 0) return;
1929
1930 // Don't warn on volatile, static, or global variables.
1931 for (auto *VD : Decls)
1932 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1933 return;
1934
1935 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1936 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1937 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1938 return;
1939
1940 // Load decl names into diagnostic.
1941 if (Decls.size() > 4) {
1942 PDiag << 0;
1943 } else {
1944 PDiag << (unsigned)Decls.size();
1945 for (auto *VD : Decls)
1946 PDiag << VD->getDeclName();
1947 }
1948
1949 for (auto Range : Ranges)
1950 PDiag << Range;
1951
1952 S.Diag(Loc: Ranges.begin()->getBegin(), PD: PDiag);
1953 }
1954
1955 // If Statement is an incemement or decrement, return true and sets the
1956 // variables Increment and DRE.
1957 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1958 DeclRefExpr *&DRE) {
1959 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Val: Statement))
1960 if (!Cleanups->cleanupsHaveSideEffects())
1961 Statement = Cleanups->getSubExpr();
1962
1963 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: Statement)) {
1964 switch (UO->getOpcode()) {
1965 default: return false;
1966 case UO_PostInc:
1967 case UO_PreInc:
1968 Increment = true;
1969 break;
1970 case UO_PostDec:
1971 case UO_PreDec:
1972 Increment = false;
1973 break;
1974 }
1975 DRE = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr());
1976 return DRE;
1977 }
1978
1979 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Val: Statement)) {
1980 FunctionDecl *FD = Call->getDirectCallee();
1981 if (!FD || !FD->isOverloadedOperator()) return false;
1982 switch (FD->getOverloadedOperator()) {
1983 default: return false;
1984 case OO_PlusPlus:
1985 Increment = true;
1986 break;
1987 case OO_MinusMinus:
1988 Increment = false;
1989 break;
1990 }
1991 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1992 return DRE;
1993 }
1994
1995 return false;
1996 }
1997
1998 // A visitor to determine if a continue or break statement is a
1999 // subexpression.
2000 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
2001 SourceLocation BreakLoc;
2002 SourceLocation ContinueLoc;
2003 bool InSwitch = false;
2004
2005 public:
2006 BreakContinueFinder(Sema &S, const Stmt* Body) :
2007 Inherited(S.Context) {
2008 Visit(S: Body);
2009 }
2010
2011 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
2012
2013 void VisitContinueStmt(const ContinueStmt* E) {
2014 ContinueLoc = E->getContinueLoc();
2015 }
2016
2017 void VisitBreakStmt(const BreakStmt* E) {
2018 if (!InSwitch)
2019 BreakLoc = E->getBreakLoc();
2020 }
2021
2022 void VisitSwitchStmt(const SwitchStmt* S) {
2023 if (const Stmt *Init = S->getInit())
2024 Visit(S: Init);
2025 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
2026 Visit(S: CondVar);
2027 if (const Stmt *Cond = S->getCond())
2028 Visit(S: Cond);
2029
2030 // Don't return break statements from the body of a switch.
2031 InSwitch = true;
2032 if (const Stmt *Body = S->getBody())
2033 Visit(S: Body);
2034 InSwitch = false;
2035 }
2036
2037 void VisitForStmt(const ForStmt *S) {
2038 // Only visit the init statement of a for loop; the body
2039 // has a different break/continue scope.
2040 if (const Stmt *Init = S->getInit())
2041 Visit(S: Init);
2042 }
2043
2044 void VisitWhileStmt(const WhileStmt *) {
2045 // Do nothing; the children of a while loop have a different
2046 // break/continue scope.
2047 }
2048
2049 void VisitDoStmt(const DoStmt *) {
2050 // Do nothing; the children of a while loop have a different
2051 // break/continue scope.
2052 }
2053
2054 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2055 // Only visit the initialization of a for loop; the body
2056 // has a different break/continue scope.
2057 if (const Stmt *Init = S->getInit())
2058 Visit(S: Init);
2059 if (const Stmt *Range = S->getRangeStmt())
2060 Visit(S: Range);
2061 if (const Stmt *Begin = S->getBeginStmt())
2062 Visit(S: Begin);
2063 if (const Stmt *End = S->getEndStmt())
2064 Visit(S: End);
2065 }
2066
2067 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
2068 // Only visit the initialization of a for loop; the body
2069 // has a different break/continue scope.
2070 if (const Stmt *Element = S->getElement())
2071 Visit(S: Element);
2072 if (const Stmt *Collection = S->getCollection())
2073 Visit(S: Collection);
2074 }
2075
2076 bool ContinueFound() { return ContinueLoc.isValid(); }
2077 bool BreakFound() { return BreakLoc.isValid(); }
2078 SourceLocation GetContinueLoc() { return ContinueLoc; }
2079 SourceLocation GetBreakLoc() { return BreakLoc; }
2080
2081 }; // end class BreakContinueFinder
2082
2083 // Emit a warning when a loop increment/decrement appears twice per loop
2084 // iteration. The conditions which trigger this warning are:
2085 // 1) The last statement in the loop body and the third expression in the
2086 // for loop are both increment or both decrement of the same variable
2087 // 2) No continue statements in the loop body.
2088 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
2089 // Return when there is nothing to check.
2090 if (!Body || !Third) return;
2091
2092 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
2093 Third->getBeginLoc()))
2094 return;
2095
2096 // Get the last statement from the loop body.
2097 CompoundStmt *CS = dyn_cast<CompoundStmt>(Val: Body);
2098 if (!CS || CS->body_empty()) return;
2099 Stmt *LastStmt = CS->body_back();
2100 if (!LastStmt) return;
2101
2102 bool LoopIncrement, LastIncrement;
2103 DeclRefExpr *LoopDRE, *LastDRE;
2104
2105 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
2106 if (!ProcessIterationStmt(S, Statement: LastStmt, Increment&: LastIncrement, DRE&: LastDRE)) return;
2107
2108 // Check that the two statements are both increments or both decrements
2109 // on the same variable.
2110 if (LoopIncrement != LastIncrement ||
2111 LoopDRE->getDecl() != LastDRE->getDecl()) return;
2112
2113 if (BreakContinueFinder(S, Body).ContinueFound()) return;
2114
2115 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
2116 << LastDRE->getDecl() << LastIncrement;
2117 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
2118 << LoopIncrement;
2119 }
2120
2121} // end namespace
2122
2123
2124void Sema::CheckBreakContinueBinding(Expr *E) {
2125 if (!E || getLangOpts().CPlusPlus)
2126 return;
2127 BreakContinueFinder BCFinder(*this, E);
2128 Scope *BreakParent = CurScope->getBreakParent();
2129 if (BCFinder.BreakFound() && BreakParent) {
2130 if (BreakParent->getFlags() & Scope::SwitchScope) {
2131 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
2132 } else {
2133 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
2134 << "break";
2135 }
2136 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
2137 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
2138 << "continue";
2139 }
2140}
2141
2142StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
2143 Stmt *First, ConditionResult Second,
2144 FullExprArg third, SourceLocation RParenLoc,
2145 Stmt *Body) {
2146 if (Second.isInvalid())
2147 return StmtError();
2148
2149 if (!getLangOpts().CPlusPlus) {
2150 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(Val: First)) {
2151 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
2152 // declare identifiers for objects having storage class 'auto' or
2153 // 'register'.
2154 const Decl *NonVarSeen = nullptr;
2155 bool VarDeclSeen = false;
2156 for (auto *DI : DS->decls()) {
2157 if (VarDecl *VD = dyn_cast<VarDecl>(Val: DI)) {
2158 VarDeclSeen = true;
2159 if (VD->isLocalVarDecl() && !VD->hasLocalStorage()) {
2160 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
2161 DI->setInvalidDecl();
2162 }
2163 } else if (!NonVarSeen) {
2164 // Keep track of the first non-variable declaration we saw so that
2165 // we can diagnose if we don't see any variable declarations. This
2166 // covers a case like declaring a typedef, function, or structure
2167 // type rather than a variable.
2168 NonVarSeen = DI;
2169 }
2170 }
2171 // Diagnose if we saw a non-variable declaration but no variable
2172 // declarations.
2173 if (NonVarSeen && !VarDeclSeen)
2174 Diag(NonVarSeen->getLocation(), diag::err_non_variable_decl_in_for);
2175 }
2176 }
2177
2178 CheckBreakContinueBinding(E: Second.get().second);
2179 CheckBreakContinueBinding(E: third.get());
2180
2181 if (!Second.get().first)
2182 CheckForLoopConditionalStatement(S&: *this, Second: Second.get().second, Third: third.get(),
2183 Body);
2184 CheckForRedundantIteration(S&: *this, Third: third.get(), Body);
2185
2186 if (Second.get().second &&
2187 !Diags.isIgnored(diag::warn_comma_operator,
2188 Second.get().second->getExprLoc()))
2189 CommaVisitor(*this).Visit(Second.get().second);
2190
2191 Expr *Third = third.release().getAs<Expr>();
2192 if (isa<NullStmt>(Val: Body))
2193 getCurCompoundScope().setHasEmptyLoopBodies();
2194
2195 return new (Context)
2196 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
2197 Body, ForLoc, LParenLoc, RParenLoc);
2198}
2199
2200/// In an Objective C collection iteration statement:
2201/// for (x in y)
2202/// x can be an arbitrary l-value expression. Bind it up as a
2203/// full-expression.
2204StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
2205 // Reduce placeholder expressions here. Note that this rejects the
2206 // use of pseudo-object l-values in this position.
2207 ExprResult result = CheckPlaceholderExpr(E);
2208 if (result.isInvalid()) return StmtError();
2209 E = result.get();
2210
2211 ExprResult FullExpr = ActOnFinishFullExpr(Expr: E, /*DiscardedValue*/ false);
2212 if (FullExpr.isInvalid())
2213 return StmtError();
2214 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
2215}
2216
2217ExprResult
2218Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
2219 if (!collection)
2220 return ExprError();
2221
2222 ExprResult result = CorrectDelayedTyposInExpr(E: collection);
2223 if (!result.isUsable())
2224 return ExprError();
2225 collection = result.get();
2226
2227 // Bail out early if we've got a type-dependent expression.
2228 if (collection->isTypeDependent()) return collection;
2229
2230 // Perform normal l-value conversion.
2231 result = DefaultFunctionArrayLvalueConversion(E: collection);
2232 if (result.isInvalid())
2233 return ExprError();
2234 collection = result.get();
2235
2236 // The operand needs to have object-pointer type.
2237 // TODO: should we do a contextual conversion?
2238 const ObjCObjectPointerType *pointerType =
2239 collection->getType()->getAs<ObjCObjectPointerType>();
2240 if (!pointerType)
2241 return Diag(forLoc, diag::err_collection_expr_type)
2242 << collection->getType() << collection->getSourceRange();
2243
2244 // Check that the operand provides
2245 // - countByEnumeratingWithState:objects:count:
2246 const ObjCObjectType *objectType = pointerType->getObjectType();
2247 ObjCInterfaceDecl *iface = objectType->getInterface();
2248
2249 // If we have a forward-declared type, we can't do this check.
2250 // Under ARC, it is an error not to have a forward-declared class.
2251 if (iface &&
2252 (getLangOpts().ObjCAutoRefCount
2253 ? RequireCompleteType(forLoc, QualType(objectType, 0),
2254 diag::err_arc_collection_forward, collection)
2255 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
2256 // Otherwise, if we have any useful type information, check that
2257 // the type declares the appropriate method.
2258 } else if (iface || !objectType->qual_empty()) {
2259 IdentifierInfo *selectorIdents[] = {
2260 &Context.Idents.get(Name: "countByEnumeratingWithState"),
2261 &Context.Idents.get(Name: "objects"),
2262 &Context.Idents.get(Name: "count")
2263 };
2264 Selector selector = Context.Selectors.getSelector(NumArgs: 3, IIV: &selectorIdents[0]);
2265
2266 ObjCMethodDecl *method = nullptr;
2267
2268 // If there's an interface, look in both the public and private APIs.
2269 if (iface) {
2270 method = iface->lookupInstanceMethod(Sel: selector);
2271 if (!method) method = iface->lookupPrivateMethod(Sel: selector);
2272 }
2273
2274 // Also check protocol qualifiers.
2275 if (!method)
2276 method = LookupMethodInQualifiedType(Sel: selector, OPT: pointerType,
2277 /*instance*/ IsInstance: true);
2278
2279 // If we didn't find it anywhere, give up.
2280 if (!method) {
2281 Diag(forLoc, diag::warn_collection_expr_type)
2282 << collection->getType() << selector << collection->getSourceRange();
2283 }
2284
2285 // TODO: check for an incompatible signature?
2286 }
2287
2288 // Wrap up any cleanups in the expression.
2289 return collection;
2290}
2291
2292StmtResult
2293Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
2294 Stmt *First, Expr *collection,
2295 SourceLocation RParenLoc) {
2296 setFunctionHasBranchProtectedScope();
2297
2298 ExprResult CollectionExprResult =
2299 CheckObjCForCollectionOperand(forLoc: ForLoc, collection);
2300
2301 if (First) {
2302 QualType FirstType;
2303 if (DeclStmt *DS = dyn_cast<DeclStmt>(Val: First)) {
2304 if (!DS->isSingleDecl())
2305 return StmtError(Diag((*DS->decl_begin())->getLocation(),
2306 diag::err_toomany_element_decls));
2307
2308 VarDecl *D = dyn_cast<VarDecl>(Val: DS->getSingleDecl());
2309 if (!D || D->isInvalidDecl())
2310 return StmtError();
2311
2312 FirstType = D->getType();
2313 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
2314 // declare identifiers for objects having storage class 'auto' or
2315 // 'register'.
2316 if (!D->hasLocalStorage())
2317 return StmtError(Diag(D->getLocation(),
2318 diag::err_non_local_variable_decl_in_for));
2319
2320 // If the type contained 'auto', deduce the 'auto' to 'id'.
2321 if (FirstType->getContainedAutoType()) {
2322 SourceLocation Loc = D->getLocation();
2323 OpaqueValueExpr OpaqueId(Loc, Context.getObjCIdType(), VK_PRValue);
2324 Expr *DeducedInit = &OpaqueId;
2325 TemplateDeductionInfo Info(Loc);
2326 FirstType = QualType();
2327 TemplateDeductionResult Result = DeduceAutoType(
2328 AutoTypeLoc: D->getTypeSourceInfo()->getTypeLoc(), Initializer: DeducedInit, Result&: FirstType, Info);
2329 if (Result != TemplateDeductionResult::Success &&
2330 Result != TemplateDeductionResult::AlreadyDiagnosed)
2331 DiagnoseAutoDeductionFailure(VDecl: D, Init: DeducedInit);
2332 if (FirstType.isNull()) {
2333 D->setInvalidDecl();
2334 return StmtError();
2335 }
2336
2337 D->setType(FirstType);
2338
2339 if (!inTemplateInstantiation()) {
2340 SourceLocation Loc =
2341 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
2342 Diag(Loc, diag::warn_auto_var_is_id)
2343 << D->getDeclName();
2344 }
2345 }
2346
2347 } else {
2348 Expr *FirstE = cast<Expr>(Val: First);
2349 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
2350 return StmtError(
2351 Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
2352 << First->getSourceRange());
2353
2354 FirstType = static_cast<Expr*>(First)->getType();
2355 if (FirstType.isConstQualified())
2356 Diag(ForLoc, diag::err_selector_element_const_type)
2357 << FirstType << First->getSourceRange();
2358 }
2359 if (!FirstType->isDependentType() &&
2360 !FirstType->isObjCObjectPointerType() &&
2361 !FirstType->isBlockPointerType())
2362 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
2363 << FirstType << First->getSourceRange());
2364 }
2365
2366 if (CollectionExprResult.isInvalid())
2367 return StmtError();
2368
2369 CollectionExprResult =
2370 ActOnFinishFullExpr(Expr: CollectionExprResult.get(), /*DiscardedValue*/ false);
2371 if (CollectionExprResult.isInvalid())
2372 return StmtError();
2373
2374 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
2375 nullptr, ForLoc, RParenLoc);
2376}
2377
2378/// Finish building a variable declaration for a for-range statement.
2379/// \return true if an error occurs.
2380static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
2381 SourceLocation Loc, int DiagID) {
2382 if (Decl->getType()->isUndeducedType()) {
2383 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(E: Init);
2384 if (!Res.isUsable()) {
2385 Decl->setInvalidDecl();
2386 return true;
2387 }
2388 Init = Res.get();
2389 }
2390
2391 // Deduce the type for the iterator variable now rather than leaving it to
2392 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
2393 QualType InitType;
2394 if (!isa<InitListExpr>(Val: Init) && Init->getType()->isVoidType()) {
2395 SemaRef.Diag(Loc, DiagID) << Init->getType();
2396 } else {
2397 TemplateDeductionInfo Info(Init->getExprLoc());
2398 TemplateDeductionResult Result = SemaRef.DeduceAutoType(
2399 AutoTypeLoc: Decl->getTypeSourceInfo()->getTypeLoc(), Initializer: Init, Result&: InitType, Info);
2400 if (Result != TemplateDeductionResult::Success &&
2401 Result != TemplateDeductionResult::AlreadyDiagnosed)
2402 SemaRef.Diag(Loc, DiagID) << Init->getType();
2403 }
2404
2405 if (InitType.isNull()) {
2406 Decl->setInvalidDecl();
2407 return true;
2408 }
2409 Decl->setType(InitType);
2410
2411 // In ARC, infer lifetime.
2412 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
2413 // we're doing the equivalent of fast iteration.
2414 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2415 SemaRef.inferObjCARCLifetime(Decl))
2416 Decl->setInvalidDecl();
2417
2418 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
2419 SemaRef.FinalizeDeclaration(Decl);
2420 SemaRef.CurContext->addHiddenDecl(Decl);
2421 return false;
2422}
2423
2424namespace {
2425// An enum to represent whether something is dealing with a call to begin()
2426// or a call to end() in a range-based for loop.
2427enum BeginEndFunction {
2428 BEF_begin,
2429 BEF_end
2430};
2431
2432/// Produce a note indicating which begin/end function was implicitly called
2433/// by a C++11 for-range statement. This is often not obvious from the code,
2434/// nor from the diagnostics produced when analysing the implicit expressions
2435/// required in a for-range statement.
2436void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
2437 BeginEndFunction BEF) {
2438 CallExpr *CE = dyn_cast<CallExpr>(Val: E);
2439 if (!CE)
2440 return;
2441 FunctionDecl *D = dyn_cast<FunctionDecl>(Val: CE->getCalleeDecl());
2442 if (!D)
2443 return;
2444 SourceLocation Loc = D->getLocation();
2445
2446 std::string Description;
2447 bool IsTemplate = false;
2448 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2449 Description = SemaRef.getTemplateArgumentBindingsText(
2450 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2451 IsTemplate = true;
2452 }
2453
2454 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2455 << BEF << IsTemplate << Description << E->getType();
2456}
2457
2458/// Build a variable declaration for a for-range statement.
2459VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
2460 QualType Type, StringRef Name) {
2461 DeclContext *DC = SemaRef.CurContext;
2462 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2463 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(T: Type, Loc);
2464 VarDecl *Decl = VarDecl::Create(C&: SemaRef.Context, DC, StartLoc: Loc, IdLoc: Loc, Id: II, T: Type,
2465 TInfo, S: SC_None);
2466 Decl->setImplicit();
2467 return Decl;
2468}
2469
2470}
2471
2472static bool ObjCEnumerationCollection(Expr *Collection) {
2473 return !Collection->isTypeDependent()
2474 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
2475}
2476
2477/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
2478///
2479/// C++11 [stmt.ranged]:
2480/// A range-based for statement is equivalent to
2481///
2482/// {
2483/// auto && __range = range-init;
2484/// for ( auto __begin = begin-expr,
2485/// __end = end-expr;
2486/// __begin != __end;
2487/// ++__begin ) {
2488/// for-range-declaration = *__begin;
2489/// statement
2490/// }
2491/// }
2492///
2493/// The body of the loop is not available yet, since it cannot be analysed until
2494/// we have determined the type of the for-range-declaration.
2495StmtResult Sema::ActOnCXXForRangeStmt(
2496 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
2497 Stmt *First, SourceLocation ColonLoc, Expr *Range, SourceLocation RParenLoc,
2498 BuildForRangeKind Kind,
2499 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps) {
2500 // FIXME: recover in order to allow the body to be parsed.
2501 if (!First)
2502 return StmtError();
2503
2504 if (Range && ObjCEnumerationCollection(Collection: Range)) {
2505 // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2506 if (InitStmt)
2507 return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
2508 << InitStmt->getSourceRange();
2509 return ActOnObjCForCollectionStmt(ForLoc, First, collection: Range, RParenLoc);
2510 }
2511
2512 DeclStmt *DS = dyn_cast<DeclStmt>(Val: First);
2513 assert(DS && "first part of for range not a decl stmt");
2514
2515 if (!DS->isSingleDecl()) {
2516 Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
2517 return StmtError();
2518 }
2519
2520 // This function is responsible for attaching an initializer to LoopVar. We
2521 // must call ActOnInitializerError if we fail to do so.
2522 Decl *LoopVar = DS->getSingleDecl();
2523 if (LoopVar->isInvalidDecl() || !Range ||
2524 DiagnoseUnexpandedParameterPack(E: Range, UPPC: UPPC_Expression)) {
2525 ActOnInitializerError(Dcl: LoopVar);
2526 return StmtError();
2527 }
2528
2529 // Build the coroutine state immediately and not later during template
2530 // instantiation
2531 if (!CoawaitLoc.isInvalid()) {
2532 if (!ActOnCoroutineBodyStart(S, KwLoc: CoawaitLoc, Keyword: "co_await")) {
2533 ActOnInitializerError(Dcl: LoopVar);
2534 return StmtError();
2535 }
2536 }
2537
2538 // Build auto && __range = range-init
2539 // Divide by 2, since the variables are in the inner scope (loop body).
2540 const auto DepthStr = std::to_string(val: S->getDepth() / 2);
2541 SourceLocation RangeLoc = Range->getBeginLoc();
2542 VarDecl *RangeVar = BuildForRangeVarDecl(SemaRef&: *this, Loc: RangeLoc,
2543 Type: Context.getAutoRRefDeductType(),
2544 Name: std::string("__range") + DepthStr);
2545 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
2546 diag::err_for_range_deduction_failure)) {
2547 ActOnInitializerError(Dcl: LoopVar);
2548 return StmtError();
2549 }
2550
2551 // Claim the type doesn't contain auto: we've already done the checking.
2552 DeclGroupPtrTy RangeGroup =
2553 BuildDeclaratorGroup(Group: MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
2554 StmtResult RangeDecl = ActOnDeclStmt(dg: RangeGroup, StartLoc: RangeLoc, EndLoc: RangeLoc);
2555 if (RangeDecl.isInvalid()) {
2556 ActOnInitializerError(Dcl: LoopVar);
2557 return StmtError();
2558 }
2559
2560 StmtResult R = BuildCXXForRangeStmt(
2561 ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl: RangeDecl.get(),
2562 /*BeginStmt=*/Begin: nullptr, /*EndStmt=*/End: nullptr,
2563 /*Cond=*/nullptr, /*Inc=*/nullptr, LoopVarDecl: DS, RParenLoc, Kind,
2564 LifetimeExtendTemps);
2565 if (R.isInvalid()) {
2566 ActOnInitializerError(Dcl: LoopVar);
2567 return StmtError();
2568 }
2569
2570 return R;
2571}
2572
2573/// Create the initialization, compare, and increment steps for
2574/// the range-based for loop expression.
2575/// This function does not handle array-based for loops,
2576/// which are created in Sema::BuildCXXForRangeStmt.
2577///
2578/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2579/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2580/// CandidateSet and BEF are set and some non-success value is returned on
2581/// failure.
2582static Sema::ForRangeStatus
2583BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2584 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2585 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2586 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2587 ExprResult *EndExpr, BeginEndFunction *BEF) {
2588 DeclarationNameInfo BeginNameInfo(
2589 &SemaRef.PP.getIdentifierTable().get(Name: "begin"), ColonLoc);
2590 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get(Name: "end"),
2591 ColonLoc);
2592
2593 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2594 Sema::LookupMemberName);
2595 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2596
2597 auto BuildBegin = [&] {
2598 *BEF = BEF_begin;
2599 Sema::ForRangeStatus RangeStatus =
2600 SemaRef.BuildForRangeBeginEndCall(Loc: ColonLoc, RangeLoc: ColonLoc, NameInfo: BeginNameInfo,
2601 MemberLookup&: BeginMemberLookup, CandidateSet,
2602 Range: BeginRange, CallExpr: BeginExpr);
2603
2604 if (RangeStatus != Sema::FRS_Success) {
2605 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2606 SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
2607 << ColonLoc << BEF_begin << BeginRange->getType();
2608 return RangeStatus;
2609 }
2610 if (!CoawaitLoc.isInvalid()) {
2611 // FIXME: getCurScope() should not be used during template instantiation.
2612 // We should pick up the set of unqualified lookup results for operator
2613 // co_await during the initial parse.
2614 *BeginExpr = SemaRef.ActOnCoawaitExpr(S: SemaRef.getCurScope(), KwLoc: ColonLoc,
2615 E: BeginExpr->get());
2616 if (BeginExpr->isInvalid())
2617 return Sema::FRS_DiagnosticIssued;
2618 }
2619 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2620 diag::err_for_range_iter_deduction_failure)) {
2621 NoteForRangeBeginEndFunction(SemaRef, E: BeginExpr->get(), BEF: *BEF);
2622 return Sema::FRS_DiagnosticIssued;
2623 }
2624 return Sema::FRS_Success;
2625 };
2626
2627 auto BuildEnd = [&] {
2628 *BEF = BEF_end;
2629 Sema::ForRangeStatus RangeStatus =
2630 SemaRef.BuildForRangeBeginEndCall(Loc: ColonLoc, RangeLoc: ColonLoc, NameInfo: EndNameInfo,
2631 MemberLookup&: EndMemberLookup, CandidateSet,
2632 Range: EndRange, CallExpr: EndExpr);
2633 if (RangeStatus != Sema::FRS_Success) {
2634 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2635 SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
2636 << ColonLoc << BEF_end << EndRange->getType();
2637 return RangeStatus;
2638 }
2639 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2640 diag::err_for_range_iter_deduction_failure)) {
2641 NoteForRangeBeginEndFunction(SemaRef, E: EndExpr->get(), BEF: *BEF);
2642 return Sema::FRS_DiagnosticIssued;
2643 }
2644 return Sema::FRS_Success;
2645 };
2646
2647 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2648 // - if _RangeT is a class type, the unqualified-ids begin and end are
2649 // looked up in the scope of class _RangeT as if by class member access
2650 // lookup (3.4.5), and if either (or both) finds at least one
2651 // declaration, begin-expr and end-expr are __range.begin() and
2652 // __range.end(), respectively;
2653 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2654 if (BeginMemberLookup.isAmbiguous())
2655 return Sema::FRS_DiagnosticIssued;
2656
2657 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2658 if (EndMemberLookup.isAmbiguous())
2659 return Sema::FRS_DiagnosticIssued;
2660
2661 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2662 // Look up the non-member form of the member we didn't find, first.
2663 // This way we prefer a "no viable 'end'" diagnostic over a "i found
2664 // a 'begin' but ignored it because there was no member 'end'"
2665 // diagnostic.
2666 auto BuildNonmember = [&](
2667 BeginEndFunction BEFFound, LookupResult &Found,
2668 llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
2669 llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
2670 LookupResult OldFound = std::move(Found);
2671 Found.clear();
2672
2673 if (Sema::ForRangeStatus Result = BuildNotFound())
2674 return Result;
2675
2676 switch (BuildFound()) {
2677 case Sema::FRS_Success:
2678 return Sema::FRS_Success;
2679
2680 case Sema::FRS_NoViableFunction:
2681 CandidateSet->NoteCandidates(
2682 PartialDiagnosticAt(BeginRange->getBeginLoc(),
2683 SemaRef.PDiag(diag::err_for_range_invalid)
2684 << BeginRange->getType() << BEFFound),
2685 SemaRef, OCD_AllCandidates, BeginRange);
2686 [[fallthrough]];
2687
2688 case Sema::FRS_DiagnosticIssued:
2689 for (NamedDecl *D : OldFound) {
2690 SemaRef.Diag(D->getLocation(),
2691 diag::note_for_range_member_begin_end_ignored)
2692 << BeginRange->getType() << BEFFound;
2693 }
2694 return Sema::FRS_DiagnosticIssued;
2695 }
2696 llvm_unreachable("unexpected ForRangeStatus");
2697 };
2698 if (BeginMemberLookup.empty())
2699 return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
2700 return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
2701 }
2702 } else {
2703 // - otherwise, begin-expr and end-expr are begin(__range) and
2704 // end(__range), respectively, where begin and end are looked up with
2705 // argument-dependent lookup (3.4.2). For the purposes of this name
2706 // lookup, namespace std is an associated namespace.
2707 }
2708
2709 if (Sema::ForRangeStatus Result = BuildBegin())
2710 return Result;
2711 return BuildEnd();
2712}
2713
2714/// Speculatively attempt to dereference an invalid range expression.
2715/// If the attempt fails, this function will return a valid, null StmtResult
2716/// and emit no diagnostics.
2717static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2718 SourceLocation ForLoc,
2719 SourceLocation CoawaitLoc,
2720 Stmt *InitStmt,
2721 Stmt *LoopVarDecl,
2722 SourceLocation ColonLoc,
2723 Expr *Range,
2724 SourceLocation RangeLoc,
2725 SourceLocation RParenLoc) {
2726 // Determine whether we can rebuild the for-range statement with a
2727 // dereferenced range expression.
2728 ExprResult AdjustedRange;
2729 {
2730 Sema::SFINAETrap Trap(SemaRef);
2731
2732 AdjustedRange = SemaRef.BuildUnaryOp(S, OpLoc: RangeLoc, Opc: UO_Deref, Input: Range);
2733 if (AdjustedRange.isInvalid())
2734 return StmtResult();
2735
2736 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2737 S, ForLoc, CoawaitLoc, InitStmt, First: LoopVarDecl, ColonLoc,
2738 Range: AdjustedRange.get(), RParenLoc, Kind: Sema::BFRK_Check);
2739 if (SR.isInvalid())
2740 return StmtResult();
2741 }
2742
2743 // The attempt to dereference worked well enough that it could produce a valid
2744 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2745 // case there are any other (non-fatal) problems with it.
2746 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2747 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2748 return SemaRef.ActOnCXXForRangeStmt(
2749 S, ForLoc, CoawaitLoc, InitStmt, First: LoopVarDecl, ColonLoc,
2750 Range: AdjustedRange.get(), RParenLoc, Kind: Sema::BFRK_Rebuild);
2751}
2752
2753/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2754StmtResult Sema::BuildCXXForRangeStmt(
2755 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
2756 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
2757 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
2758 BuildForRangeKind Kind,
2759 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps) {
2760 // FIXME: This should not be used during template instantiation. We should
2761 // pick up the set of unqualified lookup results for the != and + operators
2762 // in the initial parse.
2763 //
2764 // Testcase (accepts-invalid):
2765 // template<typename T> void f() { for (auto x : T()) {} }
2766 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2767 // bool operator!=(N::X, N::X); void operator++(N::X);
2768 // void g() { f<N::X>(); }
2769 Scope *S = getCurScope();
2770
2771 DeclStmt *RangeDS = cast<DeclStmt>(Val: RangeDecl);
2772 VarDecl *RangeVar = cast<VarDecl>(Val: RangeDS->getSingleDecl());
2773 QualType RangeVarType = RangeVar->getType();
2774
2775 DeclStmt *LoopVarDS = cast<DeclStmt>(Val: LoopVarDecl);
2776 VarDecl *LoopVar = cast<VarDecl>(Val: LoopVarDS->getSingleDecl());
2777
2778 StmtResult BeginDeclStmt = Begin;
2779 StmtResult EndDeclStmt = End;
2780 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2781
2782 if (RangeVarType->isDependentType()) {
2783 // The range is implicitly used as a placeholder when it is dependent.
2784 RangeVar->markUsed(Context);
2785
2786 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2787 // them in properly when we instantiate the loop.
2788 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2789 if (auto *DD = dyn_cast<DecompositionDecl>(Val: LoopVar))
2790 for (auto *Binding : DD->bindings())
2791 Binding->setType(Context.DependentTy);
2792 LoopVar->setType(SubstAutoTypeDependent(TypeWithAuto: LoopVar->getType()));
2793 }
2794 } else if (!BeginDeclStmt.get()) {
2795 SourceLocation RangeLoc = RangeVar->getLocation();
2796
2797 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2798
2799 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2800 VK_LValue, ColonLoc);
2801 if (BeginRangeRef.isInvalid())
2802 return StmtError();
2803
2804 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2805 VK_LValue, ColonLoc);
2806 if (EndRangeRef.isInvalid())
2807 return StmtError();
2808
2809 QualType AutoType = Context.getAutoDeductType();
2810 Expr *Range = RangeVar->getInit();
2811 if (!Range)
2812 return StmtError();
2813 QualType RangeType = Range->getType();
2814
2815 if (RequireCompleteType(RangeLoc, RangeType,
2816 diag::err_for_range_incomplete_type))
2817 return StmtError();
2818
2819 // P2718R0 - Lifetime extension in range-based for loops.
2820 if (getLangOpts().CPlusPlus23 && !LifetimeExtendTemps.empty()) {
2821 InitializedEntity Entity =
2822 InitializedEntity::InitializeVariable(Var: RangeVar);
2823 for (auto *MTE : LifetimeExtendTemps)
2824 MTE->setExtendingDecl(RangeVar, Entity.allocateManglingNumber());
2825 }
2826
2827 // Build auto __begin = begin-expr, __end = end-expr.
2828 // Divide by 2, since the variables are in the inner scope (loop body).
2829 const auto DepthStr = std::to_string(val: S->getDepth() / 2);
2830 VarDecl *BeginVar = BuildForRangeVarDecl(SemaRef&: *this, Loc: ColonLoc, Type: AutoType,
2831 Name: std::string("__begin") + DepthStr);
2832 VarDecl *EndVar = BuildForRangeVarDecl(SemaRef&: *this, Loc: ColonLoc, Type: AutoType,
2833 Name: std::string("__end") + DepthStr);
2834
2835 // Build begin-expr and end-expr and attach to __begin and __end variables.
2836 ExprResult BeginExpr, EndExpr;
2837 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2838 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2839 // __range + __bound, respectively, where __bound is the array bound. If
2840 // _RangeT is an array of unknown size or an array of incomplete type,
2841 // the program is ill-formed;
2842
2843 // begin-expr is __range.
2844 BeginExpr = BeginRangeRef;
2845 if (!CoawaitLoc.isInvalid()) {
2846 BeginExpr = ActOnCoawaitExpr(S, KwLoc: ColonLoc, E: BeginExpr.get());
2847 if (BeginExpr.isInvalid())
2848 return StmtError();
2849 }
2850 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2851 diag::err_for_range_iter_deduction_failure)) {
2852 NoteForRangeBeginEndFunction(SemaRef&: *this, E: BeginExpr.get(), BEF: BEF_begin);
2853 return StmtError();
2854 }
2855
2856 // Find the array bound.
2857 ExprResult BoundExpr;
2858 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: UnqAT))
2859 BoundExpr = IntegerLiteral::Create(
2860 C: Context, V: CAT->getSize(), type: Context.getPointerDiffType(), l: RangeLoc);
2861 else if (const VariableArrayType *VAT =
2862 dyn_cast<VariableArrayType>(Val: UnqAT)) {
2863 // For a variably modified type we can't just use the expression within
2864 // the array bounds, since we don't want that to be re-evaluated here.
2865 // Rather, we need to determine what it was when the array was first
2866 // created - so we resort to using sizeof(vla)/sizeof(element).
2867 // For e.g.
2868 // void f(int b) {
2869 // int vla[b];
2870 // b = -1; <-- This should not affect the num of iterations below
2871 // for (int &c : vla) { .. }
2872 // }
2873
2874 // FIXME: This results in codegen generating IR that recalculates the
2875 // run-time number of elements (as opposed to just using the IR Value
2876 // that corresponds to the run-time value of each bound that was
2877 // generated when the array was created.) If this proves too embarrassing
2878 // even for unoptimized IR, consider passing a magic-value/cookie to
2879 // codegen that then knows to simply use that initial llvm::Value (that
2880 // corresponds to the bound at time of array creation) within
2881 // getelementptr. But be prepared to pay the price of increasing a
2882 // customized form of coupling between the two components - which could
2883 // be hard to maintain as the codebase evolves.
2884
2885 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2886 OpLoc: EndVar->getLocation(), ExprKind: UETT_SizeOf,
2887 /*IsType=*/true,
2888 TyOrEx: CreateParsedType(T: VAT->desugar(), TInfo: Context.getTrivialTypeSourceInfo(
2889 T: VAT->desugar(), Loc: RangeLoc))
2890 .getAsOpaquePtr(),
2891 ArgRange: EndVar->getSourceRange());
2892 if (SizeOfVLAExprR.isInvalid())
2893 return StmtError();
2894
2895 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2896 OpLoc: EndVar->getLocation(), ExprKind: UETT_SizeOf,
2897 /*IsType=*/true,
2898 TyOrEx: CreateParsedType(T: VAT->desugar(),
2899 TInfo: Context.getTrivialTypeSourceInfo(
2900 T: VAT->getElementType(), Loc: RangeLoc))
2901 .getAsOpaquePtr(),
2902 ArgRange: EndVar->getSourceRange());
2903 if (SizeOfEachElementExprR.isInvalid())
2904 return StmtError();
2905
2906 BoundExpr =
2907 ActOnBinOp(S, TokLoc: EndVar->getLocation(), Kind: tok::slash,
2908 LHSExpr: SizeOfVLAExprR.get(), RHSExpr: SizeOfEachElementExprR.get());
2909 if (BoundExpr.isInvalid())
2910 return StmtError();
2911
2912 } else {
2913 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2914 // UnqAT is not incomplete and Range is not type-dependent.
2915 llvm_unreachable("Unexpected array type in for-range");
2916 }
2917
2918 // end-expr is __range + __bound.
2919 EndExpr = ActOnBinOp(S, TokLoc: ColonLoc, Kind: tok::plus, LHSExpr: EndRangeRef.get(),
2920 RHSExpr: BoundExpr.get());
2921 if (EndExpr.isInvalid())
2922 return StmtError();
2923 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2924 diag::err_for_range_iter_deduction_failure)) {
2925 NoteForRangeBeginEndFunction(SemaRef&: *this, E: EndExpr.get(), BEF: BEF_end);
2926 return StmtError();
2927 }
2928 } else {
2929 OverloadCandidateSet CandidateSet(RangeLoc,
2930 OverloadCandidateSet::CSK_Normal);
2931 BeginEndFunction BEFFailure;
2932 ForRangeStatus RangeStatus = BuildNonArrayForRange(
2933 SemaRef&: *this, BeginRange: BeginRangeRef.get(), EndRange: EndRangeRef.get(), RangeType, BeginVar,
2934 EndVar, ColonLoc, CoawaitLoc, CandidateSet: &CandidateSet, BeginExpr: &BeginExpr, EndExpr: &EndExpr,
2935 BEF: &BEFFailure);
2936
2937 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2938 BEFFailure == BEF_begin) {
2939 // If the range is being built from an array parameter, emit a
2940 // a diagnostic that it is being treated as a pointer.
2941 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Range)) {
2942 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Val: DRE->getDecl())) {
2943 QualType ArrayTy = PVD->getOriginalType();
2944 QualType PointerTy = PVD->getType();
2945 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2946 Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
2947 << RangeLoc << PVD << ArrayTy << PointerTy;
2948 Diag(PVD->getLocation(), diag::note_declared_at);
2949 return StmtError();
2950 }
2951 }
2952 }
2953
2954 // If building the range failed, try dereferencing the range expression
2955 // unless a diagnostic was issued or the end function is problematic.
2956 StmtResult SR = RebuildForRangeWithDereference(SemaRef&: *this, S, ForLoc,
2957 CoawaitLoc, InitStmt,
2958 LoopVarDecl, ColonLoc,
2959 Range, RangeLoc,
2960 RParenLoc);
2961 if (SR.isInvalid() || SR.isUsable())
2962 return SR;
2963 }
2964
2965 // Otherwise, emit diagnostics if we haven't already.
2966 if (RangeStatus == FRS_NoViableFunction) {
2967 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2968 CandidateSet.NoteCandidates(
2969 PartialDiagnosticAt(Range->getBeginLoc(),
2970 PDiag(diag::err_for_range_invalid)
2971 << RangeLoc << Range->getType()
2972 << BEFFailure),
2973 *this, OCD_AllCandidates, Range);
2974 }
2975 // Return an error if no fix was discovered.
2976 if (RangeStatus != FRS_Success)
2977 return StmtError();
2978 }
2979
2980 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2981 "invalid range expression in for loop");
2982
2983 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2984 // C++1z removes this restriction.
2985 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2986 if (!Context.hasSameType(T1: BeginType, T2: EndType)) {
2987 Diag(RangeLoc, getLangOpts().CPlusPlus17
2988 ? diag::warn_for_range_begin_end_types_differ
2989 : diag::ext_for_range_begin_end_types_differ)
2990 << BeginType << EndType;
2991 NoteForRangeBeginEndFunction(SemaRef&: *this, E: BeginExpr.get(), BEF: BEF_begin);
2992 NoteForRangeBeginEndFunction(SemaRef&: *this, E: EndExpr.get(), BEF: BEF_end);
2993 }
2994
2995 BeginDeclStmt =
2996 ActOnDeclStmt(dg: ConvertDeclToDeclGroup(BeginVar), StartLoc: ColonLoc, EndLoc: ColonLoc);
2997 EndDeclStmt =
2998 ActOnDeclStmt(dg: ConvertDeclToDeclGroup(EndVar), StartLoc: ColonLoc, EndLoc: ColonLoc);
2999
3000 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
3001 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
3002 VK_LValue, ColonLoc);
3003 if (BeginRef.isInvalid())
3004 return StmtError();
3005
3006 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
3007 VK_LValue, ColonLoc);
3008 if (EndRef.isInvalid())
3009 return StmtError();
3010
3011 // Build and check __begin != __end expression.
3012 NotEqExpr = ActOnBinOp(S, TokLoc: ColonLoc, Kind: tok::exclaimequal,
3013 LHSExpr: BeginRef.get(), RHSExpr: EndRef.get());
3014 if (!NotEqExpr.isInvalid())
3015 NotEqExpr = CheckBooleanCondition(Loc: ColonLoc, E: NotEqExpr.get());
3016 if (!NotEqExpr.isInvalid())
3017 NotEqExpr =
3018 ActOnFinishFullExpr(Expr: NotEqExpr.get(), /*DiscardedValue*/ false);
3019 if (NotEqExpr.isInvalid()) {
3020 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
3021 << RangeLoc << 0 << BeginRangeRef.get()->getType();
3022 NoteForRangeBeginEndFunction(SemaRef&: *this, E: BeginExpr.get(), BEF: BEF_begin);
3023 if (!Context.hasSameType(T1: BeginType, T2: EndType))
3024 NoteForRangeBeginEndFunction(SemaRef&: *this, E: EndExpr.get(), BEF: BEF_end);
3025 return StmtError();
3026 }
3027
3028 // Build and check ++__begin expression.
3029 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
3030 VK_LValue, ColonLoc);
3031 if (BeginRef.isInvalid())
3032 return StmtError();
3033
3034 IncrExpr = ActOnUnaryOp(S, OpLoc: ColonLoc, Op: tok::plusplus, Input: BeginRef.get());
3035 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
3036 // FIXME: getCurScope() should not be used during template instantiation.
3037 // We should pick up the set of unqualified lookup results for operator
3038 // co_await during the initial parse.
3039 IncrExpr = ActOnCoawaitExpr(S, KwLoc: CoawaitLoc, E: IncrExpr.get());
3040 if (!IncrExpr.isInvalid())
3041 IncrExpr = ActOnFinishFullExpr(Expr: IncrExpr.get(), /*DiscardedValue*/ false);
3042 if (IncrExpr.isInvalid()) {
3043 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
3044 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
3045 NoteForRangeBeginEndFunction(SemaRef&: *this, E: BeginExpr.get(), BEF: BEF_begin);
3046 return StmtError();
3047 }
3048
3049 // Build and check *__begin expression.
3050 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
3051 VK_LValue, ColonLoc);
3052 if (BeginRef.isInvalid())
3053 return StmtError();
3054
3055 ExprResult DerefExpr = ActOnUnaryOp(S, OpLoc: ColonLoc, Op: tok::star, Input: BeginRef.get());
3056 if (DerefExpr.isInvalid()) {
3057 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
3058 << RangeLoc << 1 << BeginRangeRef.get()->getType();
3059 NoteForRangeBeginEndFunction(SemaRef&: *this, E: BeginExpr.get(), BEF: BEF_begin);
3060 return StmtError();
3061 }
3062
3063 // Attach *__begin as initializer for VD. Don't touch it if we're just
3064 // trying to determine whether this would be a valid range.
3065 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
3066 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
3067 if (LoopVar->isInvalidDecl() ||
3068 (LoopVar->getInit() && LoopVar->getInit()->containsErrors()))
3069 NoteForRangeBeginEndFunction(SemaRef&: *this, E: BeginExpr.get(), BEF: BEF_begin);
3070 }
3071 }
3072
3073 // Don't bother to actually allocate the result if we're just trying to
3074 // determine whether it would be valid.
3075 if (Kind == BFRK_Check)
3076 return StmtResult();
3077
3078 // In OpenMP loop region loop control variable must be private. Perform
3079 // analysis of first part (if any).
3080 if (getLangOpts().OpenMP >= 50 && BeginDeclStmt.isUsable())
3081 ActOnOpenMPLoopInitialization(ForLoc, Init: BeginDeclStmt.get());
3082
3083 return new (Context) CXXForRangeStmt(
3084 InitStmt, RangeDS, cast_or_null<DeclStmt>(Val: BeginDeclStmt.get()),
3085 cast_or_null<DeclStmt>(Val: EndDeclStmt.get()), NotEqExpr.get(),
3086 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
3087 ColonLoc, RParenLoc);
3088}
3089
3090/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
3091/// statement.
3092StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
3093 if (!S || !B)
3094 return StmtError();
3095 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(Val: S);
3096
3097 ForStmt->setBody(B);
3098 return S;
3099}
3100
3101// Warn when the loop variable is a const reference that creates a copy.
3102// Suggest using the non-reference type for copies. If a copy can be prevented
3103// suggest the const reference type that would do so.
3104// For instance, given "for (const &Foo : Range)", suggest
3105// "for (const Foo : Range)" to denote a copy is made for the loop. If
3106// possible, also suggest "for (const &Bar : Range)" if this type prevents
3107// the copy altogether.
3108static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
3109 const VarDecl *VD,
3110 QualType RangeInitType) {
3111 const Expr *InitExpr = VD->getInit();
3112 if (!InitExpr)
3113 return;
3114
3115 QualType VariableType = VD->getType();
3116
3117 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Val: InitExpr))
3118 if (!Cleanups->cleanupsHaveSideEffects())
3119 InitExpr = Cleanups->getSubExpr();
3120
3121 const MaterializeTemporaryExpr *MTE =
3122 dyn_cast<MaterializeTemporaryExpr>(Val: InitExpr);
3123
3124 // No copy made.
3125 if (!MTE)
3126 return;
3127
3128 const Expr *E = MTE->getSubExpr()->IgnoreImpCasts();
3129
3130 // Searching for either UnaryOperator for dereference of a pointer or
3131 // CXXOperatorCallExpr for handling iterators.
3132 while (!isa<CXXOperatorCallExpr>(Val: E) && !isa<UnaryOperator>(Val: E)) {
3133 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Val: E)) {
3134 E = CCE->getArg(Arg: 0);
3135 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(Val: E)) {
3136 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
3137 E = ME->getBase();
3138 } else {
3139 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(Val: E);
3140 E = MTE->getSubExpr();
3141 }
3142 E = E->IgnoreImpCasts();
3143 }
3144
3145 QualType ReferenceReturnType;
3146 if (isa<UnaryOperator>(Val: E)) {
3147 ReferenceReturnType = SemaRef.Context.getLValueReferenceType(T: E->getType());
3148 } else {
3149 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(Val: E);
3150 const FunctionDecl *FD = Call->getDirectCallee();
3151 QualType ReturnType = FD->getReturnType();
3152 if (ReturnType->isReferenceType())
3153 ReferenceReturnType = ReturnType;
3154 }
3155
3156 if (!ReferenceReturnType.isNull()) {
3157 // Loop variable creates a temporary. Suggest either to go with
3158 // non-reference loop variable to indicate a copy is made, or
3159 // the correct type to bind a const reference.
3160 SemaRef.Diag(VD->getLocation(),
3161 diag::warn_for_range_const_ref_binds_temp_built_from_ref)
3162 << VD << VariableType << ReferenceReturnType;
3163 QualType NonReferenceType = VariableType.getNonReferenceType();
3164 NonReferenceType.removeLocalConst();
3165 QualType NewReferenceType =
3166 SemaRef.Context.getLValueReferenceType(T: E->getType().withConst());
3167 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
3168 << NonReferenceType << NewReferenceType << VD->getSourceRange()
3169 << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc());
3170 } else if (!VariableType->isRValueReferenceType()) {
3171 // The range always returns a copy, so a temporary is always created.
3172 // Suggest removing the reference from the loop variable.
3173 // If the type is a rvalue reference do not warn since that changes the
3174 // semantic of the code.
3175 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_ref_binds_ret_temp)
3176 << VD << RangeInitType;
3177 QualType NonReferenceType = VariableType.getNonReferenceType();
3178 NonReferenceType.removeLocalConst();
3179 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
3180 << NonReferenceType << VD->getSourceRange()
3181 << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc());
3182 }
3183}
3184
3185/// Determines whether the @p VariableType's declaration is a record with the
3186/// clang::trivial_abi attribute.
3187static bool hasTrivialABIAttr(QualType VariableType) {
3188 if (CXXRecordDecl *RD = VariableType->getAsCXXRecordDecl())
3189 return RD->hasAttr<TrivialABIAttr>();
3190
3191 return false;
3192}
3193
3194// Warns when the loop variable can be changed to a reference type to
3195// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
3196// "for (const Foo &x : Range)" if this form does not make a copy.
3197static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
3198 const VarDecl *VD) {
3199 const Expr *InitExpr = VD->getInit();
3200 if (!InitExpr)
3201 return;
3202
3203 QualType VariableType = VD->getType();
3204
3205 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Val: InitExpr)) {
3206 if (!CE->getConstructor()->isCopyConstructor())
3207 return;
3208 } else if (const CastExpr *CE = dyn_cast<CastExpr>(Val: InitExpr)) {
3209 if (CE->getCastKind() != CK_LValueToRValue)
3210 return;
3211 } else {
3212 return;
3213 }
3214
3215 // Small trivially copyable types are cheap to copy. Do not emit the
3216 // diagnostic for these instances. 64 bytes is a common size of a cache line.
3217 // (The function `getTypeSize` returns the size in bits.)
3218 ASTContext &Ctx = SemaRef.Context;
3219 if (Ctx.getTypeSize(T: VariableType) <= 64 * 8 &&
3220 (VariableType.isTriviallyCopyConstructibleType(Context: Ctx) ||
3221 hasTrivialABIAttr(VariableType)))
3222 return;
3223
3224 // Suggest changing from a const variable to a const reference variable
3225 // if doing so will prevent a copy.
3226 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
3227 << VD << VariableType;
3228 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
3229 << SemaRef.Context.getLValueReferenceType(VariableType)
3230 << VD->getSourceRange()
3231 << FixItHint::CreateInsertion(VD->getLocation(), "&");
3232}
3233
3234/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
3235/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
3236/// using "const foo x" to show that a copy is made
3237/// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
3238/// Suggest either "const bar x" to keep the copying or "const foo& x" to
3239/// prevent the copy.
3240/// 3) for (const foo x : foos) where x is constructed from a reference foo.
3241/// Suggest "const foo &x" to prevent the copy.
3242static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
3243 const CXXForRangeStmt *ForStmt) {
3244 if (SemaRef.inTemplateInstantiation())
3245 return;
3246
3247 if (SemaRef.Diags.isIgnored(
3248 diag::warn_for_range_const_ref_binds_temp_built_from_ref,
3249 ForStmt->getBeginLoc()) &&
3250 SemaRef.Diags.isIgnored(diag::warn_for_range_ref_binds_ret_temp,
3251 ForStmt->getBeginLoc()) &&
3252 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
3253 ForStmt->getBeginLoc())) {
3254 return;
3255 }
3256
3257 const VarDecl *VD = ForStmt->getLoopVariable();
3258 if (!VD)
3259 return;
3260
3261 QualType VariableType = VD->getType();
3262
3263 if (VariableType->isIncompleteType())
3264 return;
3265
3266 const Expr *InitExpr = VD->getInit();
3267 if (!InitExpr)
3268 return;
3269
3270 if (InitExpr->getExprLoc().isMacroID())
3271 return;
3272
3273 if (VariableType->isReferenceType()) {
3274 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
3275 RangeInitType: ForStmt->getRangeInit()->getType());
3276 } else if (VariableType.isConstQualified()) {
3277 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
3278 }
3279}
3280
3281/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
3282/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
3283/// body cannot be performed until after the type of the range variable is
3284/// determined.
3285StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
3286 if (!S || !B)
3287 return StmtError();
3288
3289 if (isa<ObjCForCollectionStmt>(Val: S))
3290 return FinishObjCForCollectionStmt(S, B);
3291
3292 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(Val: S);
3293 ForStmt->setBody(B);
3294
3295 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
3296 diag::warn_empty_range_based_for_body);
3297
3298 DiagnoseForRangeVariableCopies(SemaRef&: *this, ForStmt);
3299
3300 return S;
3301}
3302
3303StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
3304 SourceLocation LabelLoc,
3305 LabelDecl *TheDecl) {
3306 setFunctionHasBranchIntoScope();
3307 TheDecl->markUsed(Context);
3308 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
3309}
3310
3311StmtResult
3312Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
3313 Expr *E) {
3314 // Convert operand to void*
3315 if (!E->isTypeDependent()) {
3316 QualType ETy = E->getType();
3317 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
3318 ExprResult ExprRes = E;
3319 AssignConvertType ConvTy =
3320 CheckSingleAssignmentConstraints(LHSType: DestTy, RHS&: ExprRes);
3321 if (ExprRes.isInvalid())
3322 return StmtError();
3323 E = ExprRes.get();
3324 if (DiagnoseAssignmentResult(ConvTy, Loc: StarLoc, DstType: DestTy, SrcType: ETy, SrcExpr: E, Action: AA_Passing))
3325 return StmtError();
3326 }
3327
3328 ExprResult ExprRes = ActOnFinishFullExpr(Expr: E, /*DiscardedValue*/ false);
3329 if (ExprRes.isInvalid())
3330 return StmtError();
3331 E = ExprRes.get();
3332
3333 setFunctionHasIndirectGoto();
3334
3335 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
3336}
3337
3338static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
3339 const Scope &DestScope) {
3340 if (!S.CurrentSEHFinally.empty() &&
3341 DestScope.Contains(rhs: *S.CurrentSEHFinally.back())) {
3342 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
3343 }
3344}
3345
3346StmtResult
3347Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
3348 Scope *S = CurScope->getContinueParent();
3349 if (!S) {
3350 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
3351 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
3352 }
3353 if (S->isConditionVarScope()) {
3354 // We cannot 'continue;' from within a statement expression in the
3355 // initializer of a condition variable because we would jump past the
3356 // initialization of that variable.
3357 return StmtError(Diag(ContinueLoc, diag::err_continue_from_cond_var_init));
3358 }
3359 CheckJumpOutOfSEHFinally(S&: *this, Loc: ContinueLoc, DestScope: *S);
3360
3361 return new (Context) ContinueStmt(ContinueLoc);
3362}
3363
3364StmtResult
3365Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
3366 Scope *S = CurScope->getBreakParent();
3367 if (!S) {
3368 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
3369 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
3370 }
3371 if (S->isOpenMPLoopScope())
3372 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
3373 << "break");
3374 CheckJumpOutOfSEHFinally(S&: *this, Loc: BreakLoc, DestScope: *S);
3375
3376 return new (Context) BreakStmt(BreakLoc);
3377}
3378
3379/// Determine whether the given expression might be move-eligible or
3380/// copy-elidable in either a (co_)return statement or throw expression,
3381/// without considering function return type, if applicable.
3382///
3383/// \param E The expression being returned from the function or block,
3384/// being thrown, or being co_returned from a coroutine. This expression
3385/// might be modified by the implementation.
3386///
3387/// \param Mode Overrides detection of current language mode
3388/// and uses the rules for C++23.
3389///
3390/// \returns An aggregate which contains the Candidate and isMoveEligible
3391/// and isCopyElidable methods. If Candidate is non-null, it means
3392/// isMoveEligible() would be true under the most permissive language standard.
3393Sema::NamedReturnInfo Sema::getNamedReturnInfo(Expr *&E,
3394 SimplerImplicitMoveMode Mode) {
3395 if (!E)
3396 return NamedReturnInfo();
3397 // - in a return statement in a function [where] ...
3398 // ... the expression is the name of a non-volatile automatic object ...
3399 const auto *DR = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens());
3400 if (!DR || DR->refersToEnclosingVariableOrCapture())
3401 return NamedReturnInfo();
3402 const auto *VD = dyn_cast<VarDecl>(Val: DR->getDecl());
3403 if (!VD)
3404 return NamedReturnInfo();
3405 if (VD->getInit() && VD->getInit()->containsErrors())
3406 return NamedReturnInfo();
3407 NamedReturnInfo Res = getNamedReturnInfo(VD);
3408 if (Res.Candidate && !E->isXValue() &&
3409 (Mode == SimplerImplicitMoveMode::ForceOn ||
3410 (Mode != SimplerImplicitMoveMode::ForceOff &&
3411 getLangOpts().CPlusPlus23))) {
3412 E = ImplicitCastExpr::Create(Context, T: VD->getType().getNonReferenceType(),
3413 Kind: CK_NoOp, Operand: E, BasePath: nullptr, Cat: VK_XValue,
3414 FPO: FPOptionsOverride());
3415 }
3416 return Res;
3417}
3418
3419/// Determine whether the given NRVO candidate variable is move-eligible or
3420/// copy-elidable, without considering function return type.
3421///
3422/// \param VD The NRVO candidate variable.
3423///
3424/// \returns An aggregate which contains the Candidate and isMoveEligible
3425/// and isCopyElidable methods. If Candidate is non-null, it means
3426/// isMoveEligible() would be true under the most permissive language standard.
3427Sema::NamedReturnInfo Sema::getNamedReturnInfo(const VarDecl *VD) {
3428 NamedReturnInfo Info{.Candidate: VD, .S: NamedReturnInfo::MoveEligibleAndCopyElidable};
3429
3430 // C++20 [class.copy.elision]p3:
3431 // - in a return statement in a function with ...
3432 // (other than a function ... parameter)
3433 if (VD->getKind() == Decl::ParmVar)
3434 Info.S = NamedReturnInfo::MoveEligible;
3435 else if (VD->getKind() != Decl::Var)
3436 return NamedReturnInfo();
3437
3438 // (other than ... a catch-clause parameter)
3439 if (VD->isExceptionVariable())
3440 Info.S = NamedReturnInfo::MoveEligible;
3441
3442 // ...automatic...
3443 if (!VD->hasLocalStorage())
3444 return NamedReturnInfo();
3445
3446 // We don't want to implicitly move out of a __block variable during a return
3447 // because we cannot assume the variable will no longer be used.
3448 if (VD->hasAttr<BlocksAttr>())
3449 return NamedReturnInfo();
3450
3451 QualType VDType = VD->getType();
3452 if (VDType->isObjectType()) {
3453 // C++17 [class.copy.elision]p3:
3454 // ...non-volatile automatic object...
3455 if (VDType.isVolatileQualified())
3456 return NamedReturnInfo();
3457 } else if (VDType->isRValueReferenceType()) {
3458 // C++20 [class.copy.elision]p3:
3459 // ...either a non-volatile object or an rvalue reference to a non-volatile
3460 // object type...
3461 QualType VDReferencedType = VDType.getNonReferenceType();
3462 if (VDReferencedType.isVolatileQualified() ||
3463 !VDReferencedType->isObjectType())
3464 return NamedReturnInfo();
3465 Info.S = NamedReturnInfo::MoveEligible;
3466 } else {
3467 return NamedReturnInfo();
3468 }
3469
3470 // Variables with higher required alignment than their type's ABI
3471 // alignment cannot use NRVO.
3472 if (!VD->hasDependentAlignment() &&
3473 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(T: VDType))
3474 Info.S = NamedReturnInfo::MoveEligible;
3475
3476 return Info;
3477}
3478
3479/// Updates given NamedReturnInfo's move-eligible and
3480/// copy-elidable statuses, considering the function
3481/// return type criteria as applicable to return statements.
3482///
3483/// \param Info The NamedReturnInfo object to update.
3484///
3485/// \param ReturnType This is the return type of the function.
3486/// \returns The copy elision candidate, in case the initial return expression
3487/// was copy elidable, or nullptr otherwise.
3488const VarDecl *Sema::getCopyElisionCandidate(NamedReturnInfo &Info,
3489 QualType ReturnType) {
3490 if (!Info.Candidate)
3491 return nullptr;
3492
3493 auto invalidNRVO = [&] {
3494 Info = NamedReturnInfo();
3495 return nullptr;
3496 };
3497
3498 // If we got a non-deduced auto ReturnType, we are in a dependent context and
3499 // there is no point in allowing copy elision since we won't have it deduced
3500 // by the point the VardDecl is instantiated, which is the last chance we have
3501 // of deciding if the candidate is really copy elidable.
3502 if ((ReturnType->getTypeClass() == Type::TypeClass::Auto &&
3503 ReturnType->isCanonicalUnqualified()) ||
3504 ReturnType->isSpecificBuiltinType(BuiltinType::Dependent))
3505 return invalidNRVO();
3506
3507 if (!ReturnType->isDependentType()) {
3508 // - in a return statement in a function with ...
3509 // ... a class return type ...
3510 if (!ReturnType->isRecordType())
3511 return invalidNRVO();
3512
3513 QualType VDType = Info.Candidate->getType();
3514 // ... the same cv-unqualified type as the function return type ...
3515 // When considering moving this expression out, allow dissimilar types.
3516 if (!VDType->isDependentType() &&
3517 !Context.hasSameUnqualifiedType(T1: ReturnType, T2: VDType))
3518 Info.S = NamedReturnInfo::MoveEligible;
3519 }
3520 return Info.isCopyElidable() ? Info.Candidate : nullptr;
3521}
3522
3523/// Verify that the initialization sequence that was picked for the
3524/// first overload resolution is permissible under C++98.
3525///
3526/// Reject (possibly converting) constructors not taking an rvalue reference,
3527/// or user conversion operators which are not ref-qualified.
3528static bool
3529VerifyInitializationSequenceCXX98(const Sema &S,
3530 const InitializationSequence &Seq) {
3531 const auto *Step = llvm::find_if(Range: Seq.steps(), P: [](const auto &Step) {
3532 return Step.Kind == InitializationSequence::SK_ConstructorInitialization ||
3533 Step.Kind == InitializationSequence::SK_UserConversion;
3534 });
3535 if (Step != Seq.step_end()) {
3536 const auto *FD = Step->Function.Function;
3537 if (isa<CXXConstructorDecl>(Val: FD)
3538 ? !FD->getParamDecl(i: 0)->getType()->isRValueReferenceType()
3539 : cast<CXXMethodDecl>(Val: FD)->getRefQualifier() == RQ_None)
3540 return false;
3541 }
3542 return true;
3543}
3544
3545/// Perform the initialization of a potentially-movable value, which
3546/// is the result of return value.
3547///
3548/// This routine implements C++20 [class.copy.elision]p3, which attempts to
3549/// treat returned lvalues as rvalues in certain cases (to prefer move
3550/// construction), then falls back to treating them as lvalues if that failed.
3551ExprResult Sema::PerformMoveOrCopyInitialization(
3552 const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value,
3553 bool SupressSimplerImplicitMoves) {
3554 if (getLangOpts().CPlusPlus &&
3555 (!getLangOpts().CPlusPlus23 || SupressSimplerImplicitMoves) &&
3556 NRInfo.isMoveEligible()) {
3557 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
3558 CK_NoOp, Value, VK_XValue, FPOptionsOverride());
3559 Expr *InitExpr = &AsRvalue;
3560 auto Kind = InitializationKind::CreateCopy(InitLoc: Value->getBeginLoc(),
3561 EqualLoc: Value->getBeginLoc());
3562 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3563 auto Res = Seq.getFailedOverloadResult();
3564 if ((Res == OR_Success || Res == OR_Deleted) &&
3565 (getLangOpts().CPlusPlus11 ||
3566 VerifyInitializationSequenceCXX98(S: *this, Seq))) {
3567 // Promote "AsRvalue" to the heap, since we now need this
3568 // expression node to persist.
3569 Value =
3570 ImplicitCastExpr::Create(Context, T: Value->getType(), Kind: CK_NoOp, Operand: Value,
3571 BasePath: nullptr, Cat: VK_XValue, FPO: FPOptionsOverride());
3572 // Complete type-checking the initialization of the return type
3573 // using the constructor we found.
3574 return Seq.Perform(S&: *this, Entity, Kind: Kind, Args: Value);
3575 }
3576 }
3577 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3578 // above, or overload resolution failed. Either way, we need to try
3579 // (again) now with the return value expression as written.
3580 return PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Value);
3581}
3582
3583/// Determine whether the declared return type of the specified function
3584/// contains 'auto'.
3585static bool hasDeducedReturnType(FunctionDecl *FD) {
3586 const FunctionProtoType *FPT =
3587 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
3588 return FPT->getReturnType()->isUndeducedType();
3589}
3590
3591/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3592/// for capturing scopes.
3593///
3594StmtResult Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc,
3595 Expr *RetValExp,
3596 NamedReturnInfo &NRInfo,
3597 bool SupressSimplerImplicitMoves) {
3598 // If this is the first return we've seen, infer the return type.
3599 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3600 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(Val: getCurFunction());
3601 QualType FnRetType = CurCap->ReturnType;
3602 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(Val: CurCap);
3603 if (CurLambda && CurLambda->CallOperator->getType().isNull())
3604 return StmtError();
3605 bool HasDeducedReturnType =
3606 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
3607
3608 if (ExprEvalContexts.back().isDiscardedStatementContext() &&
3609 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3610 if (RetValExp) {
3611 ExprResult ER =
3612 ActOnFinishFullExpr(Expr: RetValExp, CC: ReturnLoc, /*DiscardedValue*/ false);
3613 if (ER.isInvalid())
3614 return StmtError();
3615 RetValExp = ER.get();
3616 }
3617 return ReturnStmt::Create(Ctx: Context, RL: ReturnLoc, E: RetValExp,
3618 /* NRVOCandidate=*/nullptr);
3619 }
3620
3621 if (HasDeducedReturnType) {
3622 FunctionDecl *FD = CurLambda->CallOperator;
3623 // If we've already decided this lambda is invalid, e.g. because
3624 // we saw a `return` whose expression had an error, don't keep
3625 // trying to deduce its return type.
3626 if (FD->isInvalidDecl())
3627 return StmtError();
3628 // In C++1y, the return type may involve 'auto'.
3629 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3630 if (CurCap->ReturnType.isNull())
3631 CurCap->ReturnType = FD->getReturnType();
3632
3633 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3634 assert(AT && "lost auto type from lambda return type");
3635 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetExpr: RetValExp, AT)) {
3636 FD->setInvalidDecl();
3637 // FIXME: preserve the ill-formed return expression.
3638 return StmtError();
3639 }
3640 CurCap->ReturnType = FnRetType = FD->getReturnType();
3641 } else if (CurCap->HasImplicitReturnType) {
3642 // For blocks/lambdas with implicit return types, we check each return
3643 // statement individually, and deduce the common return type when the block
3644 // or lambda is completed.
3645 // FIXME: Fold this into the 'auto' codepath above.
3646 if (RetValExp && !isa<InitListExpr>(Val: RetValExp)) {
3647 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RetValExp);
3648 if (Result.isInvalid())
3649 return StmtError();
3650 RetValExp = Result.get();
3651
3652 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3653 // when deducing a return type for a lambda-expression (or by extension
3654 // for a block). These rules differ from the stated C++11 rules only in
3655 // that they remove top-level cv-qualifiers.
3656 if (!CurContext->isDependentContext())
3657 FnRetType = RetValExp->getType().getUnqualifiedType();
3658 else
3659 FnRetType = CurCap->ReturnType = Context.DependentTy;
3660 } else {
3661 if (RetValExp) {
3662 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3663 // initializer list, because it is not an expression (even
3664 // though we represent it as one). We still deduce 'void'.
3665 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3666 << RetValExp->getSourceRange();
3667 }
3668
3669 FnRetType = Context.VoidTy;
3670 }
3671
3672 // Although we'll properly infer the type of the block once it's completed,
3673 // make sure we provide a return type now for better error recovery.
3674 if (CurCap->ReturnType.isNull())
3675 CurCap->ReturnType = FnRetType;
3676 }
3677 const VarDecl *NRVOCandidate = getCopyElisionCandidate(Info&: NRInfo, ReturnType: FnRetType);
3678
3679 if (auto *CurBlock = dyn_cast<BlockScopeInfo>(Val: CurCap)) {
3680 if (CurBlock->FunctionType->castAs<FunctionType>()->getNoReturnAttr()) {
3681 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3682 return StmtError();
3683 }
3684 } else if (auto *CurRegion = dyn_cast<CapturedRegionScopeInfo>(Val: CurCap)) {
3685 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3686 return StmtError();
3687 } else {
3688 assert(CurLambda && "unknown kind of captured scope");
3689 if (CurLambda->CallOperator->getType()
3690 ->castAs<FunctionType>()
3691 ->getNoReturnAttr()) {
3692 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3693 return StmtError();
3694 }
3695 }
3696
3697 // Otherwise, verify that this result type matches the previous one. We are
3698 // pickier with blocks than for normal functions because we don't have GCC
3699 // compatibility to worry about here.
3700 if (FnRetType->isDependentType()) {
3701 // Delay processing for now. TODO: there are lots of dependent
3702 // types we can conclusively prove aren't void.
3703 } else if (FnRetType->isVoidType()) {
3704 if (RetValExp && !isa<InitListExpr>(Val: RetValExp) &&
3705 !(getLangOpts().CPlusPlus &&
3706 (RetValExp->isTypeDependent() ||
3707 RetValExp->getType()->isVoidType()))) {
3708 if (!getLangOpts().CPlusPlus &&
3709 RetValExp->getType()->isVoidType())
3710 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
3711 else {
3712 Diag(ReturnLoc, diag::err_return_block_has_expr);
3713 RetValExp = nullptr;
3714 }
3715 }
3716 } else if (!RetValExp) {
3717 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3718 } else if (!RetValExp->isTypeDependent()) {
3719 // we have a non-void block with an expression, continue checking
3720
3721 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3722 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3723 // function return.
3724
3725 // In C++ the return statement is handled via a copy initialization.
3726 // the C version of which boils down to CheckSingleAssignmentConstraints.
3727 InitializedEntity Entity =
3728 InitializedEntity::InitializeResult(ReturnLoc, Type: FnRetType);
3729 ExprResult Res = PerformMoveOrCopyInitialization(
3730 Entity, NRInfo, Value: RetValExp, SupressSimplerImplicitMoves);
3731 if (Res.isInvalid()) {
3732 // FIXME: Cleanup temporaries here, anyway?
3733 return StmtError();
3734 }
3735 RetValExp = Res.get();
3736 CheckReturnValExpr(RetValExp, lhsType: FnRetType, ReturnLoc);
3737 }
3738
3739 if (RetValExp) {
3740 ExprResult ER =
3741 ActOnFinishFullExpr(Expr: RetValExp, CC: ReturnLoc, /*DiscardedValue*/ false);
3742 if (ER.isInvalid())
3743 return StmtError();
3744 RetValExp = ER.get();
3745 }
3746 auto *Result =
3747 ReturnStmt::Create(Ctx: Context, RL: ReturnLoc, E: RetValExp, NRVOCandidate);
3748
3749 // If we need to check for the named return value optimization,
3750 // or if we need to infer the return type,
3751 // save the return statement in our scope for later processing.
3752 if (CurCap->HasImplicitReturnType || NRVOCandidate)
3753 FunctionScopes.back()->Returns.push_back(Elt: Result);
3754
3755 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3756 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3757
3758 if (auto *CurBlock = dyn_cast<BlockScopeInfo>(Val: CurCap);
3759 CurBlock && CurCap->HasImplicitReturnType && RetValExp &&
3760 RetValExp->containsErrors())
3761 CurBlock->TheDecl->setInvalidDecl();
3762
3763 return Result;
3764}
3765
3766namespace {
3767/// Marks all typedefs in all local classes in a type referenced.
3768///
3769/// In a function like
3770/// auto f() {
3771/// struct S { typedef int a; };
3772/// return S();
3773/// }
3774///
3775/// the local type escapes and could be referenced in some TUs but not in
3776/// others. Pretend that all local typedefs are always referenced, to not warn
3777/// on this. This isn't necessary if f has internal linkage, or the typedef
3778/// is private.
3779class LocalTypedefNameReferencer
3780 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3781public:
3782 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3783 bool VisitRecordType(const RecordType *RT);
3784private:
3785 Sema &S;
3786};
3787bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3788 auto *R = dyn_cast<CXXRecordDecl>(Val: RT->getDecl());
3789 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3790 R->isDependentType())
3791 return true;
3792 for (auto *TmpD : R->decls())
3793 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3794 if (T->getAccess() != AS_private || R->hasFriends())
3795 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3796 return true;
3797}
3798}
3799
3800TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
3801 return FD->getTypeSourceInfo()
3802 ->getTypeLoc()
3803 .getAsAdjusted<FunctionProtoTypeLoc>()
3804 .getReturnLoc();
3805}
3806
3807/// Deduce the return type for a function from a returned expression, per
3808/// C++1y [dcl.spec.auto]p6.
3809bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3810 SourceLocation ReturnLoc,
3811 Expr *RetExpr, const AutoType *AT) {
3812 // If this is the conversion function for a lambda, we choose to deduce its
3813 // type from the corresponding call operator, not from the synthesized return
3814 // statement within it. See Sema::DeduceReturnType.
3815 if (isLambdaConversionOperator(FD))
3816 return false;
3817
3818 if (RetExpr && isa<InitListExpr>(Val: RetExpr)) {
3819 // If the deduction is for a return statement and the initializer is
3820 // a braced-init-list, the program is ill-formed.
3821 Diag(RetExpr->getExprLoc(),
3822 getCurLambda() ? diag::err_lambda_return_init_list
3823 : diag::err_auto_fn_return_init_list)
3824 << RetExpr->getSourceRange();
3825 return true;
3826 }
3827
3828 if (FD->isDependentContext()) {
3829 // C++1y [dcl.spec.auto]p12:
3830 // Return type deduction [...] occurs when the definition is
3831 // instantiated even if the function body contains a return
3832 // statement with a non-type-dependent operand.
3833 assert(AT->isDeduced() && "should have deduced to dependent type");
3834 return false;
3835 }
3836
3837 TypeLoc OrigResultType = getReturnTypeLoc(FD);
3838 // In the case of a return with no operand, the initializer is considered
3839 // to be void().
3840 CXXScalarValueInitExpr VoidVal(Context.VoidTy, nullptr, SourceLocation());
3841 if (!RetExpr) {
3842 // For a function with a deduced result type to return with omitted
3843 // expression, the result type as written must be 'auto' or
3844 // 'decltype(auto)', possibly cv-qualified or constrained, but not
3845 // ref-qualified.
3846 if (!OrigResultType.getType()->getAs<AutoType>()) {
3847 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3848 << OrigResultType.getType();
3849 return true;
3850 }
3851 RetExpr = &VoidVal;
3852 }
3853
3854 QualType Deduced = AT->getDeducedType();
3855 {
3856 // Otherwise, [...] deduce a value for U using the rules of template
3857 // argument deduction.
3858 auto RetExprLoc = RetExpr->getExprLoc();
3859 TemplateDeductionInfo Info(RetExprLoc);
3860 SourceLocation TemplateSpecLoc;
3861 if (RetExpr->getType() == Context.OverloadTy) {
3862 auto FindResult = OverloadExpr::find(E: RetExpr);
3863 if (FindResult.Expression)
3864 TemplateSpecLoc = FindResult.Expression->getNameLoc();
3865 }
3866 TemplateSpecCandidateSet FailedTSC(TemplateSpecLoc);
3867 TemplateDeductionResult Res = DeduceAutoType(
3868 AutoTypeLoc: OrigResultType, Initializer: RetExpr, Result&: Deduced, Info, /*DependentDeduction=*/false,
3869 /*IgnoreConstraints=*/false, FailedTSC: &FailedTSC);
3870 if (Res != TemplateDeductionResult::Success && FD->isInvalidDecl())
3871 return true;
3872 switch (Res) {
3873 case TemplateDeductionResult::Success:
3874 break;
3875 case TemplateDeductionResult::AlreadyDiagnosed:
3876 return true;
3877 case TemplateDeductionResult::Inconsistent: {
3878 // If a function with a declared return type that contains a placeholder
3879 // type has multiple return statements, the return type is deduced for
3880 // each return statement. [...] if the type deduced is not the same in
3881 // each deduction, the program is ill-formed.
3882 const LambdaScopeInfo *LambdaSI = getCurLambda();
3883 if (LambdaSI && LambdaSI->HasImplicitReturnType)
3884 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3885 << Info.SecondArg << Info.FirstArg << true /*IsLambda*/;
3886 else
3887 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3888 << (AT->isDecltypeAuto() ? 1 : 0) << Info.SecondArg
3889 << Info.FirstArg;
3890 return true;
3891 }
3892 default:
3893 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3894 << OrigResultType.getType() << RetExpr->getType();
3895 FailedTSC.NoteCandidates(S&: *this, Loc: RetExprLoc);
3896 return true;
3897 }
3898 }
3899
3900 // If a local type is part of the returned type, mark its fields as
3901 // referenced.
3902 LocalTypedefNameReferencer(*this).TraverseType(T: RetExpr->getType());
3903
3904 // CUDA: Kernel function must have 'void' return type.
3905 if (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>() &&
3906 !Deduced->isVoidType()) {
3907 Diag(FD->getLocation(), diag::err_kern_type_not_void_return)
3908 << FD->getType() << FD->getSourceRange();
3909 return true;
3910 }
3911
3912 if (!FD->isInvalidDecl() && AT->getDeducedType() != Deduced)
3913 // Update all declarations of the function to have the deduced return type.
3914 Context.adjustDeducedFunctionResultType(FD, ResultType: Deduced);
3915
3916 return false;
3917}
3918
3919StmtResult
3920Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3921 Scope *CurScope) {
3922 // Correct typos, in case the containing function returns 'auto' and
3923 // RetValExp should determine the deduced type.
3924 ExprResult RetVal = CorrectDelayedTyposInExpr(
3925 E: RetValExp, InitDecl: nullptr, /*RecoverUncorrectedTypos=*/true);
3926 if (RetVal.isInvalid())
3927 return StmtError();
3928 StmtResult R =
3929 BuildReturnStmt(ReturnLoc, RetValExp: RetVal.get(), /*AllowRecovery=*/true);
3930 if (R.isInvalid() || ExprEvalContexts.back().isDiscardedStatementContext())
3931 return R;
3932
3933 VarDecl *VD =
3934 const_cast<VarDecl *>(cast<ReturnStmt>(Val: R.get())->getNRVOCandidate());
3935
3936 CurScope->updateNRVOCandidate(VD);
3937
3938 CheckJumpOutOfSEHFinally(S&: *this, Loc: ReturnLoc, DestScope: *CurScope->getFnParent());
3939
3940 return R;
3941}
3942
3943static bool CheckSimplerImplicitMovesMSVCWorkaround(const Sema &S,
3944 const Expr *E) {
3945 if (!E || !S.getLangOpts().CPlusPlus23 || !S.getLangOpts().MSVCCompat)
3946 return false;
3947 const Decl *D = E->getReferencedDeclOfCallee();
3948 if (!D || !S.SourceMgr.isInSystemHeader(Loc: D->getLocation()))
3949 return false;
3950 for (const DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent()) {
3951 if (DC->isStdNamespace())
3952 return true;
3953 }
3954 return false;
3955}
3956
3957StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3958 bool AllowRecovery) {
3959 // Check for unexpanded parameter packs.
3960 if (RetValExp && DiagnoseUnexpandedParameterPack(E: RetValExp))
3961 return StmtError();
3962
3963 // HACK: We suppress simpler implicit move here in msvc compatibility mode
3964 // just as a temporary work around, as the MSVC STL has issues with
3965 // this change.
3966 bool SupressSimplerImplicitMoves =
3967 CheckSimplerImplicitMovesMSVCWorkaround(S: *this, E: RetValExp);
3968 NamedReturnInfo NRInfo = getNamedReturnInfo(
3969 E&: RetValExp, Mode: SupressSimplerImplicitMoves ? SimplerImplicitMoveMode::ForceOff
3970 : SimplerImplicitMoveMode::Normal);
3971
3972 if (isa<CapturingScopeInfo>(Val: getCurFunction()))
3973 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp, NRInfo,
3974 SupressSimplerImplicitMoves);
3975
3976 QualType FnRetType;
3977 QualType RelatedRetType;
3978 const AttrVec *Attrs = nullptr;
3979 bool isObjCMethod = false;
3980
3981 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3982 FnRetType = FD->getReturnType();
3983 if (FD->hasAttrs())
3984 Attrs = &FD->getAttrs();
3985 if (FD->isNoReturn())
3986 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) << FD;
3987 if (FD->isMain() && RetValExp)
3988 if (isa<CXXBoolLiteralExpr>(RetValExp))
3989 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3990 << RetValExp->getSourceRange();
3991 if (FD->hasAttr<CmseNSEntryAttr>() && RetValExp) {
3992 if (const auto *RT = dyn_cast<RecordType>(Val: FnRetType.getCanonicalType())) {
3993 if (RT->getDecl()->isOrContainsUnion())
3994 Diag(RetValExp->getBeginLoc(), diag::warn_cmse_nonsecure_union) << 1;
3995 }
3996 }
3997 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3998 FnRetType = MD->getReturnType();
3999 isObjCMethod = true;
4000 if (MD->hasAttrs())
4001 Attrs = &MD->getAttrs();
4002 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
4003 // In the implementation of a method with a related return type, the
4004 // type used to type-check the validity of return statements within the
4005 // method body is a pointer to the type of the class being implemented.
4006 RelatedRetType = Context.getObjCInterfaceType(Decl: MD->getClassInterface());
4007 RelatedRetType = Context.getObjCObjectPointerType(OIT: RelatedRetType);
4008 }
4009 } else // If we don't have a function/method context, bail.
4010 return StmtError();
4011
4012 if (RetValExp) {
4013 const auto *ATy = dyn_cast<ArrayType>(Val: RetValExp->getType());
4014 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
4015 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
4016 return StmtError();
4017 }
4018 }
4019
4020 // C++1z: discarded return statements are not considered when deducing a
4021 // return type.
4022 if (ExprEvalContexts.back().isDiscardedStatementContext() &&
4023 FnRetType->getContainedAutoType()) {
4024 if (RetValExp) {
4025 ExprResult ER =
4026 ActOnFinishFullExpr(Expr: RetValExp, CC: ReturnLoc, /*DiscardedValue*/ false);
4027 if (ER.isInvalid())
4028 return StmtError();
4029 RetValExp = ER.get();
4030 }
4031 return ReturnStmt::Create(Ctx: Context, RL: ReturnLoc, E: RetValExp,
4032 /* NRVOCandidate=*/nullptr);
4033 }
4034
4035 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
4036 // deduction.
4037 if (getLangOpts().CPlusPlus14) {
4038 if (AutoType *AT = FnRetType->getContainedAutoType()) {
4039 FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
4040 // If we've already decided this function is invalid, e.g. because
4041 // we saw a `return` whose expression had an error, don't keep
4042 // trying to deduce its return type.
4043 // (Some return values may be needlessly wrapped in RecoveryExpr).
4044 if (FD->isInvalidDecl() ||
4045 DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetExpr: RetValExp, AT)) {
4046 FD->setInvalidDecl();
4047 if (!AllowRecovery)
4048 return StmtError();
4049 // The deduction failure is diagnosed and marked, try to recover.
4050 if (RetValExp) {
4051 // Wrap return value with a recovery expression of the previous type.
4052 // If no deduction yet, use DependentTy.
4053 auto Recovery = CreateRecoveryExpr(
4054 Begin: RetValExp->getBeginLoc(), End: RetValExp->getEndLoc(), SubExprs: RetValExp,
4055 T: AT->isDeduced() ? FnRetType : QualType());
4056 if (Recovery.isInvalid())
4057 return StmtError();
4058 RetValExp = Recovery.get();
4059 } else {
4060 // Nothing to do: a ReturnStmt with no value is fine recovery.
4061 }
4062 } else {
4063 FnRetType = FD->getReturnType();
4064 }
4065 }
4066 }
4067 const VarDecl *NRVOCandidate = getCopyElisionCandidate(Info&: NRInfo, ReturnType: FnRetType);
4068
4069 bool HasDependentReturnType = FnRetType->isDependentType();
4070
4071 ReturnStmt *Result = nullptr;
4072 if (FnRetType->isVoidType()) {
4073 if (RetValExp) {
4074 if (auto *ILE = dyn_cast<InitListExpr>(Val: RetValExp)) {
4075 // We simply never allow init lists as the return value of void
4076 // functions. This is compatible because this was never allowed before,
4077 // so there's no legacy code to deal with.
4078 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4079 int FunctionKind = 0;
4080 if (isa<ObjCMethodDecl>(Val: CurDecl))
4081 FunctionKind = 1;
4082 else if (isa<CXXConstructorDecl>(Val: CurDecl))
4083 FunctionKind = 2;
4084 else if (isa<CXXDestructorDecl>(Val: CurDecl))
4085 FunctionKind = 3;
4086
4087 Diag(ReturnLoc, diag::err_return_init_list)
4088 << CurDecl << FunctionKind << RetValExp->getSourceRange();
4089
4090 // Preserve the initializers in the AST.
4091 RetValExp = AllowRecovery
4092 ? CreateRecoveryExpr(Begin: ILE->getLBraceLoc(),
4093 End: ILE->getRBraceLoc(), SubExprs: ILE->inits())
4094 .get()
4095 : nullptr;
4096 } else if (!RetValExp->isTypeDependent()) {
4097 // C99 6.8.6.4p1 (ext_ since GCC warns)
4098 unsigned D = diag::ext_return_has_expr;
4099 if (RetValExp->getType()->isVoidType()) {
4100 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4101 if (isa<CXXConstructorDecl>(CurDecl) ||
4102 isa<CXXDestructorDecl>(CurDecl))
4103 D = diag::err_ctor_dtor_returns_void;
4104 else
4105 D = diag::ext_return_has_void_expr;
4106 }
4107 else {
4108 ExprResult Result = RetValExp;
4109 Result = IgnoredValueConversions(E: Result.get());
4110 if (Result.isInvalid())
4111 return StmtError();
4112 RetValExp = Result.get();
4113 RetValExp = ImpCastExprToType(E: RetValExp,
4114 Type: Context.VoidTy, CK: CK_ToVoid).get();
4115 }
4116 // return of void in constructor/destructor is illegal in C++.
4117 if (D == diag::err_ctor_dtor_returns_void) {
4118 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4119 Diag(Loc: ReturnLoc, DiagID: D) << CurDecl << isa<CXXDestructorDecl>(Val: CurDecl)
4120 << RetValExp->getSourceRange();
4121 }
4122 // return (some void expression); is legal in C++.
4123 else if (D != diag::ext_return_has_void_expr ||
4124 !getLangOpts().CPlusPlus) {
4125 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4126
4127 int FunctionKind = 0;
4128 if (isa<ObjCMethodDecl>(Val: CurDecl))
4129 FunctionKind = 1;
4130 else if (isa<CXXConstructorDecl>(Val: CurDecl))
4131 FunctionKind = 2;
4132 else if (isa<CXXDestructorDecl>(Val: CurDecl))
4133 FunctionKind = 3;
4134
4135 Diag(Loc: ReturnLoc, DiagID: D)
4136 << CurDecl << FunctionKind << RetValExp->getSourceRange();
4137 }
4138 }
4139
4140 if (RetValExp) {
4141 ExprResult ER =
4142 ActOnFinishFullExpr(Expr: RetValExp, CC: ReturnLoc, /*DiscardedValue*/ false);
4143 if (ER.isInvalid())
4144 return StmtError();
4145 RetValExp = ER.get();
4146 }
4147 }
4148
4149 Result = ReturnStmt::Create(Ctx: Context, RL: ReturnLoc, E: RetValExp,
4150 /* NRVOCandidate=*/nullptr);
4151 } else if (!RetValExp && !HasDependentReturnType) {
4152 FunctionDecl *FD = getCurFunctionDecl();
4153
4154 if ((FD && FD->isInvalidDecl()) || FnRetType->containsErrors()) {
4155 // The intended return type might have been "void", so don't warn.
4156 } else if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
4157 // C++11 [stmt.return]p2
4158 Diag(ReturnLoc, diag::err_constexpr_return_missing_expr)
4159 << FD << FD->isConsteval();
4160 FD->setInvalidDecl();
4161 } else {
4162 // C99 6.8.6.4p1 (ext_ since GCC warns)
4163 // C90 6.6.6.4p4
4164 unsigned DiagID = getLangOpts().C99 ? diag::ext_return_missing_expr
4165 : diag::warn_return_missing_expr;
4166 // Note that at this point one of getCurFunctionDecl() or
4167 // getCurMethodDecl() must be non-null (see above).
4168 assert((getCurFunctionDecl() || getCurMethodDecl()) &&
4169 "Not in a FunctionDecl or ObjCMethodDecl?");
4170 bool IsMethod = FD == nullptr;
4171 const NamedDecl *ND =
4172 IsMethod ? cast<NamedDecl>(Val: getCurMethodDecl()) : cast<NamedDecl>(Val: FD);
4173 Diag(Loc: ReturnLoc, DiagID) << ND << IsMethod;
4174 }
4175
4176 Result = ReturnStmt::Create(Ctx: Context, RL: ReturnLoc, /* RetExpr=*/E: nullptr,
4177 /* NRVOCandidate=*/nullptr);
4178 } else {
4179 assert(RetValExp || HasDependentReturnType);
4180 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
4181
4182 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
4183 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
4184 // function return.
4185
4186 // In C++ the return statement is handled via a copy initialization,
4187 // the C version of which boils down to CheckSingleAssignmentConstraints.
4188 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
4189 // we have a non-void function with an expression, continue checking
4190 InitializedEntity Entity =
4191 InitializedEntity::InitializeResult(ReturnLoc, Type: RetType);
4192 ExprResult Res = PerformMoveOrCopyInitialization(
4193 Entity, NRInfo, Value: RetValExp, SupressSimplerImplicitMoves);
4194 if (Res.isInvalid() && AllowRecovery)
4195 Res = CreateRecoveryExpr(Begin: RetValExp->getBeginLoc(),
4196 End: RetValExp->getEndLoc(), SubExprs: RetValExp, T: RetType);
4197 if (Res.isInvalid()) {
4198 // FIXME: Clean up temporaries here anyway?
4199 return StmtError();
4200 }
4201 RetValExp = Res.getAs<Expr>();
4202
4203 // If we have a related result type, we need to implicitly
4204 // convert back to the formal result type. We can't pretend to
4205 // initialize the result again --- we might end double-retaining
4206 // --- so instead we initialize a notional temporary.
4207 if (!RelatedRetType.isNull()) {
4208 Entity = InitializedEntity::InitializeRelatedResult(MD: getCurMethodDecl(),
4209 Type: FnRetType);
4210 Res = PerformCopyInitialization(Entity, EqualLoc: ReturnLoc, Init: RetValExp);
4211 if (Res.isInvalid()) {
4212 // FIXME: Clean up temporaries here anyway?
4213 return StmtError();
4214 }
4215 RetValExp = Res.getAs<Expr>();
4216 }
4217
4218 CheckReturnValExpr(RetValExp, lhsType: FnRetType, ReturnLoc, isObjCMethod, Attrs,
4219 FD: getCurFunctionDecl());
4220 }
4221
4222 if (RetValExp) {
4223 ExprResult ER =
4224 ActOnFinishFullExpr(Expr: RetValExp, CC: ReturnLoc, /*DiscardedValue*/ false);
4225 if (ER.isInvalid())
4226 return StmtError();
4227 RetValExp = ER.get();
4228 }
4229 Result = ReturnStmt::Create(Ctx: Context, RL: ReturnLoc, E: RetValExp, NRVOCandidate);
4230 }
4231
4232 // If we need to check for the named return value optimization, save the
4233 // return statement in our scope for later processing.
4234 if (Result->getNRVOCandidate())
4235 FunctionScopes.back()->Returns.push_back(Elt: Result);
4236
4237 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
4238 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
4239
4240 return Result;
4241}
4242
4243StmtResult
4244Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
4245 SourceLocation RParen, Decl *Parm,
4246 Stmt *Body) {
4247 VarDecl *Var = cast_or_null<VarDecl>(Val: Parm);
4248 if (Var && Var->isInvalidDecl())
4249 return StmtError();
4250
4251 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
4252}
4253
4254StmtResult
4255Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
4256 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
4257}
4258
4259StmtResult
4260Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4261 MultiStmtArg CatchStmts, Stmt *Finally) {
4262 if (!getLangOpts().ObjCExceptions)
4263 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
4264
4265 // Objective-C try is incompatible with SEH __try.
4266 sema::FunctionScopeInfo *FSI = getCurFunction();
4267 if (FSI->FirstSEHTryLoc.isValid()) {
4268 Diag(AtLoc, diag::err_mixing_cxx_try_seh_try) << 1;
4269 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
4270 }
4271
4272 FSI->setHasObjCTry(AtLoc);
4273 unsigned NumCatchStmts = CatchStmts.size();
4274 return ObjCAtTryStmt::Create(Context, atTryLoc: AtLoc, atTryStmt: Try, CatchStmts: CatchStmts.data(),
4275 NumCatchStmts, atFinallyStmt: Finally);
4276}
4277
4278StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
4279 if (Throw) {
4280 ExprResult Result = DefaultLvalueConversion(E: Throw);
4281 if (Result.isInvalid())
4282 return StmtError();
4283
4284 Result = ActOnFinishFullExpr(Expr: Result.get(), /*DiscardedValue*/ false);
4285 if (Result.isInvalid())
4286 return StmtError();
4287 Throw = Result.get();
4288
4289 QualType ThrowType = Throw->getType();
4290 // Make sure the expression type is an ObjC pointer or "void *".
4291 if (!ThrowType->isDependentType() &&
4292 !ThrowType->isObjCObjectPointerType()) {
4293 const PointerType *PT = ThrowType->getAs<PointerType>();
4294 if (!PT || !PT->getPointeeType()->isVoidType())
4295 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
4296 << Throw->getType() << Throw->getSourceRange());
4297 }
4298 }
4299
4300 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
4301}
4302
4303StmtResult
4304Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4305 Scope *CurScope) {
4306 if (!getLangOpts().ObjCExceptions)
4307 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
4308
4309 if (!Throw) {
4310 // @throw without an expression designates a rethrow (which must occur
4311 // in the context of an @catch clause).
4312 Scope *AtCatchParent = CurScope;
4313 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
4314 AtCatchParent = AtCatchParent->getParent();
4315 if (!AtCatchParent)
4316 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
4317 }
4318 return BuildObjCAtThrowStmt(AtLoc, Throw);
4319}
4320
4321ExprResult
4322Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
4323 ExprResult result = DefaultLvalueConversion(E: operand);
4324 if (result.isInvalid())
4325 return ExprError();
4326 operand = result.get();
4327
4328 // Make sure the expression type is an ObjC pointer or "void *".
4329 QualType type = operand->getType();
4330 if (!type->isDependentType() &&
4331 !type->isObjCObjectPointerType()) {
4332 const PointerType *pointerType = type->getAs<PointerType>();
4333 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
4334 if (getLangOpts().CPlusPlus) {
4335 if (RequireCompleteType(atLoc, type,
4336 diag::err_incomplete_receiver_type))
4337 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
4338 << type << operand->getSourceRange();
4339
4340 ExprResult result = PerformContextuallyConvertToObjCPointer(From: operand);
4341 if (result.isInvalid())
4342 return ExprError();
4343 if (!result.isUsable())
4344 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
4345 << type << operand->getSourceRange();
4346
4347 operand = result.get();
4348 } else {
4349 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
4350 << type << operand->getSourceRange();
4351 }
4352 }
4353 }
4354
4355 // The operand to @synchronized is a full-expression.
4356 return ActOnFinishFullExpr(Expr: operand, /*DiscardedValue*/ false);
4357}
4358
4359StmtResult
4360Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
4361 Stmt *SyncBody) {
4362 // We can't jump into or indirect-jump out of a @synchronized block.
4363 setFunctionHasBranchProtectedScope();
4364 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
4365}
4366
4367/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
4368/// and creates a proper catch handler from them.
4369StmtResult
4370Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
4371 Stmt *HandlerBlock) {
4372 // There's nothing to test that ActOnExceptionDecl didn't already test.
4373 return new (Context)
4374 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(Val: ExDecl), HandlerBlock);
4375}
4376
4377StmtResult
4378Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
4379 setFunctionHasBranchProtectedScope();
4380 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
4381}
4382
4383namespace {
4384class CatchHandlerType {
4385 QualType QT;
4386 LLVM_PREFERRED_TYPE(bool)
4387 unsigned IsPointer : 1;
4388
4389 // This is a special constructor to be used only with DenseMapInfo's
4390 // getEmptyKey() and getTombstoneKey() functions.
4391 friend struct llvm::DenseMapInfo<CatchHandlerType>;
4392 enum Unique { ForDenseMap };
4393 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
4394
4395public:
4396 /// Used when creating a CatchHandlerType from a handler type; will determine
4397 /// whether the type is a pointer or reference and will strip off the top
4398 /// level pointer and cv-qualifiers.
4399 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
4400 if (QT->isPointerType())
4401 IsPointer = true;
4402
4403 QT = QT.getUnqualifiedType();
4404 if (IsPointer || QT->isReferenceType())
4405 QT = QT->getPointeeType();
4406 }
4407
4408 /// Used when creating a CatchHandlerType from a base class type; pretends the
4409 /// type passed in had the pointer qualifier, does not need to get an
4410 /// unqualified type.
4411 CatchHandlerType(QualType QT, bool IsPointer)
4412 : QT(QT), IsPointer(IsPointer) {}
4413
4414 QualType underlying() const { return QT; }
4415 bool isPointer() const { return IsPointer; }
4416
4417 friend bool operator==(const CatchHandlerType &LHS,
4418 const CatchHandlerType &RHS) {
4419 // If the pointer qualification does not match, we can return early.
4420 if (LHS.IsPointer != RHS.IsPointer)
4421 return false;
4422 // Otherwise, check the underlying type without cv-qualifiers.
4423 return LHS.QT == RHS.QT;
4424 }
4425};
4426} // namespace
4427
4428namespace llvm {
4429template <> struct DenseMapInfo<CatchHandlerType> {
4430 static CatchHandlerType getEmptyKey() {
4431 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
4432 CatchHandlerType::ForDenseMap);
4433 }
4434
4435 static CatchHandlerType getTombstoneKey() {
4436 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
4437 CatchHandlerType::ForDenseMap);
4438 }
4439
4440 static unsigned getHashValue(const CatchHandlerType &Base) {
4441 return DenseMapInfo<QualType>::getHashValue(Val: Base.underlying());
4442 }
4443
4444 static bool isEqual(const CatchHandlerType &LHS,
4445 const CatchHandlerType &RHS) {
4446 return LHS == RHS;
4447 }
4448};
4449}
4450
4451namespace {
4452class CatchTypePublicBases {
4453 const llvm::DenseMap<QualType, CXXCatchStmt *> &TypesToCheck;
4454
4455 CXXCatchStmt *FoundHandler;
4456 QualType FoundHandlerType;
4457 QualType TestAgainstType;
4458
4459public:
4460 CatchTypePublicBases(const llvm::DenseMap<QualType, CXXCatchStmt *> &T,
4461 QualType QT)
4462 : TypesToCheck(T), FoundHandler(nullptr), TestAgainstType(QT) {}
4463
4464 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
4465 QualType getFoundHandlerType() const { return FoundHandlerType; }
4466
4467 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
4468 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
4469 QualType Check = S->getType().getCanonicalType();
4470 const auto &M = TypesToCheck;
4471 auto I = M.find(Val: Check);
4472 if (I != M.end()) {
4473 // We're pretty sure we found what we need to find. However, we still
4474 // need to make sure that we properly compare for pointers and
4475 // references, to handle cases like:
4476 //
4477 // } catch (Base *b) {
4478 // } catch (Derived &d) {
4479 // }
4480 //
4481 // where there is a qualification mismatch that disqualifies this
4482 // handler as a potential problem.
4483 if (I->second->getCaughtType()->isPointerType() ==
4484 TestAgainstType->isPointerType()) {
4485 FoundHandler = I->second;
4486 FoundHandlerType = Check;
4487 return true;
4488 }
4489 }
4490 }
4491 return false;
4492 }
4493};
4494}
4495
4496/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
4497/// handlers and creates a try statement from them.
4498StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4499 ArrayRef<Stmt *> Handlers) {
4500 const llvm::Triple &T = Context.getTargetInfo().getTriple();
4501 const bool IsOpenMPGPUTarget =
4502 getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN());
4503 // Don't report an error if 'try' is used in system headers or in an OpenMP
4504 // target region compiled for a GPU architecture.
4505 if (!IsOpenMPGPUTarget && !getLangOpts().CXXExceptions &&
4506 !getSourceManager().isInSystemHeader(Loc: TryLoc) && !getLangOpts().CUDA) {
4507 // Delay error emission for the OpenMP device code.
4508 targetDiag(TryLoc, diag::err_exceptions_disabled) << "try";
4509 }
4510
4511 // In OpenMP target regions, we assume that catch is never reached on GPU
4512 // targets.
4513 if (IsOpenMPGPUTarget)
4514 targetDiag(TryLoc, diag::warn_try_not_valid_on_target) << T.str();
4515
4516 // Exceptions aren't allowed in CUDA device code.
4517 if (getLangOpts().CUDA)
4518 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
4519 << "try" << CurrentCUDATarget();
4520
4521 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4522 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
4523
4524 sema::FunctionScopeInfo *FSI = getCurFunction();
4525
4526 // C++ try is incompatible with SEH __try.
4527 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
4528 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try) << 0;
4529 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
4530 }
4531
4532 const unsigned NumHandlers = Handlers.size();
4533 assert(!Handlers.empty() &&
4534 "The parser shouldn't call this if there are no handlers.");
4535
4536 llvm::DenseMap<QualType, CXXCatchStmt *> HandledBaseTypes;
4537 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
4538 for (unsigned i = 0; i < NumHandlers; ++i) {
4539 CXXCatchStmt *H = cast<CXXCatchStmt>(Val: Handlers[i]);
4540
4541 // Diagnose when the handler is a catch-all handler, but it isn't the last
4542 // handler for the try block. [except.handle]p5. Also, skip exception
4543 // declarations that are invalid, since we can't usefully report on them.
4544 if (!H->getExceptionDecl()) {
4545 if (i < NumHandlers - 1)
4546 return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
4547 continue;
4548 } else if (H->getExceptionDecl()->isInvalidDecl())
4549 continue;
4550
4551 // Walk the type hierarchy to diagnose when this type has already been
4552 // handled (duplication), or cannot be handled (derivation inversion). We
4553 // ignore top-level cv-qualifiers, per [except.handle]p3
4554 CatchHandlerType HandlerCHT = H->getCaughtType().getCanonicalType();
4555
4556 // We can ignore whether the type is a reference or a pointer; we need the
4557 // underlying declaration type in order to get at the underlying record
4558 // decl, if there is one.
4559 QualType Underlying = HandlerCHT.underlying();
4560 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
4561 if (!RD->hasDefinition())
4562 continue;
4563 // Check that none of the public, unambiguous base classes are in the
4564 // map ([except.handle]p1). Give the base classes the same pointer
4565 // qualification as the original type we are basing off of. This allows
4566 // comparison against the handler type using the same top-level pointer
4567 // as the original type.
4568 CXXBasePaths Paths;
4569 Paths.setOrigin(RD);
4570 CatchTypePublicBases CTPB(HandledBaseTypes,
4571 H->getCaughtType().getCanonicalType());
4572 if (RD->lookupInBases(BaseMatches: CTPB, Paths)) {
4573 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
4574 if (!Paths.isAmbiguous(
4575 BaseType: CanQualType::CreateUnsafe(Other: CTPB.getFoundHandlerType()))) {
4576 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4577 diag::warn_exception_caught_by_earlier_handler)
4578 << H->getCaughtType();
4579 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4580 diag::note_previous_exception_handler)
4581 << Problem->getCaughtType();
4582 }
4583 }
4584 // Strip the qualifiers here because we're going to be comparing this
4585 // type to the base type specifiers of a class, which are ignored in a
4586 // base specifier per [class.derived.general]p2.
4587 HandledBaseTypes[Underlying.getUnqualifiedType()] = H;
4588 }
4589
4590 // Add the type the list of ones we have handled; diagnose if we've already
4591 // handled it.
4592 auto R = HandledTypes.insert(
4593 std::make_pair(x: H->getCaughtType().getCanonicalType(), y&: H));
4594 if (!R.second) {
4595 const CXXCatchStmt *Problem = R.first->second;
4596 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4597 diag::warn_exception_caught_by_earlier_handler)
4598 << H->getCaughtType();
4599 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4600 diag::note_previous_exception_handler)
4601 << Problem->getCaughtType();
4602 }
4603 }
4604
4605 FSI->setHasCXXTry(TryLoc);
4606
4607 return CXXTryStmt::Create(C: Context, tryLoc: TryLoc, tryBlock: cast<CompoundStmt>(Val: TryBlock),
4608 handlers: Handlers);
4609}
4610
4611StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
4612 Stmt *TryBlock, Stmt *Handler) {
4613 assert(TryBlock && Handler);
4614
4615 sema::FunctionScopeInfo *FSI = getCurFunction();
4616
4617 // SEH __try is incompatible with C++ try. Borland appears to support this,
4618 // however.
4619 if (!getLangOpts().Borland) {
4620 if (FSI->FirstCXXOrObjCTryLoc.isValid()) {
4621 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try) << FSI->FirstTryType;
4622 Diag(FSI->FirstCXXOrObjCTryLoc, diag::note_conflicting_try_here)
4623 << (FSI->FirstTryType == sema::FunctionScopeInfo::TryLocIsCXX
4624 ? "'try'"
4625 : "'@try'");
4626 }
4627 }
4628
4629 FSI->setHasSEHTry(TryLoc);
4630
4631 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4632 // track if they use SEH.
4633 DeclContext *DC = CurContext;
4634 while (DC && !DC->isFunctionOrMethod())
4635 DC = DC->getParent();
4636 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: DC);
4637 if (FD)
4638 FD->setUsesSEHTry(true);
4639 else
4640 Diag(TryLoc, diag::err_seh_try_outside_functions);
4641
4642 // Reject __try on unsupported targets.
4643 if (!Context.getTargetInfo().isSEHTrySupported())
4644 Diag(TryLoc, diag::err_seh_try_unsupported);
4645
4646 return SEHTryStmt::Create(C: Context, isCXXTry: IsCXXTry, TryLoc, TryBlock, Handler);
4647}
4648
4649StmtResult Sema::ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
4650 Stmt *Block) {
4651 assert(FilterExpr && Block);
4652 QualType FTy = FilterExpr->getType();
4653 if (!FTy->isIntegerType() && !FTy->isDependentType()) {
4654 return StmtError(
4655 Diag(FilterExpr->getExprLoc(), diag::err_filter_expression_integral)
4656 << FTy);
4657 }
4658 return SEHExceptStmt::Create(C: Context, ExceptLoc: Loc, FilterExpr, Block);
4659}
4660
4661void Sema::ActOnStartSEHFinallyBlock() {
4662 CurrentSEHFinally.push_back(Elt: CurScope);
4663}
4664
4665void Sema::ActOnAbortSEHFinallyBlock() {
4666 CurrentSEHFinally.pop_back();
4667}
4668
4669StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
4670 assert(Block);
4671 CurrentSEHFinally.pop_back();
4672 return SEHFinallyStmt::Create(C: Context, FinallyLoc: Loc, Block);
4673}
4674
4675StmtResult
4676Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
4677 Scope *SEHTryParent = CurScope;
4678 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4679 SEHTryParent = SEHTryParent->getParent();
4680 if (!SEHTryParent)
4681 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
4682 CheckJumpOutOfSEHFinally(S&: *this, Loc, DestScope: *SEHTryParent);
4683
4684 return new (Context) SEHLeaveStmt(Loc);
4685}
4686
4687StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4688 bool IsIfExists,
4689 NestedNameSpecifierLoc QualifierLoc,
4690 DeclarationNameInfo NameInfo,
4691 Stmt *Nested)
4692{
4693 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
4694 QualifierLoc, NameInfo,
4695 cast<CompoundStmt>(Val: Nested));
4696}
4697
4698
4699StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4700 bool IsIfExists,
4701 CXXScopeSpec &SS,
4702 UnqualifiedId &Name,
4703 Stmt *Nested) {
4704 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
4705 QualifierLoc: SS.getWithLocInContext(Context),
4706 NameInfo: GetNameFromUnqualifiedId(Name),
4707 Nested);
4708}
4709
4710RecordDecl*
4711Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4712 unsigned NumParams) {
4713 DeclContext *DC = CurContext;
4714 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4715 DC = DC->getParent();
4716
4717 RecordDecl *RD = nullptr;
4718 if (getLangOpts().CPlusPlus)
4719 RD = CXXRecordDecl::Create(C: Context, TK: TagTypeKind::Struct, DC, StartLoc: Loc, IdLoc: Loc,
4720 /*Id=*/nullptr);
4721 else
4722 RD = RecordDecl::Create(C: Context, TK: TagTypeKind::Struct, DC, StartLoc: Loc, IdLoc: Loc,
4723 /*Id=*/nullptr);
4724
4725 RD->setCapturedRecord();
4726 DC->addDecl(RD);
4727 RD->setImplicit();
4728 RD->startDefinition();
4729
4730 assert(NumParams > 0 && "CapturedStmt requires context parameter");
4731 CD = CapturedDecl::Create(C&: Context, DC: CurContext, NumParams);
4732 DC->addDecl(CD);
4733 return RD;
4734}
4735
4736static bool
4737buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI,
4738 SmallVectorImpl<CapturedStmt::Capture> &Captures,
4739 SmallVectorImpl<Expr *> &CaptureInits) {
4740 for (const sema::Capture &Cap : RSI->Captures) {
4741 if (Cap.isInvalid())
4742 continue;
4743
4744 // Form the initializer for the capture.
4745 ExprResult Init = S.BuildCaptureInit(Capture: Cap, ImplicitCaptureLoc: Cap.getLocation(),
4746 IsOpenMPMapping: RSI->CapRegionKind == CR_OpenMP);
4747
4748 // FIXME: Bail out now if the capture is not used and the initializer has
4749 // no side-effects.
4750
4751 // Create a field for this capture.
4752 FieldDecl *Field = S.BuildCaptureField(RD: RSI->TheRecordDecl, Capture: Cap);
4753
4754 // Add the capture to our list of captures.
4755 if (Cap.isThisCapture()) {
4756 Captures.push_back(Elt: CapturedStmt::Capture(Cap.getLocation(),
4757 CapturedStmt::VCK_This));
4758 } else if (Cap.isVLATypeCapture()) {
4759 Captures.push_back(
4760 Elt: CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
4761 } else {
4762 assert(Cap.isVariableCapture() && "unknown kind of capture");
4763
4764 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
4765 S.setOpenMPCaptureKind(FD: Field, D: Cap.getVariable(), Level: RSI->OpenMPLevel);
4766
4767 Captures.push_back(Elt: CapturedStmt::Capture(
4768 Cap.getLocation(),
4769 Cap.isReferenceCapture() ? CapturedStmt::VCK_ByRef
4770 : CapturedStmt::VCK_ByCopy,
4771 cast<VarDecl>(Val: Cap.getVariable())));
4772 }
4773 CaptureInits.push_back(Elt: Init.get());
4774 }
4775 return false;
4776}
4777
4778void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4779 CapturedRegionKind Kind,
4780 unsigned NumParams) {
4781 CapturedDecl *CD = nullptr;
4782 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
4783
4784 // Build the context parameter
4785 DeclContext *DC = CapturedDecl::castToDeclContext(D: CD);
4786 IdentifierInfo *ParamName = &Context.Idents.get(Name: "__context");
4787 QualType ParamType = Context.getPointerType(T: Context.getTagDeclType(RD));
4788 auto *Param =
4789 ImplicitParamDecl::Create(C&: Context, DC, IdLoc: Loc, Id: ParamName, T: ParamType,
4790 ParamKind: ImplicitParamKind::CapturedContext);
4791 DC->addDecl(D: Param);
4792
4793 CD->setContextParam(i: 0, P: Param);
4794
4795 // Enter the capturing scope for this captured region.
4796 PushCapturedRegionScope(RegionScope: CurScope, CD, RD, K: Kind);
4797
4798 if (CurScope)
4799 PushDeclContext(CurScope, CD);
4800 else
4801 CurContext = CD;
4802
4803 PushExpressionEvaluationContext(
4804 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
4805 ExprEvalContexts.back().InImmediateEscalatingFunctionContext = false;
4806}
4807
4808void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4809 CapturedRegionKind Kind,
4810 ArrayRef<CapturedParamNameType> Params,
4811 unsigned OpenMPCaptureLevel) {
4812 CapturedDecl *CD = nullptr;
4813 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams: Params.size());
4814
4815 // Build the context parameter
4816 DeclContext *DC = CapturedDecl::castToDeclContext(D: CD);
4817 bool ContextIsFound = false;
4818 unsigned ParamNum = 0;
4819 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4820 E = Params.end();
4821 I != E; ++I, ++ParamNum) {
4822 if (I->second.isNull()) {
4823 assert(!ContextIsFound &&
4824 "null type has been found already for '__context' parameter");
4825 IdentifierInfo *ParamName = &Context.Idents.get(Name: "__context");
4826 QualType ParamType = Context.getPointerType(T: Context.getTagDeclType(RD))
4827 .withConst()
4828 .withRestrict();
4829 auto *Param =
4830 ImplicitParamDecl::Create(C&: Context, DC, IdLoc: Loc, Id: ParamName, T: ParamType,
4831 ParamKind: ImplicitParamKind::CapturedContext);
4832 DC->addDecl(D: Param);
4833 CD->setContextParam(i: ParamNum, P: Param);
4834 ContextIsFound = true;
4835 } else {
4836 IdentifierInfo *ParamName = &Context.Idents.get(Name: I->first);
4837 auto *Param =
4838 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4839 ImplicitParamKind::CapturedContext);
4840 DC->addDecl(D: Param);
4841 CD->setParam(i: ParamNum, P: Param);
4842 }
4843 }
4844 assert(ContextIsFound && "no null type for '__context' parameter");
4845 if (!ContextIsFound) {
4846 // Add __context implicitly if it is not specified.
4847 IdentifierInfo *ParamName = &Context.Idents.get(Name: "__context");
4848 QualType ParamType = Context.getPointerType(T: Context.getTagDeclType(RD));
4849 auto *Param =
4850 ImplicitParamDecl::Create(C&: Context, DC, IdLoc: Loc, Id: ParamName, T: ParamType,
4851 ParamKind: ImplicitParamKind::CapturedContext);
4852 DC->addDecl(D: Param);
4853 CD->setContextParam(i: ParamNum, P: Param);
4854 }
4855 // Enter the capturing scope for this captured region.
4856 PushCapturedRegionScope(RegionScope: CurScope, CD, RD, K: Kind, OpenMPCaptureLevel);
4857
4858 if (CurScope)
4859 PushDeclContext(CurScope, CD);
4860 else
4861 CurContext = CD;
4862
4863 PushExpressionEvaluationContext(
4864 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
4865}
4866
4867void Sema::ActOnCapturedRegionError() {
4868 DiscardCleanupsInEvaluationContext();
4869 PopExpressionEvaluationContext();
4870 PopDeclContext();
4871 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4872 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(Val: ScopeRAII.get());
4873
4874 RecordDecl *Record = RSI->TheRecordDecl;
4875 Record->setInvalidDecl();
4876
4877 SmallVector<Decl*, 4> Fields(Record->fields());
4878 ActOnFields(/*Scope=*/S: nullptr, RecLoc: Record->getLocation(), TagDecl: Record, Fields,
4879 LBrac: SourceLocation(), RBrac: SourceLocation(), AttrList: ParsedAttributesView());
4880}
4881
4882StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4883 // Leave the captured scope before we start creating captures in the
4884 // enclosing scope.
4885 DiscardCleanupsInEvaluationContext();
4886 PopExpressionEvaluationContext();
4887 PopDeclContext();
4888 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4889 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(Val: ScopeRAII.get());
4890
4891 SmallVector<CapturedStmt::Capture, 4> Captures;
4892 SmallVector<Expr *, 4> CaptureInits;
4893 if (buildCapturedStmtCaptureList(S&: *this, RSI, Captures, CaptureInits))
4894 return StmtError();
4895
4896 CapturedDecl *CD = RSI->TheCapturedDecl;
4897 RecordDecl *RD = RSI->TheRecordDecl;
4898
4899 CapturedStmt *Res = CapturedStmt::Create(
4900 Context: getASTContext(), S, Kind: static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4901 Captures, CaptureInits, CD, RD);
4902
4903 CD->setBody(Res->getCapturedStmt());
4904 RD->completeDefinition();
4905
4906 return Res;
4907}
4908

source code of clang/lib/Sema/SemaStmt.cpp