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