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