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