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