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