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