32#include "llvm/ADT/APInt.h"
33#include "llvm/ADT/FoldingSet.h"
34#include "llvm/ADT/PointerIntPair.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/StringExtras.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/raw_ostream.h"
74 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
92 auto IsCharOrUnsignedChar = [](
const QualType &
T) {
93 const BuiltinType *BT = dyn_cast<BuiltinType>(
T.getTypePtr());
98 case StringLiteralKind::UTF8:
108 case StringLiteralKind::Ordinary:
109 case StringLiteralKind::Binary:
113 return (SL->
getKind() == StringLiteralKind::UTF8 &&
127 case StringLiteralKind::UTF16:
135 case StringLiteralKind::UTF32:
143 case StringLiteralKind::Wide:
151 case StringLiteralKind::Unevaluated:
152 assert(
false &&
"Unevaluated string literal in initialization");
156 llvm_unreachable(
"missed a StringLiteral kind?");
177 if (isa<StringLiteral>(
E) || isa<ObjCEncodeExpr>(
E))
188 if (isa<CompoundLiteralExpr>(
E))
203 if (
const auto *VD = dyn_cast_if_present<VarDecl>(
D); VD && VD->isConstexpr())
214 bool CheckC23ConstexprInit =
false) {
216 auto *ConstantArrayTy =
218 uint64_t StrLength = ConstantArrayTy->getZExtSize();
220 if (CheckC23ConstexprInit)
227 llvm::APInt ConstVal(32, StrLength);
252 if (StrLength > ArrayLen)
254 diag::err_initializer_string_for_char_array_too_long)
258 if (StrLength - 1 > ArrayLen)
260 diag::ext_initializer_string_for_char_array_too_long)
262 else if (StrLength - 1 == ArrayLen) {
265 const auto *SL = dyn_cast<StringLiteral>(Str->
IgnoreParens());
266 bool IsSLSafe = SL && SL->getLength() > 0 &&
267 SL->getCodeUnit(SL->getLength() - 1) == 0;
274 auto FindCorrectEntity =
286 if (
const ValueDecl *
D = FindCorrectEntity(&Entity);
291 warn_initializer_string_for_char_array_too_long_no_nonstring)
296 diag::warn_initializer_string_for_char_array_too_long_for_cpp)
310 if (Field->hasAttr<ExplicitInitAttr>())
311 S.
Diag(Field->getLocation(), diag::note_entity_declared_at) << Field;
352class InitListChecker {
354 bool hadError =
false;
356 bool TreatUnavailableAsInvalid;
357 bool InOverloadResolution;
362 unsigned CurEmbedIndex = 0;
373 unsigned &StructuredIndex);
377 bool TopLevelObject =
false);
380 bool SubobjectIsDesignatorContext,
383 unsigned &StructuredIndex,
384 bool TopLevelObject =
false);
389 unsigned &StructuredIndex,
390 bool DirectlyDesignated =
false);
395 unsigned &StructuredIndex);
400 unsigned &StructuredIndex);
405 unsigned &StructuredIndex);
409 unsigned &StructuredIndex);
414 bool SubobjectIsDesignatorContext,
unsigned &Index,
416 unsigned &StructuredIndex,
417 bool TopLevelObject =
false);
420 llvm::APSInt elementIndex,
421 bool SubobjectIsDesignatorContext,
unsigned &Index,
423 unsigned &StructuredIndex);
429 llvm::APSInt *NextElementIndex,
432 unsigned &StructuredIndex,
433 bool FinishSubobjectInit,
434 bool TopLevelObject);
438 unsigned StructuredIndex,
440 bool IsFullyOverwritten =
false);
441 void UpdateStructuredListElement(
InitListExpr *StructuredList,
442 unsigned &StructuredIndex,
446 unsigned ExpectedNumInits);
447 int numArrayElements(
QualType DeclType);
448 int numStructUnionElements(
QualType DeclType);
455 bool UnionOverride =
false,
456 bool FullyOverwritten =
true) {
461 ? (UnionOverride ? diag::ext_initializer_union_overrides
462 : diag::ext_initializer_overrides)
463 : diag::warn_initializer_overrides;
465 if (InOverloadResolution && SemaRef.
getLangOpts().CPlusPlus) {
486 DiagID = diag::err_initializer_overrides_destructed;
506 << NewInitRange << FullyOverwritten << OldInit->
getType();
535 bool FillWithNoInit);
536 void FillInEmptyInitForField(
unsigned Init,
FieldDecl *Field,
539 bool FillWithNoInit =
false);
543 bool FillWithNoInit =
false);
546 bool TopLevelObject);
551 Expr *Result =
nullptr;
564 assert(AType &&
"expected array type when initializing array");
566 if (
const auto *CAType = dyn_cast<ConstantArrayType>(AType))
567 ElsCount = std::min(CAType->getSize().getZExtValue() - ArrIndex,
568 ElsCount - CurEmbedIndex);
578 CurEmbedIndex, ElsCount);
579 CurEmbedIndex += ElsCount;
590 bool VerifyOnly,
bool TreatUnavailableAsInvalid,
591 bool InOverloadResolution =
false,
596 : InitListChecker(S, Entity, IL,
T,
true,
599 &AggrDeductionCandidateParamTypes) {}
601 bool HadError() {
return hadError; }
605 InitListExpr *getFullyStructuredList()
const {
return FullyStructuredList; }
622 bool EmptyInitList = SemaRef.
getLangOpts().CPlusPlus11 &&
635 InitExpr = VerifyOnly ? &DummyInitList
652 if (!InitSeq && EmptyInitList &&
653 InitSeq.getFailureKind() ==
658 InitSeq.getFailedCandidateSet()
659 .BestViableFunction(SemaRef,
Kind.getLocation(), Best);
661 assert(O ==
OR_Success &&
"Inconsistent overload resolution");
668 bool IsInStd =
false;
670 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
675 if (IsInStd && llvm::StringSwitch<bool>(R->
getName())
676 .Cases(
"basic_string",
"deque",
"forward_list",
true)
677 .Cases(
"list",
"map",
"multimap",
"multiset",
true)
678 .Cases(
"priority_queue",
"queue",
"set",
"stack",
true)
679 .Cases(
"unordered_map",
"unordered_set",
"vector",
true)
681 InitSeq.InitializeFrom(
685 TreatUnavailableAsInvalid);
690 diag::warn_invalid_initializer_from_system_header);
693 diag::note_used_in_initialization_here);
695 SemaRef.
Diag(
Loc, diag::note_used_in_initialization_here);
702 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
705 diag::note_in_omitted_aggregate_initializer)
708 bool IsTrailingArrayNewMember =
711 SemaRef.
Diag(
Loc, diag::note_in_omitted_aggregate_initializer)
712 << (IsTrailingArrayNewMember ? 2 : 0)
721 : InitSeq.Perform(SemaRef, Entity,
Kind, SubInit);
729 if (FullyStructuredList)
731 PerformEmptyInit(
Loc, Entity);
734void InitListChecker::FillInEmptyInitForBase(
737 bool &RequiresSecondPass,
bool FillWithNoInit) {
744 : PerformEmptyInit(ILE->
getEndLoc(), BaseEntity);
751 assert(Init < ILE->getNumInits() &&
"should have been expanded");
756 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
757 ILE,
Init, FillWithNoInit);
759 dyn_cast<DesignatedInitUpdateExpr>(ILE->
getInit(
Init))) {
760 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
761 RequiresSecondPass, ILE,
Init,
766void InitListChecker::FillInEmptyInitForField(
unsigned Init,
FieldDecl *Field,
769 bool &RequiresSecondPass,
770 bool FillWithNoInit) {
778 if (!RType->getOriginalDecl()->isUnion())
779 assert((
Init < NumInits || VerifyOnly) &&
780 "This ILE should have been expanded");
782 if (FillWithNoInit) {
783 assert(!VerifyOnly &&
"should not fill with no-init in verify-only mode");
792 if (!VerifyOnly &&
Field->hasAttr<ExplicitInitAttr>() &&
794 SemaRef.
Diag(ILE->
getExprLoc(), diag::warn_field_requires_explicit_init)
796 SemaRef.
Diag(
Field->getLocation(), diag::note_entity_declared_at)
804 if (
Field->hasInClassInitializer()) {
834 RequiresSecondPass =
true;
839 if (
Field->getType()->isReferenceType()) {
845 SemaRef.
Diag(
Loc, diag::err_init_reference_member_uninitialized)
849 SemaRef.
Diag(
Field->getLocation(), diag::note_uninit_reference_member);
861 if (hadError || VerifyOnly) {
863 }
else if (
Init < NumInits) {
865 }
else if (!isa<ImplicitValueInitExpr>(MemberInit.
get())) {
871 RequiresSecondPass =
true;
875 FillInEmptyInitializations(MemberEntity, InnerILE,
876 RequiresSecondPass, ILE,
Init, FillWithNoInit);
878 dyn_cast<DesignatedInitUpdateExpr>(ILE->
getInit(
Init))) {
879 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
880 RequiresSecondPass, ILE,
Init,
891 bool &RequiresSecondPass,
894 bool FillWithNoInit) {
896 "Should not have void type");
900 if (FillWithNoInit && VerifyOnly)
910 struct UpdateOuterILEWithUpdatedInit {
913 ~UpdateOuterILEWithUpdatedInit() {
917 } UpdateOuterRAII = {OuterILE, OuterIndex};
927 RequiresSecondPass, FillWithNoInit);
929 assert((!RDecl->isUnion() || !isa<CXXRecordDecl>(RDecl) ||
930 !cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) &&
931 "We should have computed initialized fields already");
935 unsigned NumElems = numStructUnionElements(ILE->
getType());
936 if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
943 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
944 for (
auto &
Base : CXXRD->bases()) {
948 FillInEmptyInitForBase(
Init,
Base, Entity, ILE, RequiresSecondPass,
954 for (
auto *Field : RDecl->fields()) {
955 if (
Field->isUnnamedBitField())
961 FillInEmptyInitForField(
Init, Field, Entity, ILE, RequiresSecondPass,
969 if (RDecl->isUnion())
983 ElementType = AType->getElementType();
984 if (
const auto *CAType = dyn_cast<ConstantArrayType>(AType))
985 NumElements = CAType->getZExtSize();
993 ElementType = VType->getElementType();
994 NumElements = VType->getNumElements();
1000 bool SkipEmptyInitChecks =
false;
1013 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
1018 if (SkipEmptyInitChecks)
1021 Expr *Filler =
nullptr;
1027 PerformEmptyInit(ILE->
getEndLoc(), ElementEntity);
1038 }
else if (VerifyOnly) {
1039 SkipEmptyInitChecks =
true;
1040 }
else if (
Init < NumInits) {
1055 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
1061 RequiresSecondPass =
true;
1065 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
1066 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
1067 ILE,
Init, FillWithNoInit);
1069 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
1070 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
1071 RequiresSecondPass, ILE,
Init,
1079 if (isa_and_nonnull<DesignatedInitExpr>(
Init))
1084InitListChecker::InitListChecker(
1086 bool VerifyOnly,
bool TreatUnavailableAsInvalid,
bool InOverloadResolution,
1088 : SemaRef(S), VerifyOnly(VerifyOnly),
1089 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
1090 InOverloadResolution(InOverloadResolution),
1091 AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {
1093 FullyStructuredList =
1102 CheckExplicitInitList(Entity, IL,
T, FullyStructuredList,
1105 if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {
1106 bool RequiresSecondPass =
false;
1107 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
1109 if (RequiresSecondPass && !hadError)
1110 FillInEmptyInitializations(Entity, FullyStructuredList,
1111 RequiresSecondPass,
nullptr, 0);
1113 if (hadError && FullyStructuredList)
1117int InitListChecker::numArrayElements(
QualType DeclType) {
1119 int maxElements = 0x7FFFFFFF;
1122 maxElements =
static_cast<int>(CAT->getZExtSize());
1127int InitListChecker::numStructUnionElements(
QualType DeclType) {
1129 int InitializableMembers = 0;
1130 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
1131 InitializableMembers += CXXRD->getNumBases();
1132 for (
const auto *Field : structDecl->fields())
1133 if (!
Field->isUnnamedBitField())
1134 ++InitializableMembers;
1136 if (structDecl->isUnion())
1137 return std::min(InitializableMembers, 1);
1138 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1165 if (
CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1166 if (CXXRD->getNumBases()) {
1171 assert(FieldIt != ParentRD->field_end() &&
1172 "no fields but have initializer for member?");
1173 return ++FieldIt == ParentRD->field_end();
1189 unsigned &StructuredIndex) {
1190 int maxElements = 0;
1193 maxElements = numArrayElements(
T);
1195 maxElements = numStructUnionElements(
T);
1199 llvm_unreachable(
"CheckImplicitInitList(): Illegal type");
1201 if (maxElements == 0) {
1204 diag::err_implicit_empty_initializer);
1211 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1212 ParentIList, Index,
T, StructuredList, StructuredIndex,
1215 unsigned StructuredSubobjectInitIndex = 0;
1218 unsigned StartIndex = Index;
1219 CheckListElementTypes(Entity, ParentIList,
T,
1221 StructuredSubobjectInitList,
1222 StructuredSubobjectInitIndex);
1224 if (StructuredSubobjectInitList) {
1225 StructuredSubobjectInitList->
setType(
T);
1227 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1230 if (EndIndex < ParentIList->getNumInits() &&
1231 ParentIList->
getInit(EndIndex)) {
1242 diag::warn_missing_braces)
1248 StructuredSubobjectInitList->
getEndLoc()),
1254 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1256 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1272 unsigned DiagID = 0;
1284 DiagID = diag::warn_braces_around_init;
1291 DiagID = diag::warn_braces_around_init;
1317 llvm_unreachable(
"unexpected braced scalar init");
1336 bool TopLevelObject) {
1337 unsigned Index = 0, StructuredIndex = 0;
1338 CheckListElementTypes(Entity, IList,
T,
true,
1339 Index, StructuredList, StructuredIndex, TopLevelObject);
1340 if (StructuredList) {
1346 StructuredList->
setType(ExprTy);
1354 bool ExtraInitsIsError = SemaRef.
getLangOpts().CPlusPlus ||
1356 hadError = ExtraInitsIsError;
1359 }
else if (StructuredIndex == 1 &&
1364 ? diag::err_excess_initializers_in_char_array_initializer
1365 : diag::ext_excess_initializers_in_char_array_initializer;
1369 unsigned DK = ExtraInitsIsError
1370 ? diag::err_excess_initializers_for_sizeless_type
1371 : diag::ext_excess_initializers_for_sizeless_type;
1381 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1382 : diag::ext_excess_initializers;
1390 !isa<InitListExpr>(IList->
getInit(0)))
1396 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1399 bool HasEquivCtor =
false;
1405 if (!HasEquivCtor) {
1407 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1417 bool SubobjectIsDesignatorContext,
1420 unsigned &StructuredIndex,
1421 bool TopLevelObject) {
1425 CheckComplexType(Entity, IList, DeclType, Index,
1426 StructuredList, StructuredIndex);
1428 CheckScalarType(Entity, IList, DeclType, Index,
1429 StructuredList, StructuredIndex);
1431 CheckVectorType(Entity, IList, DeclType, Index,
1432 StructuredList, StructuredIndex);
1439 "non-aggregate records should be handed in CheckSubElementType");
1440 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1441 Bases = CXXRD->bases();
1443 Bases = cast<CXXRecordDecl>(RD)->bases();
1445 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1446 SubobjectIsDesignatorContext, Index, StructuredList,
1447 StructuredIndex, TopLevelObject);
1452 CheckArrayType(Entity, IList, DeclType,
Zero,
1453 SubobjectIsDesignatorContext, Index,
1454 StructuredList, StructuredIndex);
1459 SemaRef.
Diag(IList->
getBeginLoc(), diag::err_illegal_initializer_type)
1463 CheckReferenceType(Entity, IList, DeclType, Index,
1464 StructuredList, StructuredIndex);
1467 SemaRef.
Diag(IList->
getBeginLoc(), diag::err_init_objc_class) << DeclType;
1472 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1479 assert(AggrDeductionCandidateParamTypes);
1480 AggrDeductionCandidateParamTypes->push_back(DeclType);
1483 SemaRef.
Diag(IList->
getBeginLoc(), diag::err_illegal_initializer_type)
1494 unsigned &StructuredIndex,
1495 bool DirectlyDesignated) {
1499 return CheckReferenceType(Entity, IList, ElemType, Index,
1500 StructuredList, StructuredIndex);
1503 if (SubInitList->getNumInits() == 1 &&
1508 expr = SubInitList->getInit(0);
1511 }
else if (isa<ImplicitValueInitExpr>(
expr)) {
1515 "found implicit initialization for the wrong type");
1516 UpdateStructuredListElement(StructuredList, StructuredIndex,
expr);
1538 if (TmpEntity.getType()->isDependentType()) {
1543 assert(AggrDeductionCandidateParamTypes);
1557 if (isa<InitListExpr, DesignatedInitExpr>(
expr) ||
1558 !isa_and_present<ConstantArrayType>(
1561 AggrDeductionCandidateParamTypes->push_back(ElemType);
1573 if (
Seq || isa<InitListExpr>(
expr)) {
1574 if (
auto *Embed = dyn_cast<EmbedExpr>(
expr)) {
1575 expr = HandleEmbed(Embed, Entity);
1579 if (Result.isInvalid())
1582 UpdateStructuredListElement(StructuredList, StructuredIndex,
1583 Result.getAs<
Expr>());
1586 }
else if (StructuredList) {
1587 UpdateStructuredListElement(StructuredList, StructuredIndex,
1592 if (AggrDeductionCandidateParamTypes)
1593 AggrDeductionCandidateParamTypes->push_back(ElemType);
1601 return CheckScalarType(Entity, IList, ElemType, Index,
1602 StructuredList, StructuredIndex);
1616 UpdateStructuredListElement(StructuredList, StructuredIndex,
expr);
1639 AssignConvertType::Incompatible) {
1647 UpdateStructuredListElement(StructuredList, StructuredIndex,
1665 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1670 if (DirectlyDesignated && SemaRef.
getLangOpts().CPlusPlus && !hadError) {
1671 if (InOverloadResolution)
1675 diag::ext_designated_init_brace_elision)
1676 <<
expr->getSourceRange()
1691 assert(
Copy.isInvalid() &&
1692 "expected non-aggregate initialization to fail");
1704 unsigned &StructuredIndex) {
1705 assert(Index == 0 &&
"Index in explicit init list must be zero");
1715 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1720 if (!SemaRef.
getLangOpts().CPlusPlus && !VerifyOnly)
1729 for (
unsigned i = 0; i < 2; ++i) {
1731 CheckSubElementType(ElementEntity, IList, elementType, Index,
1732 StructuredList, StructuredIndex);
1740 unsigned &StructuredIndex) {
1747 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1748 : diag::err_empty_sizeless_initializer)
1753 ? diag::warn_cxx98_compat_empty_scalar_initializer
1754 : diag::err_empty_scalar_initializer)
1770 SemaRef.
Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1773 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1776 }
else if (isa<DesignatedInitExpr>(
expr)) {
1779 diag::err_designator_for_scalar_or_sizeless_init)
1781 <<
expr->getSourceRange();
1786 }
else if (
auto *Embed = dyn_cast<EmbedExpr>(
expr)) {
1787 expr = HandleEmbed(Embed, Entity);
1793 Result = getDummyInit();
1802 Expr *ResultExpr =
nullptr;
1804 if (Result.isInvalid())
1807 ResultExpr = Result.getAs<
Expr>();
1809 if (ResultExpr !=
expr && !VerifyOnly && !CurEmbed) {
1812 IList->
setInit(Index, ResultExpr);
1816 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1819 if (AggrDeductionCandidateParamTypes)
1820 AggrDeductionCandidateParamTypes->push_back(DeclType);
1827 unsigned &StructuredIndex) {
1835 diag::err_init_reference_member_uninitialized)
1857 Result = getDummyInit();
1866 if (Result.isInvalid())
1871 if (!VerifyOnly &&
expr)
1874 UpdateStructuredListElement(StructuredList, StructuredIndex,
expr);
1876 if (AggrDeductionCandidateParamTypes)
1877 AggrDeductionCandidateParamTypes->push_back(DeclType);
1884 unsigned &StructuredIndex) {
1887 unsigned numEltsInit = 0;
1892 CheckEmptyInitializable(
1902 if (!isa<InitListExpr>(
Init) &&
Init->getType()->isVectorType()) {
1906 Result = getDummyInit();
1915 Expr *ResultExpr =
nullptr;
1916 if (Result.isInvalid())
1919 ResultExpr = Result.getAs<
Expr>();
1921 if (ResultExpr !=
Init && !VerifyOnly) {
1924 IList->
setInit(Index, ResultExpr);
1927 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1929 if (AggrDeductionCandidateParamTypes)
1930 AggrDeductionCandidateParamTypes->push_back(elementType);
1937 for (
unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1940 CheckEmptyInitializable(ElementEntity, IList->
getEndLoc());
1945 CheckSubElementType(ElementEntity, IList, elementType, Index,
1946 StructuredList, StructuredIndex);
1954 if (isBigEndian && (
T->getVectorKind() == VectorKind::Neon ||
1955 T->getVectorKind() == VectorKind::NeonPoly)) {
1967 diag::warn_neon_vector_initializer_non_portable);
1969 const char *typeCode;
1981 llvm_unreachable(
"Invalid element type!");
1985 ? diag::note_neon_vector_initializer_non_portable_q
1986 : diag::note_neon_vector_initializer_non_portable)
1987 << typeCode << typeSize;
1997 for (
unsigned i = 0; i < maxElements; ++i) {
2006 CheckSubElementType(ElementEntity, IList, elementType, Index,
2007 StructuredList, StructuredIndex);
2019 CheckSubElementType(ElementEntity, IList, VecType, Index,
2020 StructuredList, StructuredIndex);
2021 numEltsInit += numIElts;
2026 if (numEltsInit != maxElements) {
2029 diag::err_vector_incorrect_num_elements)
2030 << (numEltsInit < maxElements) << maxElements << numEltsInit
2057 SemaRef.
PDiag(diag::err_access_dtor_temp)
2071 InitType =
Parent->getType();
2077 ExprList.size() == 1
2078 ? dyn_cast_if_present<EmbedExpr>(ExprList[0]->IgnoreParens())
2093 llvm::APSInt elementIndex,
2094 bool SubobjectIsDesignatorContext,
2097 unsigned &StructuredIndex) {
2115 if (Index < IList->getNumInits()) {
2128 if (StructuredList) {
2129 UpdateStructuredListElement(StructuredList, StructuredIndex,
2134 if (AggrDeductionCandidateParamTypes)
2135 AggrDeductionCandidateParamTypes->push_back(DeclType);
2156 SemaRef.
Diag(VAT->getSizeExpr()->getBeginLoc(),
2157 diag::err_variable_object_no_init)
2158 << VAT->getSizeExpr()->getSourceRange();
2167 llvm::APSInt maxElements(elementIndex.getBitWidth(),
2168 elementIndex.isUnsigned());
2169 bool maxElementsKnown =
false;
2171 maxElements = CAT->getSize();
2172 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
2173 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2174 maxElementsKnown =
true;
2178 while (Index < IList->getNumInits()) {
2184 if (!SubobjectIsDesignatorContext)
2189 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2190 DeclType,
nullptr, &elementIndex, Index,
2191 StructuredList, StructuredIndex,
true,
2197 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2198 maxElements = maxElements.extend(elementIndex.getBitWidth());
2199 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2200 elementIndex = elementIndex.extend(maxElements.getBitWidth());
2201 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2205 if (!maxElementsKnown && elementIndex > maxElements)
2206 maxElements = elementIndex;
2213 if (maxElementsKnown && elementIndex == maxElements)
2217 SemaRef.
Context, StructuredIndex, Entity);
2220 unsigned EmbedElementIndexBeforeInit = CurEmbedIndex;
2222 CheckSubElementType(ElementEntity, IList, elementType, Index,
2223 StructuredList, StructuredIndex);
2228 elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1;
2230 auto Embed = cast<EmbedExpr>(
Init);
2232 EmbedElementIndexBeforeInit - 1;
2238 if (!maxElementsKnown && elementIndex > maxElements)
2239 maxElements = elementIndex;
2244 llvm::APSInt
Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2248 SemaRef.
Diag(IList->
getBeginLoc(), diag::ext_typecheck_zero_array_size);
2252 elementType, maxElements,
nullptr, ArraySizeModifier::Normal, 0);
2259 if ((maxElementsKnown && elementIndex < maxElements) ||
2261 CheckEmptyInitializable(
2270 bool TopLevelObject) {
2272 unsigned FlexArrayDiag;
2273 if (isa<InitListExpr>(InitExpr) &&
2274 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2276 FlexArrayDiag = diag::ext_flexible_array_init;
2277 }
else if (!TopLevelObject) {
2279 FlexArrayDiag = diag::err_flexible_array_init;
2282 FlexArrayDiag = diag::err_flexible_array_init;
2283 }
else if (cast<VarDecl>(Entity.
getDecl())->hasLocalStorage()) {
2285 FlexArrayDiag = diag::err_flexible_array_init;
2288 FlexArrayDiag = diag::ext_flexible_array_init;
2294 SemaRef.
Diag(
Field->getLocation(), diag::note_flexible_array_member)
2298 return FlexArrayDiag != diag::ext_flexible_array_init;
2302 return StructuredList && StructuredList->
getNumInits() == 1U;
2305void InitListChecker::CheckStructUnionTypes(
2308 bool SubobjectIsDesignatorContext,
unsigned &Index,
2309 InitListExpr *StructuredList,
unsigned &StructuredIndex,
2310 bool TopLevelObject) {
2333 if (isa<CXXRecordDecl>(RD) &&
2334 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2335 if (!StructuredList)
2338 Field != FieldEnd; ++Field) {
2339 if (
Field->hasInClassInitializer() ||
2340 (
Field->isAnonymousStructOrUnion() &&
2342 ->castAsCXXRecordDecl()
2343 ->hasInClassInitializer())) {
2349 llvm_unreachable(
"Couldn't find in-class initializer");
2355 Field != FieldEnd; ++Field) {
2356 if (!
Field->isUnnamedBitField()) {
2357 CheckEmptyInitializable(
2368 bool InitializedSomething =
false;
2371 for (
auto I = Bases.begin(),
E = Bases.end(); I !=
E; ++I) {
2377 if (isa_and_nonnull<DesignatedInitExpr>(
Init))
2394 if (AggrDeductionCandidateParamTypes &&
Base.isPackExpansion()) {
2395 AggrDeductionCandidateParamTypes->push_back(
2400 if (Index < IList->getNumInits())
2412 CheckSubElementType(BaseEntity, IList,
Base.getType(), Index,
2413 StructuredList, StructuredIndex);
2414 InitializedSomething =
true;
2416 CheckEmptyInitializable(BaseEntity, InitLoc);
2431 size_t NumRecordDecls = llvm::count_if(RD->
decls(), [&](
const Decl *
D) {
2432 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2434 bool HasDesignatedInit =
false;
2438 while (Index < IList->getNumInits()) {
2446 if (!SubobjectIsDesignatorContext)
2449 HasDesignatedInit =
true;
2453 bool DesignatedInitFailed = CheckDesignatedInitializer(
2454 Entity, IList, DIE, 0, DeclType, &Field,
nullptr, Index,
2455 StructuredList, StructuredIndex,
true, TopLevelObject);
2456 if (DesignatedInitFailed)
2461 if (!VerifyOnly &&
D->isFieldDesignator()) {
2463 InitializedFields.insert(F);
2464 if (!DesignatedInitFailed) {
2473 InitializedSomething =
true;
2490 if (NumRecordDecls == 1)
2492 if (
const auto *IL = dyn_cast<IntegerLiteral>(I))
2493 return IL->getValue().isZero();
2501 SemaRef.
Diag(InitLoc, diag::err_non_designated_init_used);
2506 if (Field == FieldEnd) {
2512 if (InitializedSomething && RD->
isUnion())
2516 if (
Field->getType()->isIncompleteArrayType())
2519 if (
Field->isUnnamedBitField()) {
2528 InvalidUse = !SemaRef.
CanUseDecl(*Field, TreatUnavailableAsInvalid);
2549 CheckSubElementType(MemberEntity, IList,
Field->getType(), Index,
2550 StructuredList, StructuredIndex);
2551 InitializedSomething =
true;
2552 InitializedFields.insert(*Field);
2564 bool IsCDesignatedInitializer =
2565 HasDesignatedInit && !SemaRef.
getLangOpts().CPlusPlus;
2566 if (!VerifyOnly && InitializedSomething && !RD->
isUnion() &&
2568 !IsCDesignatedInitializer) {
2575 if (HasDesignatedInit && InitializedFields.count(*it))
2578 if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&
2579 !it->getType()->isIncompleteArrayType()) {
2580 auto Diag = HasDesignatedInit
2581 ? diag::warn_missing_designated_field_initializers
2582 : diag::warn_missing_field_initializers;
2591 if (!StructuredList && Field != FieldEnd && !RD->
isUnion() &&
2592 !
Field->getType()->isIncompleteArrayType()) {
2593 for (;
Field != FieldEnd && !hadError; ++
Field) {
2594 if (!
Field->isUnnamedBitField() && !
Field->hasInClassInitializer())
2595 CheckEmptyInitializable(
2616 if (Field == FieldEnd || !
Field->getType()->isIncompleteArrayType() ||
2620 if (CheckFlexibleArrayInit(Entity, IList->
getInit(Index), *Field,
2630 if (isa<InitListExpr>(IList->
getInit(Index)) ||
2631 AggrDeductionCandidateParamTypes)
2632 CheckSubElementType(MemberEntity, IList,
Field->getType(), Index,
2633 StructuredList, StructuredIndex);
2635 CheckImplicitInitList(MemberEntity, IList,
Field->getType(), Index,
2636 StructuredList, StructuredIndex);
2657 PE = IndirectField->
chain_end(); PI != PE; ++PI) {
2665 assert(isa<FieldDecl>(*PI));
2666 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2673 &Replacements[0] + Replacements.size());
2680 for (
unsigned I = 0; I < NumIndexExprs; ++I)
2694 explicit FieldInitializerValidatorCCC(
const RecordDecl *RD)
2702 std::unique_ptr<CorrectionCandidateCallback>
clone()
override {
2703 return std::make_unique<FieldInitializerValidatorCCC>(*
this);
2756 llvm::APSInt *NextElementIndex,
2759 unsigned &StructuredIndex,
2760 bool FinishSubobjectInit,
2761 bool TopLevelObject) {
2762 if (DesigIdx == DIE->
size()) {
2769 assert(isa<InitListExpr>(
Init) &&
2770 "designator result in direct non-list initialization?");
2775 if (StructuredList) {
2779 UpdateStructuredListElement(StructuredList, StructuredIndex,
2783 if (AggrDeductionCandidateParamTypes)
2784 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2789 bool prevHadError = hadError;
2794 unsigned OldIndex = Index;
2796 dyn_cast_if_present<DesignatedInitExpr>(IList->
getInit(OldIndex));
2799 IList->
setInit(OldIndex, OldDIE->getInit());
2801 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2802 StructuredIndex,
true);
2806 if (IList->
getInit(OldIndex) != OldDIE->getInit())
2807 OldDIE->setInit(IList->
getInit(OldIndex));
2808 IList->
setInit(OldIndex, OldDIE);
2810 return hadError && !prevHadError;
2814 bool IsFirstDesignator = (DesigIdx == 0);
2815 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2818 if (IsFirstDesignator)
2819 StructuredList = FullyStructuredList;
2821 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2822 StructuredList->getInit(StructuredIndex) :
nullptr;
2823 if (!ExistingInit && StructuredList->hasArrayFiller())
2824 ExistingInit = StructuredList->getArrayFiller();
2827 StructuredList = getStructuredSubobjectInit(
2828 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2830 else if (
InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2831 StructuredList = Result;
2844 diagnoseInitOverride(ExistingInit,
2851 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2852 StructuredList =
E->getUpdater();
2857 StructuredList->updateInit(SemaRef.
Context, StructuredIndex, DIUE);
2866 StructuredList =
nullptr;
2872 if (
D->isFieldDesignator()) {
2886 Loc =
D->getFieldLoc();
2888 SemaRef.
Diag(
Loc, diag::err_field_designator_non_aggr)
2889 << SemaRef.
getLangOpts().CPlusPlus << CurrentObjectType;
2898 if (
auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2900 }
else if (
auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2906 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2923 SemaRef.
Diag(
D->getFieldLoc(), diag::err_field_designator_nonfield)
2925 SemaRef.
Diag(Lookup.front()->getLocation(),
2926 diag::note_field_designator_found);
2933 FieldInitializerValidatorCCC CCC(RD);
2937 CorrectTypoKind::ErrorRecovery, RD)) {
2940 SemaRef.
PDiag(diag::err_field_designator_unknown_suggest)
2941 << FieldName << CurrentObjectType);
2942 KnownField = Corrected.getCorrectionDeclAs<
FieldDecl>();
2953 SemaRef.
Diag(
Loc, diag::err_field_designator_unknown)
2961 unsigned NumBases = 0;
2962 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2963 NumBases = CXXRD->getNumBases();
2965 unsigned FieldIndex = NumBases;
2967 for (
auto *FI : RD->
fields()) {
2968 if (FI->isUnnamedBitField())
2984 if (StructuredList) {
2985 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2987 assert(StructuredList->getNumInits() == 1
2988 &&
"A union should never have more than one initializer!");
2990 Expr *ExistingInit = StructuredList->getInit(0);
2993 diagnoseInitOverride(
3001 StructuredList->resizeInits(SemaRef.
Context, 0);
3002 StructuredList->setInitializedFieldInUnion(
nullptr);
3005 StructuredList->setInitializedFieldInUnion(*Field);
3012 InvalidUse = !SemaRef.
CanUseDecl(*Field, TreatUnavailableAsInvalid);
3035 if (IsFirstDesignator && !VerifyOnly && SemaRef.
getLangOpts().CPlusPlus &&
3038 (*NextField)->getFieldIndex() >
Field->getFieldIndex() + 1)) {
3042 if (FI->isUnnamedBitField())
3053 diag::ext_designated_init_reordered)
3056 unsigned OldIndex = StructuredIndex - 1;
3057 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
3058 if (
Expr *PrevInit = StructuredList->getInit(OldIndex)) {
3059 SemaRef.
Diag(PrevInit->getBeginLoc(),
3060 diag::note_previous_field_init)
3070 D->setFieldDecl(*Field);
3074 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
3075 StructuredList->resizeInits(SemaRef.
Context, FieldIndex + 1);
3078 if (
Field->getType()->isIncompleteArrayType()) {
3080 if ((DesigIdx + 1) != DIE->
size()) {
3087 diag::err_designator_into_flexible_array_member)
3089 SemaRef.
Diag(
Field->getLocation(), diag::note_flexible_array_member)
3095 if (!hadError && !isa<InitListExpr>(DIE->
getInit()) &&
3096 !isa<StringLiteral>(DIE->
getInit())) {
3100 diag::err_flexible_array_init_needs_braces)
3102 SemaRef.
Diag(
Field->getLocation(), diag::note_flexible_array_member)
3109 if (!
Invalid && CheckFlexibleArrayInit(Entity, DIE->
getInit(), *Field,
3119 bool prevHadError = hadError;
3120 unsigned newStructuredIndex = FieldIndex;
3121 unsigned OldIndex = Index;
3126 CheckSubElementType(MemberEntity, IList,
Field->getType(), Index,
3127 StructuredList, newStructuredIndex);
3129 IList->
setInit(OldIndex, DIE);
3130 if (hadError && !prevHadError) {
3135 StructuredIndex = FieldIndex;
3141 unsigned newStructuredIndex = FieldIndex;
3145 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
3146 FieldType,
nullptr,
nullptr, Index,
3147 StructuredList, newStructuredIndex,
3148 FinishSubobjectInit,
false))
3159 if (IsFirstDesignator) {
3166 StructuredIndex = FieldIndex;
3170 if (!FinishSubobjectInit)
3178 bool prevHadError = hadError;
3183 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
3184 false, Index, StructuredList, FieldIndex);
3185 return hadError && !prevHadError;
3206 SemaRef.
Diag(
D->getLBracketLoc(), diag::err_array_designator_non_array)
3207 << CurrentObjectType;
3212 Expr *IndexExpr =
nullptr;
3213 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3214 if (
D->isArrayDesignator()) {
3217 DesignatedEndIndex = DesignatedStartIndex;
3219 assert(
D->isArrayRangeDesignator() &&
"Need array-range designator");
3221 DesignatedStartIndex =
3223 DesignatedEndIndex =
3232 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3237 if (isa<ConstantArrayType>(AT)) {
3238 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(),
false);
3239 DesignatedStartIndex
3240 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3241 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3243 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3244 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3245 if (DesignatedEndIndex >= MaxElements) {
3248 diag::err_array_designator_too_large)
3255 unsigned DesignatedIndexBitWidth =
3257 DesignatedStartIndex =
3258 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3259 DesignatedEndIndex =
3260 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3261 DesignatedStartIndex.setIsUnsigned(
true);
3262 DesignatedEndIndex.setIsUnsigned(
true);
3265 bool IsStringLiteralInitUpdate =
3266 StructuredList && StructuredList->isStringLiteralInit();
3267 if (IsStringLiteralInitUpdate && VerifyOnly) {
3270 StructuredList =
nullptr;
3271 }
else if (IsStringLiteralInitUpdate) {
3284 unsigned PromotedCharTyWidth = Context.
getTypeSize(PromotedCharTy);
3289 if (
const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3290 CAT && CAT->getSize().ult(StrLen))
3291 StrLen = CAT->getZExtSize();
3292 StructuredList->resizeInits(Context, StrLen);
3296 for (
unsigned i = 0, e = StrLen; i != e; ++i) {
3297 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3299 Context, CodeUnit, PromotedCharTy, SubExpr->
getExprLoc());
3300 if (CharTy != PromotedCharTy)
3304 StructuredList->updateInit(Context, i,
Init);
3313 if (
const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3314 CAT && CAT->getSize().ult(StrLen))
3315 StrLen = CAT->getZExtSize();
3316 StructuredList->resizeInits(Context, StrLen);
3320 for (
unsigned i = 0, e = StrLen; i != e; ++i) {
3321 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3323 Context, CodeUnit, PromotedCharTy, SubExpr->
getExprLoc());
3324 if (CharTy != PromotedCharTy)
3328 StructuredList->updateInit(Context, i,
Init);
3335 if (StructuredList &&
3336 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3337 StructuredList->resizeInits(SemaRef.
Context,
3338 DesignatedEndIndex.getZExtValue() + 1);
3344 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3345 unsigned OldIndex = Index;
3350 while (DesignatedStartIndex <= DesignatedEndIndex) {
3356 if (CheckDesignatedInitializer(
3357 ElementEntity, IList, DIE, DesigIdx + 1, ElementType,
nullptr,
3358 nullptr, Index, StructuredList, ElementIndex,
3359 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3364 ++DesignatedStartIndex;
3365 ElementIndex = DesignatedStartIndex.getZExtValue();
3370 if (IsFirstDesignator) {
3371 if (NextElementIndex)
3372 *NextElementIndex = DesignatedStartIndex;
3373 StructuredIndex = ElementIndex;
3377 if (!FinishSubobjectInit)
3381 bool prevHadError = hadError;
3382 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3384 StructuredList, ElementIndex);
3385 return hadError && !prevHadError;
3391InitListChecker::getStructuredSubobjectInit(
InitListExpr *IList,
unsigned Index,
3394 unsigned StructuredIndex,
3396 bool IsFullyOverwritten) {
3397 if (!StructuredList)
3400 Expr *ExistingInit =
nullptr;
3401 if (StructuredIndex < StructuredList->getNumInits())
3402 ExistingInit = StructuredList->
getInit(StructuredIndex);
3404 if (
InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3413 if (!IsFullyOverwritten)
3436 diagnoseInitOverride(ExistingInit, InitRange);
3439 unsigned ExpectedNumInits = 0;
3440 if (Index < IList->getNumInits()) {
3441 if (
auto *
Init = dyn_cast_or_null<InitListExpr>(IList->
getInit(Index)))
3442 ExpectedNumInits =
Init->getNumInits();
3448 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3457InitListChecker::createInitListExpr(
QualType CurrentObjectType,
3459 unsigned ExpectedNumInits) {
3463 QualType ResultType = CurrentObjectType;
3466 Result->setType(ResultType);
3469 unsigned NumElements = 0;
3474 NumElements = CAType->getZExtSize();
3477 if (NumElements > ExpectedNumInits)
3481 NumElements = VType->getNumElements();
3483 NumElements = numStructUnionElements(CurrentObjectType);
3488 Result->reserveInits(SemaRef.
Context, NumElements);
3495void InitListChecker::UpdateStructuredListElement(
InitListExpr *StructuredList,
3496 unsigned &StructuredIndex,
3499 if (!StructuredList)
3503 StructuredIndex,
expr)) {
3509 diagnoseInitOverride(PrevInit,
expr->getSourceRange());
3518 InitListChecker Check(*
this, Entity, From,
Type,
true,
3521 return !Check.HadError();
3542 return S.
Diag(
Loc, diag::err_array_designator_negative)
3545 Value.setIsUnsigned(
true);
3563 if (
D.isFieldDesignator()) {
3564 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3565 D.getFieldDecl(),
D.getDotLoc(),
D.getFieldLoc()));
3566 }
else if (
D.isArrayDesignator()) {
3567 Expr *Index =
D.getArrayIndex();
3568 llvm::APSInt IndexValue;
3569 if (!Index->isTypeDependent() && !Index->isValueDependent())
3574 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3575 InitExpressions.size(),
D.getLBracketLoc(),
D.getRBracketLoc()));
3576 InitExpressions.push_back(Index);
3578 }
else if (
D.isArrayRangeDesignator()) {
3579 Expr *StartIndex =
D.getArrayRangeStart();
3580 Expr *EndIndex =
D.getArrayRangeEnd();
3581 llvm::APSInt StartValue;
3582 llvm::APSInt EndValue;
3587 if (!StartDependent)
3593 if (!StartIndex || !EndIndex)
3597 if (StartDependent || EndDependent) {
3599 }
else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3600 EndValue = EndValue.extend(StartValue.getBitWidth());
3601 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3602 StartValue = StartValue.extend(EndValue.getBitWidth());
3604 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3605 Diag(
D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3610 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3611 InitExpressions.size(),
D.getLBracketLoc(),
D.getEllipsisLoc(),
3612 D.getRBracketLoc()));
3613 InitExpressions.push_back(StartIndex);
3614 InitExpressions.push_back(EndIndex);
3624 EqualOrColonLoc, GNUSyntax,
3632InitializedEntity::InitializedEntity(
ASTContext &Context,
unsigned Index,
3637 Kind = EK_ArrayElement;
3640 Kind = EK_VectorElement;
3644 assert(CT &&
"Unexpected type");
3645 Kind = EK_ComplexElement;
3653 bool IsInheritedVirtualBase,
3658 Result.Base = {
Base, IsInheritedVirtualBase};
3676 return Variable.VariableOrMember->getDeclName();
3698 llvm_unreachable(
"Invalid EntityKind!");
3708 return cast<ValueDecl>(
Variable.VariableOrMember);
3732 llvm_unreachable(
"Invalid EntityKind!");
3767unsigned InitializedEntity::dumpImpl(raw_ostream &OS)
const {
3770 for (
unsigned I = 0; I != Depth; ++I)
3787 case EK_New: OS <<
"New";
break;
3791 case EK_Base: OS <<
"Base";
break;
3798 OS <<
"Block (lambda)";
3801 OS <<
"LambdaCapture ";
3808 D->printQualifiedName(OS);
3811 OS <<
" '" <<
getType() <<
"'\n";
3817 dumpImpl(llvm::errs());
3872 for (
const Step &S : llvm::reverse(Steps)) {
3932 llvm_unreachable(
"Invalid EntityKind!");
3940InitializationSequence
3943 bool HadMultipleCandidates) {
3947 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3949 S.Function.FoundDecl =
Found;
3968 bool BindingTemporary) {
3993 bool HadMultipleCandidates) {
3997 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3999 S.Function.FoundDecl = FoundDecl;
4038 bool TopLevelOfInitList) {
4056 bool HadMultipleCandidates,
bool FromInitList,
bool AsInitList) {
4062 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4064 S.Function.FoundDecl = FoundDecl;
4107 Steps.insert(Steps.begin(), S);
4168 "Can only unwrap trivial init lists.");
4172 Steps.insert(Steps.begin(), S);
4178 "Can only rewrap trivial init lists.");
4182 Steps.insert(Steps.begin(), S);
4186 S.WrappingSyntacticList = Syntactic;
4193 this->Failure = Failure;
4194 this->FailedOverloadResult =
Result;
4215 if (!
Init.empty()) {
4235 "consuming an object of unretainable type?");
4255 bool TreatUnavailableAsInvalid) {
4270 Expr *OVEAsExpr = &OVE;
4273 TreatUnavailableAsInvalid);
4283 bool TreatUnavailableAsInvalid);
4294 bool TreatUnavailableAsInvalid) {
4308 List->getNumInitsWithEmbedExpanded()),
4313 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4315 TreatUnavailableAsInvalid);
4342 bool CopyInitializing,
bool AllowExplicit,
bool OnlyListConstructors,
4343 bool IsListInit,
bool RequireActualConstructor,
4344 bool SecondStepOfCopyInit =
false) {
4350 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4367 bool SuppressUserConversions =
4368 SecondStepOfCopyInit ||
4369 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4372 if (Info.ConstructorTmpl)
4374 Info.ConstructorTmpl, Info.FoundDecl,
4375 nullptr, Args, CandidateSet, SuppressUserConversions,
4376 false, AllowExplicit);
4385 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4389 CandidateSet, SuppressUserConversions,
4390 false, AllowExplicit,
4406 if (S.
getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4407 !RequireActualConstructor && !SecondStepOfCopyInit) {
4409 auto *SourceRD =
Initializer->getType()->getAsCXXRecordDecl();
4411 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4412 for (
auto I = Conversions.begin(),
E = Conversions.end(); I !=
E; ++I) {
4415 D =
D->getUnderlyingDecl();
4422 Conv = cast<CXXConversionDecl>(
D);
4426 ConvTemplate, I.getPair(), ActingDC,
Initializer, DestType,
4427 CandidateSet, AllowExplicit, AllowExplicit,
4431 DestType, CandidateSet, AllowExplicit,
4458 bool IsListInit =
false,
4459 bool IsInitListCopy =
false) {
4460 assert(((!IsListInit && !IsInitListCopy) ||
4461 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4462 "IsListInit/IsInitListCopy must come with a single initializer list "
4465 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) :
nullptr;
4475 bool RequireActualConstructor =
4481 bool CopyElisionPossible =
false;
4482 auto ElideConstructor = [&] {
4498 if (S.
getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4499 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4521 assert(!IsInitListCopy &&
4522 "IsInitListCopy only possible with aggregate types");
4523 CopyElisionPossible =
true;
4537 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4547 bool AsInitializerList =
false;
4559 AsInitializerList =
true;
4565 S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4566 CopyInitialization, AllowExplicit,
4567 true, IsListInit, RequireActualConstructor);
4582 AsInitializerList =
false;
4584 S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4585 Best, CopyInitialization, AllowExplicit,
4586 false, IsListInit, RequireActualConstructor);
4598 bool HadMultipleCandidates = (CandidateSet.
size() > 1);
4602 if (
auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4604 QualType ConvType = CD->getConversionType();
4606 "should not have selected this conversion function");
4608 HadMultipleCandidates);
4622 DestRecordDecl->isAggregate() &&
4623 DestRecordDecl->hasUninitializedExplicitInitFields() &&
4625 S.
Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
4626 << 1 << DestRecordDecl;
4651 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->
isExplicit()) {
4671 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4672 IsListInit | IsInitListCopy, AsInitializerList);
4692 bool IsAggrListInit) {
4710 Sequence,
false, IsAggrListInit);
4738 bool HadMultipleCandidates =
false;
4741 UnqualifiedTargetType,
4743 &HadMultipleCandidates)) {
4745 HadMultipleCandidates);
4746 SourceType = Fn->getType();
4765 bool TopLevelOfInitList);
4779 bool TreatUnavailableAsInvalid) {
4819 T1Quals, cv2T2, T2, T2Quals, Sequence,
4827 if (!Sequence.
steps().empty())
4850 TreatUnavailableAsInvalid);
4882 bool TreatUnavailableAsInvalid) {
4897 TreatUnavailableAsInvalid);
4935 !IsDesignatedInit) {
4946 Expr *InitListAsExpr = InitList;
4948 S, Entity, SubKind, InitListAsExpr, DestType, Sequence,
4964 if (isa<ConstantArrayType>(DestAT) &&
4966 isa<DecompositionDecl>(Entity.
getDecl())) {
4969 "Deduced to other type?");
4971 "List-initialize structured bindings but not "
4972 "direct-list-initialization?");
4977 Entity, SubInit[0], DestType, Sequence,
4978 TreatUnavailableAsInvalid);
4984 if (!isa<VariableArrayType>(DestAT) &&
4994 TreatUnavailableAsInvalid);
5027 TreatUnavailableAsInvalid))
5031 Expr *InitListAsExpr = InitList;
5033 DestType, Sequence,
true);
5099 if (
Init->getType()->isRecordType() ||
5110 TreatUnavailableAsInvalid);
5117 InitListChecker CheckInitList(S, Entity, InitList,
5118 DestType,
true, TreatUnavailableAsInvalid);
5119 if (CheckInitList.HadError()) {
5141 "Must have incompatible references when binding via conversion");
5152 bool AllowExplicitCtors =
false;
5153 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
5158 if (T1RecordDecl->isInvalidDecl())
5164 if (!Info.Constructor)
5167 if (!Info.Constructor->isInvalidDecl() &&
5168 Info.Constructor->isConvertingConstructor(
true)) {
5169 if (Info.ConstructorTmpl)
5171 Info.ConstructorTmpl, Info.FoundDecl,
5174 false, AllowExplicitCtors);
5177 Info.Constructor, Info.FoundDecl,
Initializer, CandidateSet,
5179 false, AllowExplicitCtors);
5186 if (T2RecordDecl->isInvalidDecl())
5190 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5191 for (
auto I = Conversions.begin(),
E = Conversions.end(); I !=
E; ++I) {
5194 if (isa<UsingShadowDecl>(
D))
5195 D = cast<UsingShadowDecl>(
D)->getTargetDecl();
5202 Conv = cast<CXXConversionDecl>(
D);
5210 if ((AllowRValues ||
5214 ConvTemplate, I.getPair(), ActingDC,
Initializer, DestType,
5216 false, AllowExplicitConvs);
5219 Conv, I.getPair(), ActingDC,
Initializer, DestType, CandidateSet,
5220 false, AllowExplicitConvs);
5240 if (isa<CXXConversionDecl>(
Function))
5253 bool HadMultipleCandidates = (CandidateSet.
size() > 1);
5255 HadMultipleCandidates);
5265 assert(Best->HasFinalConversion && !isa<CXXConstructorDecl>(
Function) &&
5266 "should not have conversion after constructor");
5270 ICS.
Standard = Best->FinalConversion;
5291 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5293 else if (RefConv & Sema::ReferenceConversions::ObjC)
5295 else if (RefConv & Sema::ReferenceConversions::Function)
5297 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5314 bool TopLevelOfInitList) {
5332 T1Quals, cv2T2, T2, T2Quals, Sequence,
5333 TopLevelOfInitList);
5357 bool TopLevelOfInitList) {
5381 if (isLValueRef || T1Function) {
5384 (Kind.isCStyleOrFunctionalCast() &&
5388 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5389 Sema::ReferenceConversions::ObjC)) {
5392 if (RefConv & (Sema::ReferenceConversions::Qualification))
5396 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5400 }
else if (RefConv & Sema::ReferenceConversions::Qualification) {
5404 }
else if (RefConv & Sema::ReferenceConversions::Function) {
5424 (isLValueRef || InitCategory.
isRValue())) {
5429 isLValueRef, Sequence);
5464 switch (RefRelationship) {
5476 llvm_unreachable(
"unexpected kind of compatible initializer");
5500 (Kind.isCStyleOrFunctionalCast() &&
5529 auto T1QualsIgnoreAS = T1Quals;
5530 auto T2QualsIgnoreAS = T2Quals;
5533 T2QualsIgnoreAS.removeAddressSpace();
5536 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5546 cv1T4 = cv1T4WithAS;
5551 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5553 else if (RefConv & Sema::ReferenceConversions::ObjC)
5555 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5572 isLValueRef, Sequence);
5612 Sema::AllowedExplicit::None,
5614 Kind.isCStyleOrFunctionalCast(),
5633 TopLevelOfInitList);
5642 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5687 assert((!InitList || InitList->
getNumInits() == 0) &&
5688 "Shouldn't use value-init for non-empty init lists");
5694 assert(!
T->
isVoidType() &&
"Cannot value-init void");
5700 bool NeedZeroInitialization =
true;
5715 NeedZeroInitialization =
false;
5723 if (NeedZeroInitialization)
5737 ClassDecl->hasUninitializedReferenceMember()) {
5745 Expr *InitListAsExpr = InitList;
5747 bool InitListSyntax = InitList;
5752 S, Entity, Kind, Args,
T, Entity.
getType(), Sequence, InitListSyntax);
5801 unsigned EntityIndexToProcess = 0;
5804 Expr *ArrayFiller =
nullptr;
5805 FieldDecl *InitializedFieldInUnion =
nullptr;
5809 Expr *Arg,
Expr **InitExpr =
nullptr) {
5811 S, SubEntity, SubKind,
5827 ER = IS.
Perform(S, SubEntity, SubKind,
5834 *InitExpr = ER.
get();
5836 InitExprs.push_back(ER.
get());
5843 uint64_t ArrayLength;
5851 ArrayLength = CAT->getZExtSize();
5852 ResultType = Entity.
getType();
5859 const Expr *SE = VAT->getSizeExpr();
5865 ArrayLength = Args.size();
5867 EntityIndexToProcess = ArrayLength;
5871 for (
Expr *
E : Args) {
5876 if (!HandleInitializedEntity(SubEntity, SubKind,
E))
5884 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
true);
5885 if (!HandleInitializedEntity(SubEntity, SubKind,
nullptr, &ArrayFiller))
5889 if (ResultType.
isNull()) {
5909 if (EntityIndexToProcess < Args.size()) {
5915 Expr *
E = Args[EntityIndexToProcess];
5918 if (!HandleInitializedEntity(SubEntity, SubKind,
E))
5926 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
5928 if (!HandleInitializedEntity(SubEntity, SubKind,
nullptr))
5931 EntityIndexToProcess++;
5944 if (EntityIndexToProcess < Args.size()) {
5946 Expr *
E = Args[EntityIndexToProcess];
5964 if (!HandleInitializedEntity(SubEntity, SubKind,
E))
5972 InitializedFieldInUnion = FD;
5973 EntityIndexToProcess = 1;
5979 if (!VerifyOnly && FD->
hasAttr<ExplicitInitAttr>() &&
5981 S.
Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
5992 Kind.getParenOrBraceRange().getEnd(), FD);
5996 InitExprs.push_back(DIE.
get());
6006 S.
Diag(SR.
getEnd(), diag::err_init_reference_member_uninitialized)
6013 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
true);
6014 if (!HandleInitializedEntity(SubEntity, SubKind,
nullptr))
6018 EntityIndexToProcess++;
6020 ResultType = Entity.
getType();
6025 if (EntityIndexToProcess < Args.size()) {
6030 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
6031 Args.back()->getEndLoc());
6032 S.
Diag(Kind.getLocation(), diag::err_excess_initializers)
6033 << InitKind << ExcessInitSR;
6047 CPLIE->setArrayFiller(ArrayFiller);
6048 if (InitializedFieldInUnion)
6049 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
6051 S.
Diag(Kind.getLocation(),
6052 diag::warn_cxx17_compat_aggregate_init_paren_list)
6053 << Kind.getLocation() << SR << ResultType;
6065 bool TopLevelOfInitList) {
6066 assert(!DestType->
isReferenceType() &&
"References are handled elsewhere");
6069 "Must have a class type to perform a user-defined conversion");
6079 bool AllowExplicit = Kind.AllowExplicit();
6089 if (!Info.Constructor)
6092 if (!Info.Constructor->isInvalidDecl() &&
6093 Info.Constructor->isConvertingConstructor(
true)) {
6094 if (Info.ConstructorTmpl)
6096 Info.ConstructorTmpl, Info.FoundDecl,
6099 false, AllowExplicit);
6104 false, AllowExplicit);
6120 const auto &Conversions =
6122 for (
auto I = Conversions.begin(),
E = Conversions.end(); I !=
E; ++I) {
6125 if (isa<UsingShadowDecl>(
D))
6126 D = cast<UsingShadowDecl>(
D)->getTargetDecl();
6133 Conv = cast<CXXConversionDecl>(
D);
6137 ConvTemplate, I.getPair(), ActingDC,
Initializer, DestType,
6138 CandidateSet, AllowExplicit, AllowExplicit);
6141 DestType, CandidateSet, AllowExplicit,
6167 bool HadMultipleCandidates = (CandidateSet.
size() > 1);
6169 if (isa<CXXConstructorDecl>(
Function)) {
6175 HadMultipleCandidates);
6204 HadMultipleCandidates);
6217 Function->getReturnType()->isReferenceType() ||
6227 assert(Best->HasFinalConversion);
6228 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
6229 Best->FinalConversion.Third) {
6232 ICS.
Standard = Best->FinalConversion;
6242 bool isAddressOf,
bool &isWeakAccess) {
6248 if (op->getOpcode() == UO_AddrOf)
6253 }
else if (
CastExpr *ce = dyn_cast<CastExpr>(e)) {
6254 switch (ce->getCastKind()) {
6257 case CK_LValueBitCast:
6261 case CK_ArrayToPointerDecay:
6264 case CK_NullToPointer:
6272 }
else if (isa<DeclRefExpr>(e)) {
6276 isWeakAccess =
true;
6280 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
6294 }
else if (isa<ArraySubscriptExpr>(e)) {
6310 bool isWeakAccess =
false;
6314 if (S.
getLangOpts().ObjCAutoRefCount && isWeakAccess)
6346 bool ArrayDecay =
false;
6351 ArgPointee = ArgArrayType->getElementType();
6363 bool ShouldCopy =
true;
6403 std::optional<llvm::APSInt>
Value =
Init->getIntegerConstantExpr(Ctx);
6434 "cl_intel_device_side_avc_motion_estimation", S.
getLangOpts()) &&
6436 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6437 DestType->isOCLIntelSubgroupAVCMceResultType())
6451 MultiExprArg Args,
bool TopLevelOfInitList,
bool TreatUnavailableAsInvalid)
6455 TreatUnavailableAsInvalid);
6461 auto *DRE = dyn_cast<DeclRefExpr>(
E);
6462 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
6466 cast<FunctionDecl>(DRE->getDecl()));
6483 return isa<DecompositionDecl>(Entity.
getDecl());
6506 assert(!isa<CXXRecordDecl>(RD) &&
"Only expect to call this in C mode");
6532 bool TopLevelOfInitList,
6533 bool TreatUnavailableAsInvalid) {
6540 for (
unsigned I = 0,
E = Args.size(); I !=
E; ++I)
6541 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6548 Args[I] = result.
get();
6570 if (Args.size() == 1) {
6588 TreatUnavailableAsInvalid);
6597 if (Rec->hasUninitializedExplicitInitFields()) {
6609 if (Var && !
Initializer && !Rec->isUnion() && !Rec->isInvalidDecl()) {
6611 unsigned DiagID = diag::warn_default_init_const_field_unsafe;
6614 DiagID = diag::warn_default_init_const_field;
6617 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
6621 S.
Diag(FD->
getLocation(), diag::note_default_init_const_member) << FD;
6634 if (Args.size() != 1)
6640 else if (isa<InitListExpr>(Args[0]))
6644 TopLevelOfInitList);
6670 if (
Initializer && isa<VariableArrayType>(DestAT)) {
6704 cast<ArrayParameterType>(SrcType)->getConstantArrayType(Context);
6707 TreatUnavailableAsInvalid);
6714 if (
Initializer && isa<ConstantArrayType>(DestAT) &&
6719 TreatUnavailableAsInvalid);
6727 isa<CompoundLiteralExpr>(
Initializer->IgnoreParens()) &&
6745 *
this, TreatUnavailableAsInvalid);
6747 }
else if (S.
getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6763 bool allowObjCWritebackConversion = S.
getLangOpts().ObjCAutoRefCount &&
6772 assert(
Initializer &&
"Initializer must be non-null");
6774 if (allowObjCWritebackConversion &&
6800 SourceType, DestType))))) {
6810 assert(
Initializer &&
"Initializer must be non-null");
6812 TopLevelOfInitList);
6817 assert(Args.size() >= 1 &&
"Zero-argument case handled above");
6827 for (
auto *Arg : Args) {
6828 if (Arg->getType()->isExtVectorType()) {
6831 for (
unsigned Idx = 0; Idx < Elm; ++Idx) {
6837 VTy->getElementType(), Arg->
getValueKind(), Arg->getObjectKind(),
6841 InitArgs.emplace_back(Arg);
6851 if (Args.size() > 1) {
6854 }
else if (isa<InitListExpr>(Args[0])) {
6862 assert(
Initializer &&
"Initializer must be non-null");
6865 bool NeedAtomicConversion =
false;
6869 Atomic->getValueType())) {
6870 DestType =
Atomic->getValueType();
6871 NeedAtomicConversion =
true;
6876 TopLevelOfInitList);
6878 if (!
Failed() && NeedAtomicConversion)
6905 Sema::AllowedExplicit::None,
6907 Kind.isCStyleOrFunctionalCast(),
6908 allowObjCWritebackConversion);
6916 bool ShouldCopy =
true;
6932 }
else if (ICS.
isBad()) {
6938 else if (
Initializer->getType()->isFunctionType() &&
6951 for (
auto &S : Steps)
6959 bool Diagnose =
false) {
7010 llvm_unreachable(
"Invalid EntityKind!");
7044 llvm_unreachable(
"missed an InitializedEntity kind?");
7078 llvm_unreachable(
"missed an InitializedEntity kind?");
7117 llvm_unreachable(
"missed an InitializedEntity kind?");
7144 bool IsExtraneousCopy) {
7167 S,
Loc, CurInitExpr, CandidateSet,
T, Ctors, Best,
7179 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
7180 : diag::err_temp_copy_no_viable)
7198 S.
Diag(
Loc, diag::err_temp_copy_deleted)
7205 bool HadMultipleCandidates = CandidateSet.
size() > 1;
7214 if (IsExtraneousCopy) {
7225 for (
unsigned I = 1, N =
Constructor->getNumParams(); I != N; ++I) {
7228 diag::err_call_incomplete_argument))
7269 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
7275 HadMultipleCandidates,
7291 Expr *CurInitExpr) {
7309 S,
Loc, CurInitExpr, CandidateSet, CurInitExpr->
getType(), Ctors, Best,
7322 Best->FoundDecl, Entity,
Diag);
7343void InitializationSequence::PrintInitLocationNote(
Sema &S,
7358 diag::note_method_return_type_change)
7376 switch (Kind.getKind()) {
7382 return NumArgs != 1;
7394 bool &ConstructorInitRequiresZeroInit,
7395 bool IsListInitialization,
7396 bool IsStdInitListInitialization,
7399 unsigned NumArgs = Args.size();
7407 ? Kind.getEqualLoc()
7408 : Kind.getLocation();
7414 assert(
Constructor->getParent() &&
"No parent class for constructor.");
7431 bool AllowExplicitConv =
7432 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7437 if (NumArgs == 1 && !Kind.isExplicitCast())
7439 Entity.
getType(), Args.front()->getType(), Kind.getLocation());
7444 ConstructorArgs, AllowExplicitConv,
7445 IsListInitialization))
7459 if (I >= ConstructorArgs.size() && FD->
hasAttr<ExplicitInitAttr>() &&
7461 S.
Diag(
Loc, diag::warn_field_requires_explicit_init)
7476 : Kind.getParenOrBraceRange();
7479 if (
auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7489 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7490 IsListInitialization, IsStdInitListInitialization,
7491 ConstructorInitRequiresZeroInit),
7507 if (IsListInitialization)
7508 ParenOrBraceRange =
SourceRange(LBraceLoc, RBraceLoc);
7510 ParenOrBraceRange = Kind.getParenOrBraceRange();
7519 HadMultipleCandidates,
7520 IsListInitialization,
7521 IsStdInitListInitialization,
7522 ConstructorInitRequiresZeroInit,
7530 HadMultipleCandidates,
7531 IsListInitialization,
7532 IsStdInitListInitialization,
7533 ConstructorInitRequiresZeroInit,
7564 const Expr *PostInit);
7571 bool IsReturnStmt) {
7582 unsigned DiagID = 0;
7612 if (VD->
hasAttr<BlocksAttr>())
7625 if (isa<ParmVarDecl>(VD))
7626 DiagID = diag::warn_redundant_move_on_return;
7628 DiagID = diag::warn_pessimizing_move_on_return;
7630 DiagID = diag::warn_pessimizing_move_on_initialization;
7672 if (UO->getOpcode() == UO_Deref &&
7673 UO->getSubExpr()->IgnoreParenCasts()->
7676 S.
PDiag(diag::warn_binding_null_to_reference)
7677 << UO->getSubExpr()->getSourceRange());
7683 bool BoundToLvalueReference) {
7729 if (!PointeeTy.isNull() &&
7730 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
7731 CK = CK_AddressSpaceConversion;
7733 CK = CK_AddressSpaceConversion;
7748 if (!ZeroInitializationFixit.empty()) {
7750 const auto *VD = dyn_cast_or_null<VarDecl>(
D);
7756 if (!DestType->
isRecordType() && VD && VD->isConstexpr()) {
7758 S.
Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
7761 ZeroInitializationFixit);
7763 unsigned DiagID = diag::err_default_init_const;
7765 DiagID = diag::ext_default_init_const;
7767 S.
Diag(Kind.getLocation(), DiagID)
7770 ZeroInitializationFixit);
7790 if (isa<InitListExpr>((
Expr *)Args[0]))
7792 ArrayT->getElementType(),
7793 nullptr, ArrayT->getSizeModifier(),
7794 ArrayT->getIndexTypeCVRQualifiers());
7798 !Kind.isExplicitCast()) {
7800 SourceRange ParenRange = Kind.getParenOrBraceRange();
7805 Kind.isExplicitCast() ||
7815 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
7821 S.
Diag(
Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
7822 <<
Init->getSourceRange();
7825 if (S.
getLangOpts().MicrosoftExt && Args.size() == 1 &&
7831 S.
Diag(
Init->getBeginLoc(), diag::ext_init_from_predefined) <<
Init;
7842 S.
Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
7862 isa<InitListExpr>(Args[0]);
7863 (void)IsHLSLVectorInit;
7868 switch (Steps.front().Kind) {
7902 assert(Args.size() == 1 || IsHLSLVectorInit);
7921 isa_and_nonnull<InitListExpr>(CurInit.
get()));
7926 auto checkAbstractType = [&](
QualType T) ->
bool {
7931 diag::err_allocation_of_abstract_type);
7936 bool ConstructorInitRequiresZeroInit =
false;
7969 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
7981 CK_DerivedToBase, CurInit.
get(),
7997 if (
auto *DRE = dyn_cast<DeclRefExpr>(CurInit.
get()->
IgnoreParens())) {
7998 if (
auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8011 assert(CurInit.
get()->
isPRValue() &&
"not a temporary");
8069 bool CreatedObject =
false;
8086 HadMultipleCandidates,
8098 CastKind = CK_ConstructorConversion;
8099 CreatedObject =
true;
8109 HadMultipleCandidates);
8113 CastKind = CK_UserDefinedConversion;
8117 if (CreatedObject && checkAbstractType(CurInit.
get()->
getType()))
8137 S.
PDiag(diag::err_access_dtor_temp) <<
T);
8161 "function reference should be lvalue");
8167 assert(CurInit.
get()->
isPRValue() &&
"cannot convert glvalue to atomic");
8175 if (
const auto *FromPtrType =
8178 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8179 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8182 if (!Kind.isStaticCast()) {
8184 diag::warn_noderef_to_dereferenceable_pointer)
8203 CurInit = CurInitExprRes;
8224 InitListChecker PerformInitList(S, InitEntity,
8225 InitList, Ty,
false,
8227 if (PerformInitList.HadError())
8235 if ((*ResultType)->isRValueReferenceType())
8237 else if ((*ResultType)->isLValueReferenceType())
8244 PerformInitList.getFullyStructuredList();
8248 : StructuredInitList;
8265 assert(Args.size() == 1 &&
"expected a single argument for list init");
8267 S.
Diag(InitList->
getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
8273 ConstructorInitRequiresZeroInit,
8282 CurInit = cast<InitListExpr>(CurInit.
get())->getInit(0);
8311 bool IsStdInitListInit =
8315 ? Kind.getParenOrBraceRange()
8318 S, UseTemporary ? TempEntity : Entity, Kind,
8320 ConstructorInitRequiresZeroInit,
8331 if (NextStep != StepEnd &&
8336 ConstructorInitRequiresZeroInit =
true;
8339 !Kind.isImplicitValueInit()) {
8343 Kind.getRange().getBegin());
8347 Kind.getRange().getEnd());
8382 CurInit = CurInitExprRes;
8397 S.
Diag(Kind.getLocation(), diag::err_c23_constexpr_pointer_not_null);
8411 InitialCurInit.
get(),
8414 PrintInitLocationNote(S, Entity);
8416 }
else if (Complained)
8417 PrintInitLocationNote(S, Entity);
8433 CK_ObjCObjectLValueCast,
8445 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
8446 ArrayLoopCommonExprs.push_back(BaseExpr);
8451 assert(!ArrayLoopCommonExprs.empty() &&
8452 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
8453 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
8462 S.
Diag(Kind.getLocation(), diag::ext_array_init_copy)
8476 IncompleteDest->getElementType(), ConstantSource->getSize(),
8486 S.
Diag(Kind.getLocation(), diag::ext_array_init_parens)
8506 diag::warn_cxx98_compat_initializer_list_init)
8519 [[maybe_unused]]
bool IsStdInitializerList =
8521 assert(IsStdInitializerList &&
8522 "StdInitializerList step to non-std::initializer_list");
8524 assert(
Record->isCompleteDefinition() &&
8525 "std::initializer_list should have already be "
8526 "complete/instantiated by this point");
8528 auto InvalidType = [&] {
8530 diag::err_std_initializer_list_malformed)
8537 return InvalidType();
8540 if (Field ==
Record->field_end())
8541 return InvalidType();
8544 if (!Field->getType()->isPointerType() ||
8547 return InvalidType();
8549 if (++Field ==
Record->field_end())
8550 return InvalidType();
8553 if (
const auto *PT = Field->getType()->getAs<
PointerType>()) {
8556 return InvalidType();
8558 if (Field->isBitField() ||
8560 return InvalidType();
8563 if (++Field !=
Record->field_end())
8564 return InvalidType();
8591 "Sampler initialization on non-sampler type.");
8597 S.
Diag(Kind.getLocation(), diag::err_sampler_argument_required)
8601 auto Var = cast<VarDecl>(DRE->getDecl());
8604 if (!Var->hasGlobalStorage()) {
8616 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8618 Init = cast<ImplicitCastExpr>(
const_cast<Expr*
>(
8619 Var->getInit()))->getSubExpr();
8620 SourceType =
Init->getType();
8627 if (!
Init->isConstantInitializer(S.
Context,
false))
8632 S.
Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
8640 const uint64_t SamplerValue =
Result.getLimitedValue();
8647 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
8648 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
8649 if (FilterMode != 1 && FilterMode != 2 &&
8651 "cl_intel_device_side_avc_motion_estimation", S.
getLangOpts()))
8652 S.
Diag(Kind.getLocation(),
8653 diag::warn_sampler_initializer_invalid_bits)
8655 if (AddressingMode > 4)
8656 S.
Diag(Kind.getLocation(),
8657 diag::warn_sampler_initializer_invalid_bits)
8658 <<
"Addressing Mode";
8664 CK_IntToOCLSampler);
8670 "Wrong type for initialization of OpenCL opaque type.");
8673 CK_ZeroToOCLOpaqueType,
8681 if (CurInit.
get() && ResultType)
8702 cast<FieldDecl>(Entity.
getDecl())->isBitField())
8703 S.CheckBitFieldInitialization(Kind.getLocation(),
8718 S.
Diag(
Loc, diag::err_reference_without_init)
8719 <<
T.getNonReferenceType();
8727 for (
const auto *FI : RD->
fields()) {
8728 if (FI->isUnnamedBitField())
8732 S.
Diag(
Loc, diag::note_value_initialization_here) << RD;
8737 for (
const auto &BI : RD->
bases()) {
8739 S.
Diag(
Loc, diag::note_value_initialization_here) << RD;
8774 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
8775 destDecl->getDeclKind() == Decl::CXXRecord &&
8776 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
8777 !fromDecl->hasDefinition() &&
8780 S.
Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
8810 S.
Diag(
Loc, diag::note_in_reference_temporary_list_initializer) <<
T;
8814 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
8817 assert(DiagnoseInitList.HadError() &&
8818 "Inconsistent init list check result.");
8833 if (Args.size() == 1) {
8834 auto *List = dyn_cast<InitListExpr>(Args[0]);
8835 if (List && List->getNumInits() == 1)
8836 OnlyArg = List->getInit(0);
8845 if (
Expr *Resolved =
8865 assert(Diagnosed &&
"couldn't find uninitialized reference to diagnose");
8868 S.
Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
8869 <<
SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
8872 S.
Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8873 << 1 << Entity.
getType() << Args[0]->getSourceRange();
8877 S.
Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
8880 S.
Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
8883 S.
Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
8886 S.
Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
8889 S.
Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
8892 S.
Diag(Kind.getLocation(),
8893 diag::err_array_init_incompat_wide_string_into_wchar);
8896 S.
Diag(Kind.getLocation(),
8897 diag::err_array_init_plain_string_into_char8_t);
8898 S.
Diag(Args.front()->getBeginLoc(),
8899 diag::note_array_init_plain_string_into_char8_t)
8903 S.
Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
8908 S.
Diag(Kind.getLocation(),
8910 ? diag::err_array_init_different_type
8911 : diag::err_array_init_non_constant_array))
8914 << Args[0]->getSourceRange();
8918 S.
Diag(Kind.getLocation(), diag::err_variable_object_no_init)
8919 << Args[0]->getSourceRange();
8932 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
8940 switch (FailedOverloadResult) {
8947 ? (S.
PDiag(diag::err_typecheck_ambiguous_condition)
8948 << OnlyArg->
getType() << DestType
8949 << Args[0]->getSourceRange())
8950 : (S.
PDiag(diag::err_ref_init_ambiguous)
8951 << DestType << OnlyArg->
getType()
8952 << Args[0]->getSourceRange())),
8960 diag::err_typecheck_nonviable_condition_incomplete,
8961 OnlyArg->
getType(), Args[0]->getSourceRange()))
8962 S.
Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
8964 << OnlyArg->
getType() << Args[0]->getSourceRange()
8976 S.
Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
8978 << (Msg !=
nullptr) << (Msg ? Msg->
getString() : StringRef())
8979 << Args[0]->getSourceRange();
8983 llvm_unreachable(
"Inconsistent overload resolution?");
8989 llvm_unreachable(
"Conversion did not fail!");
8994 if (isa<InitListExpr>(Args[0])) {
8995 S.
Diag(Kind.getLocation(),
8996 diag::err_lvalue_reference_bind_to_initlist)
8999 << Args[0]->getSourceRange();
9005 S.
Diag(Kind.getLocation(),
9007 ? diag::err_lvalue_reference_bind_to_temporary
9008 : diag::err_lvalue_reference_bind_to_unrelated)
9012 << Args[0]->getSourceRange();
9017 FieldDecl *BitField = Args[0]->getSourceBitField();
9018 S.
Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9021 << (BitField !=
nullptr)
9022 << Args[0]->getSourceRange();
9029 S.
Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9031 << Args[0]->getSourceRange();
9035 S.
Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9040 S.
Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9042 << Args[0]->getSourceRange();
9046 S.
Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9047 << DestType << Args[0]->getSourceRange();
9058 S.
Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9059 << NonRefType << SourceType << 1
9060 << Args[0]->getSourceRange();
9062 S.
Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9063 << NonRefType << SourceType << 0
9069 S.
Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9070 << NonRefType << SourceType << 2
9071 << Args[0]->getSourceRange();
9076 S.
Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9081 << Args[0]->getSourceRange();
9092 << Args[0]->getSourceRange();
9094 S.
Diag(Kind.getLocation(), PDiag);
9106 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9107 if (InitList && InitList->getNumInits() >= 1) {
9108 R =
SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9110 assert(Args.size() > 1 &&
"Expected multiple initializers!");
9111 R =
SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9115 if (Kind.isCStyleOrFunctionalCast())
9116 S.
Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9119 S.
Diag(Kind.getLocation(), diag::err_excess_initializers)
9125 S.
Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9126 << 0 << Entity.
getType() << Args[0]->getSourceRange();
9130 S.
Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9135 S.
Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9136 << (DestType->
isRecordType()) << DestType << Args[0]->getSourceRange();
9144 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9147 assert(Args.size() == 1 &&
9148 "List construction from other than 1 argument.");
9155 switch (FailedOverloadResult) {
9159 S.
PDiag(diag::err_ovl_ambiguous_init)
9160 << DestType << ArgsRange),
9177 if (
auto Inherited =
Constructor->getInheritedConstructor())
9178 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9180 S.
Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9181 << (InheritedFrom ? 2
9185 << 0 << Entity.
getType() << InheritedFrom;
9189 S.
Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9192 S.
Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9193 << (InheritedFrom ? 2
9197 << 1 << Entity.
getName() << InheritedFrom;
9199 diag::note_member_declared_at);
9202 S.
Diag(
Record->getOriginalDecl()->getLocation(),
9203 diag::note_previous_decl)
9212 S.
PDiag(diag::err_ovl_no_viable_function_in_init)
9213 << DestType << ArgsRange),
9222 S.
Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9223 << DestType << ArgsRange;
9224 llvm_unreachable(
"Inconsistent overload resolution?");
9232 S.
Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
9234 << DestType << ArgsRange;
9237 S.
Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9238 << DestType << (Msg !=
nullptr)
9239 << (Msg ? Msg->
getString() : StringRef()) << ArgsRange;
9250 diag::note_default_constructed_field)
9258 llvm_unreachable(
"Conversion did not fail!");
9270 S.
Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
9278 }
else if (
const auto *VD = dyn_cast_if_present<VarDecl>(Entity.
getDecl());
9279 VD && VD->isConstexpr()) {
9280 S.
Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
9283 S.
Diag(Kind.getLocation(), diag::err_default_init_const)
9290 diag::err_init_incomplete_type);
9306 S.
Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
9307 << Args[0]->getSourceRange();
9312 assert(Ovl ==
OR_Success &&
"Inconsistent overload resolution");
9315 diag::note_explicit_ctor_deduction_guide_here) <<
false;
9326 S.
Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
9331 PrintInitLocationNote(S, Entity);
9338 OS <<
"Failed sequence: ";
9341 OS <<
"too many initializers for reference";
9345 OS <<
"parenthesized list init for reference";
9349 OS <<
"array requires initializer list";
9353 OS <<
"address of unaddressable function was taken";
9357 OS <<
"array requires initializer list or string literal";
9361 OS <<
"array requires initializer list or wide string literal";
9365 OS <<
"narrow string into wide char array";
9369 OS <<
"wide string into char array";
9373 OS <<
"incompatible wide string into wide char array";
9377 OS <<
"plain string literal into char8_t array";
9381 OS <<
"u8 string literal into char array";
9385 OS <<
"array type mismatch";
9389 OS <<
"non-constant array initializer";
9393 OS <<
"address of overloaded function failed";
9397 OS <<
"overload resolution for reference initialization failed";
9401 OS <<
"non-const lvalue reference bound to temporary";
9405 OS <<
"non-const lvalue reference bound to bit-field";
9409 OS <<
"non-const lvalue reference bound to vector element";
9413 OS <<
"non-const lvalue reference bound to matrix element";
9417 OS <<
"non-const lvalue reference bound to unrelated type";
9421 OS <<
"rvalue reference bound to an lvalue";
9425 OS <<
"reference initialization drops qualifiers";
9429 OS <<
"reference with mismatching address space bound to temporary";
9433 OS <<
"reference initialization failed";
9437 OS <<
"conversion failed";
9441 OS <<
"conversion from property failed";
9445 OS <<
"too many initializers for scalar";
9449 OS <<
"parenthesized list init for reference";
9453 OS <<
"referencing binding to initializer list";
9457 OS <<
"initializer list for non-aggregate, non-scalar type";
9461 OS <<
"overloading failed for user-defined conversion";
9465 OS <<
"constructor overloading failed";
9469 OS <<
"default initialization of a const variable";
9473 OS <<
"initialization of incomplete type";
9477 OS <<
"list initialization checker failure";
9481 OS <<
"variable length array has an initializer";
9485 OS <<
"initializer expression isn't contextually valid";
9489 OS <<
"list constructor overloading failed";
9493 OS <<
"list copy initialization chose explicit constructor";
9497 OS <<
"parenthesized list initialization failed";
9501 OS <<
"designated initializer for non-aggregate type";
9509 OS <<
"Dependent sequence\n";
9513 OS <<
"Normal sequence: ";
9524 OS <<
"resolve address of overloaded function";
9528 OS <<
"derived-to-base (prvalue)";
9532 OS <<
"derived-to-base (xvalue)";
9536 OS <<
"derived-to-base (lvalue)";
9540 OS <<
"bind reference to lvalue";
9544 OS <<
"bind reference to a temporary";
9548 OS <<
"final copy in class direct-initialization";
9552 OS <<
"extraneous C++03 copy to temporary";
9556 OS <<
"user-defined conversion via " << *S->Function.Function;
9560 OS <<
"qualification conversion (prvalue)";
9564 OS <<
"qualification conversion (xvalue)";
9568 OS <<
"qualification conversion (lvalue)";
9572 OS <<
"function reference conversion";
9576 OS <<
"non-atomic-to-atomic conversion";
9580 OS <<
"implicit conversion sequence (";
9586 OS <<
"implicit conversion sequence with narrowing prohibited (";
9592 OS <<
"list aggregate initialization";
9596 OS <<
"unwrap reference initializer list";
9600 OS <<
"rewrap reference initializer list";
9604 OS <<
"constructor initialization";
9608 OS <<
"list initialization via constructor";
9612 OS <<
"zero initialization";
9616 OS <<
"C assignment";
9620 OS <<
"string initialization";
9624 OS <<
"Objective-C object conversion";
9628 OS <<
"indexing for array initialization loop";
9632 OS <<
"array initialization loop";
9636 OS <<
"array initialization";
9640 OS <<
"array initialization (GNU extension)";
9644 OS <<
"parenthesized array initialization";
9648 OS <<
"pass by indirect copy and restore";
9652 OS <<
"pass by indirect restore";
9656 OS <<
"Objective-C object retension";
9660 OS <<
"std::initializer_list from initializer list";
9664 OS <<
"list initialization from std::initializer_list";
9668 OS <<
"OpenCL sampler_t from integer constant";
9672 OS <<
"OpenCL opaque type from zero";
9675 OS <<
"initialization from a parenthesized list of values";
9679 OS <<
" [" << S->Type <<
']';
9693 const Expr *PostInit) {
9709 auto MakeDiag = [&](
bool IsConstRef,
unsigned DefaultDiagID,
9710 unsigned ConstRefDiagID,
unsigned WarnDiagID) {
9713 if (L.CPlusPlus11 && !L.HLSL &&
9715 DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
9717 DiagID = WarnDiagID;
9737 MakeDiag(
T != EntityType, diag::ext_init_list_type_narrowing,
9738 diag::ext_init_list_type_narrowing_const_reference,
9739 diag::warn_init_list_type_narrowing)
9741 <<
T.getLocalUnqualifiedType();
9748 diag::ext_init_list_constant_narrowing,
9749 diag::ext_init_list_constant_narrowing_const_reference,
9750 diag::warn_init_list_constant_narrowing)
9759 diag::ext_init_list_variable_narrowing,
9760 diag::ext_init_list_variable_narrowing_const_reference,
9761 diag::warn_init_list_variable_narrowing)
9769 llvm::raw_svector_ostream OS(StaticCast);
9770 OS <<
"static_cast<";
9777 OS << *TT->getDecl();
9786 S.
Diag(PostInit->
getBeginLoc(), diag::note_init_list_narrowing_silence)
9797 Init->IgnoreParenImpCasts(), ToType,
false,
9798 Sema::AllowedExplicit::None,
9814 S.
Diag(
Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)
9815 <<
Value.getAsString(S.
Context, PreNarrowingType) << ToType;
9820 S.
Diag(
Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)
9821 << ToType << FromType;
9831 llvm_unreachable(
"unhandled case in switch");
9843 for (
unsigned I = 0, N = SE->
getLength(); I != N; ++I) {
9848 diag::err_c23_constexpr_init_not_representable)
9861 if (
Init.isInvalid())
9865 assert(InitE &&
"No initialization expression");
9870 return !
Seq.Failed();
9877 bool TopLevelOfInitList,
9878 bool AllowExplicit) {
9879 if (
Init.isInvalid())
9883 assert(InitE &&
"No initialization expression?");
9893 const bool ShouldTrackCopy =
9895 if (ShouldTrackCopy) {
9897 Seq.SetOverloadFailure(
9903 const auto LastStep =
Seq.step_end() - 1;
9904 assert(LastStep->Kind ==
9908 llvm::find_if(
Seq.getFailedCandidateSet(),
9910 return Candidate.Viable &&
9911 Candidate.Function == Function &&
9912 Candidate.Conversions.size() > 0;
9914 if (Candidate !=
Seq.getFailedCandidateSet().end() &&
9916 Candidate->
Viable =
false;
9920 Function->getParamDecl(0)->getType());
9928 if (ShouldTrackCopy)
9937 auto NotSpecialization = [&] (
const CXXRecordDecl *Candidate) {
9938 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
9941 return !(NotSpecialization(RD) && RD->
forallBases(NotSpecialization));
9947 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
9949 assert(DeducedTST &&
"not a deduced template specialization type");
9960 if (
auto *
AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(
9962 DiagCompat(Kind.getLocation(), diag_compat::ctad_for_alias_templates);
9965 ->getUnderlyingType()
9966 .getCanonicalType();
9970 if (
const auto *TST =
9972 Template = dyn_cast_or_null<ClassTemplateDecl>(
9973 TST->getTemplateName().getAsTemplateDecl());
9974 }
else if (
const auto *RT = UnderlyingType->getAs<
RecordType>()) {
9978 if (
const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(
9979 RT->getOriginalDecl()))
9980 Template = CTSD->getSpecializedTemplate();
9985 Diag(Kind.getLocation(),
9986 diag::err_deduced_non_class_or_alias_template_specialization_type)
9996 diag::warn_cxx14_compat_class_template_argument_deduction)
10024 ? dyn_cast<InitListExpr>(Inits[0])
10040 bool AllowExplicit = !Kind.isCopyInit() ||
ListInit;
10046 bool OnlyListConstructors,
10047 bool AllowAggregateDeductionCandidate) {
10053 if (!AllowExplicit) {
10060 if (GD->getMinRequiredArguments() > 1 ||
10061 (GD->getNumParams() == 0 && !GD->isVariadic()))
10071 if (!AllowAggregateDeductionCandidate &&
10091 for (
auto [I,
E] : llvm::enumerate(Inits)) {
10092 if (
auto *DI = dyn_cast<DesignatedInitExpr>(
E))
10093 TmpInits[I] = DI->getInit();
10099 TD, FoundDecl,
nullptr, TmpInits, Candidates,
10101 false, AllowExplicit, ADLCallKind::NotADL,
10102 {}, AllowAggregateDeductionCandidate);
10106 false, AllowExplicit);
10110 bool FoundDeductionGuide =
false;
10112 auto TryToResolveOverload =
10115 bool HasAnyDeductionGuide =
false;
10119 while (Pattern->getInstantiatedFromMemberTemplate()) {
10120 if (Pattern->isMemberSpecialization())
10122 Pattern = Pattern->getInstantiatedFromMemberTemplate();
10125 auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl());
10131 InitListChecker CheckInitList(*
this, Entity,
ListInit, Ty, ElementTypes);
10132 if (!CheckInitList.HadError()) {
10141 for (
int I = 0,
E =
ListInit->getNumInits();
10142 I <
E && !isa<PackExpansionType>(ElementTypes[I]); ++I)
10143 if (ElementTypes[I]->isArrayType()) {
10144 if (isa<InitListExpr, DesignatedInitExpr>(
ListInit->getInit(I)))
10146 else if (isa<StringLiteral>(
10147 ListInit->getInit(I)->IgnoreParenImpCasts()))
10154 LookupTemplateDecl, ElementTypes,
10158 OnlyListConstructors,
10160 HasAnyDeductionGuide =
true;
10165 for (
auto I = Guides.
begin(),
E = Guides.
end(); I !=
E; ++I) {
10170 auto *TD = dyn_cast<FunctionTemplateDecl>(
D);
10171 auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10176 if (!GD->isImplicit())
10177 HasAnyDeductionGuide =
true;
10179 addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10194 }
else if (Inits.size()) {
10199 Inits, Inits.back()->getEndLoc());
10200 SynthesizeAggrGuide(&TempListInit);
10204 FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10214 bool TryListConstructors =
true;
10220 auto *FD = dyn_cast<FunctionDecl>(
D->getUnderlyingDecl());
10221 if (FD && FD->getMinRequiredArguments() == 0) {
10222 TryListConstructors =
false;
10226 }
else if (
ListInit->getNumInits() == 1) {
10234 if (!isa<InitListExpr>(
E) && RD &&
10237 TryListConstructors =
false;
10240 if (TryListConstructors)
10241 Result = TryToResolveOverload(
true);
10250 Result = TryToResolveOverload(
false);
10259 Kind.getLocation(),
10260 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
10267 cast<ClassTemplateDecl>(
Template)->getTemplatedDecl();
10272 Kind.getLocation(),
10273 PDiag(
Complete ? diag::err_deduced_class_template_ctor_no_viable
10274 : diag::err_deduced_class_template_incomplete)
10284 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
10294 if (Kind.isCopyInit() &&
ListInit &&
10295 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
10296 bool IsDeductionGuide = !Best->Function->isImplicit();
10297 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
10299 Diag(Best->Function->getLocation(),
10300 diag::note_explicit_ctor_deduction_guide_here)
10301 << IsDeductionGuide;
10319 diag::warn_cxx14_compat_class_template_argument_deduction)
10324 if (!FoundDeductionGuide) {
10326 diag::warn_ctad_maybe_unsupported)
10328 Diag(
Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
Defines the clang::ASTContext interface.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
static bool isRValueRef(QualType ParamType)
Defines the clang::Expr interface and subclasses for C++ expressions.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
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.
static void CheckForNullPointerDereference(Sema &S, Expr *E)
This file declares semantic analysis for HLSL constructs.
static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E)
Tries to get a FunctionDecl out of E.
static void updateStringLiteralType(Expr *E, QualType Ty)
Update the type of a string literal, including any surrounding parentheses, to match the type of the ...
static void updateGNUCompoundLiteralRValue(Expr *E)
Fix a compound literal initializing an array so it's correctly marked as an rvalue.
static bool initializingConstexprVariable(const InitializedEntity &Entity)
static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity, SourceRange Braces)
Warn that Entity was of scalar type and was initialized by a single-element braced initializer list.
static bool shouldDestroyEntity(const InitializedEntity &Entity)
Whether the given entity, when initialized with an object created for that initialization,...
static SourceLocation getInitializationLoc(const InitializedEntity &Entity, Expr *Initializer)
Get the location at which initialization diagnostics should appear.
static bool hasAnyDesignatedInits(const InitListExpr *IL)
static bool tryObjCWritebackConversion(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity, Expr *Initializer)
static DesignatedInitExpr * CloneDesignatedInitExpr(Sema &SemaRef, DesignatedInitExpr *DIE)
static ExprResult CopyObject(Sema &S, QualType T, const InitializedEntity &Entity, ExprResult CurInit, bool IsExtraneousCopy)
Make a (potentially elidable) temporary copy of the object provided by the given initializer by calli...
static void TryOrBuildParenListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args, InitializationSequence &Sequence, bool VerifyOnly, ExprResult *Result=nullptr)
static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, Sema &S, const InitializedEntity &Entity, bool CheckC23ConstexprInit=false)
static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, bool IsReturnStmt)
Provide warnings when std::move is used on construction.
static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE, Sema &SemaRef, QualType &TT)
static void CheckCXX98CompatAccessibleCopy(Sema &S, const InitializedEntity &Entity, Expr *CurInitExpr)
Check whether elidable copy construction for binding a reference to a temporary would have succeeded ...
static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, ClassTemplateDecl *CTD)
Determine whether RD is, or is derived from, a specialization of CTD.
static bool canInitializeArrayWithEmbedDataString(ArrayRef< Expr * > ExprList, const InitializedEntity &Entity, ASTContext &Context)
static bool TryInitializerListConstruction(Sema &S, InitListExpr *List, QualType DestType, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid)
When initializing from init list via constructor, handle initialization of an object of type std::ini...
static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT, ASTContext &Context)
Check whether the array of type AT can be initialized by the Init expression by means of string initi...
static void TryArrayCopy(Sema &S, const InitializationKind &Kind, const InitializedEntity &Entity, Expr *Initializer, QualType DestType, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid)
Initialize an array from another array.
static bool isInitializedStructuredList(const InitListExpr *StructuredList)
@ SIF_PlainStringIntoUTF8Char
@ SIF_IncompatWideStringIntoWideChar
@ SIF_UTF8StringIntoPlainChar
@ SIF_NarrowStringIntoWideChar
static void TryDefaultInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitializationSequence &Sequence)
Attempt default initialization (C++ [dcl.init]p6).
static bool TryOCLSamplerInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
static bool maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity)
Tries to add a zero initializer. Returns true if that worked.
static ExprResult CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value)
Check that the given Index expression is a valid array designator value.
static bool canPerformArrayCopy(const InitializedEntity &Entity)
Determine whether we can perform an elementwise array copy for this kind of entity.
static void TryReferenceInitializationCore(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, QualType cv1T1, QualType T1, Qualifiers T1Quals, QualType cv2T2, QualType T2, Qualifiers T2Quals, InitializationSequence &Sequence, bool TopLevelOfInitList)
Reference initialization without resolving overloaded functions.
static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType, QualType ToType, Expr *Init)
static void ExpandAnonymousFieldDesignator(Sema &SemaRef, DesignatedInitExpr *DIE, unsigned DesigIdx, IndirectFieldDecl *IndirectField)
Expand a field designator that refers to a member of an anonymous struct or union into a series of fi...
static void TryValueInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitializationSequence &Sequence, InitListExpr *InitList=nullptr)
Attempt value initialization (C++ [dcl.init]p7).
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
static OverloadingResult ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, MultiExprArg Args, OverloadCandidateSet &CandidateSet, QualType DestType, DeclContext::lookup_result Ctors, OverloadCandidateSet::iterator &Best, bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors, bool IsListInit, bool RequireActualConstructor, bool SecondStepOfCopyInit=false)
static AssignmentAction getAssignmentAction(const InitializedEntity &Entity, bool Diagnose=false)
static void TryListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitListExpr *InitList, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid)
Attempt list initialization (C++0x [dcl.init.list])
static void TryStringLiteralInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence)
Attempt character array initialization from a string literal (C++ [dcl.init.string],...
static bool checkDestructorReference(QualType ElementType, SourceLocation Loc, Sema &SemaRef)
Check if the type of a class element has an accessible destructor, and marks it referenced.
static void TryReferenceInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt reference initialization (C++0x [dcl.init.ref])
static void DiagnoseNarrowingInInitList(Sema &S, const ImplicitConversionSequence &ICS, QualType PreNarrowingType, QualType EntityType, const Expr *PostInit)
static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest, const ArrayType *Source)
Determine whether we have compatible array types for the purposes of GNU by-copy array initialization...
static bool isExplicitTemporary(const InitializedEntity &Entity, const InitializationKind &Kind, unsigned NumArgs)
Returns true if the parameters describe a constructor initialization of an explicit temporary object,...
static bool isNonReferenceableGLValue(Expr *E)
Determine whether an expression is a non-referenceable glvalue (one to which a reference can never bi...
static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
static bool IsWideCharCompatible(QualType T, ASTContext &Context)
Check whether T is compatible with a wide character type (wchar_t, char16_t or char32_t).
static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, InitListExpr *InitList)
static OverloadingResult TryRefInitWithConversionFunction(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, bool AllowRValues, bool IsLValueRef, InitializationSequence &Sequence)
Try a reference initialization that involves calling a conversion function.
void emitUninitializedExplicitInitFields(Sema &S, const RecordDecl *R)
static void TryConstructorInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType DestType, QualType DestArrayType, InitializationSequence &Sequence, bool IsListInit=false, bool IsInitListCopy=false)
Attempt initialization by constructor (C++ [dcl.init]), which enumerates the constructors of the init...
static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, Expr *op)
Emit notes associated with an initialization that failed due to a "simple" conversion failure.
static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity)
Determine whether Entity is an entity for which it is idiomatic to elide the braces in aggregate init...
static void MaybeProduceObjCObject(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity)
static void checkIndirectCopyRestoreSource(Sema &S, Expr *src)
Check whether the given expression is a valid operand for an indirect copy/restore.
static bool shouldBindAsTemporary(const InitializedEntity &Entity)
Whether we should bind a created object as a temporary when initializing the given entity.
static void TryConstructorOrParenListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType DestType, InitializationSequence &Sequence, bool IsAggrListInit)
Attempt to initialize an object of a class type either by direct-initialization, or by copy-initializ...
static bool IsZeroInitializer(const Expr *Init, ASTContext &Ctx)
static const FieldDecl * getConstField(const RecordDecl *RD)
static bool ResolveOverloadedFunctionForReferenceBinding(Sema &S, Expr *Initializer, QualType &SourceType, QualType &UnqualifiedSourceType, QualType UnqualifiedTargetType, InitializationSequence &Sequence)
InvalidICRKind
The non-zero enum values here are indexes into diagnostic alternatives.
static ExprResult PerformConstructorInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, const InitializationSequence::Step &Step, bool &ConstructorInitRequiresZeroInit, bool IsListInitialization, bool IsStdInitListInitialization, SourceLocation LBraceLoc, SourceLocation RBraceLoc)
static void TryReferenceListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitListExpr *InitList, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid)
Attempt list initialization of a reference.
static bool hasCopyOrMoveCtorParam(ASTContext &Ctx, const ConstructorInfo &Info)
Determine if the constructor has the signature of a copy or move constructor for the type T of the cl...
static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, QualType T)
Somewhere within T there is an uninitialized reference subobject.
static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, bool isAddressOf, bool &isWeakAccess)
Determines whether this expression is an acceptable ICR source.
This file declares semantic analysis for Objective-C.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
__device__ __2f16 float __ockl_bool s
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
bool isNullPointer() const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
unsigned getIntWidth(QualType T) const
DeclarationNameTable DeclarationNames
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
CanQualType getCanonicalTagType(const TagDecl *TD) const
QualType getWideCharType() const
Return the type of wide characters.
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Represents a loop initializing the elements of an array.
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
QualType getElementType() const
This class is used for builtin types like 'int'.
Represents a base class of a C++ class.
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
QualType getType() const
Retrieves the type of the base class.
Represents a call to a C++ constructor.
Expr * getArg(unsigned Arg)
Return the specified argument.
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Represents a C++ constructor within a class.
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Represents a C++ conversion function within a class.
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Represents a C++ deduction guide declaration.
Represents a C++ destructor within a class.
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Represents a C++ struct/union/class.
bool hasUninitializedReferenceMember() const
Whether this class or any of its subobjects has any members of reference type which would make value-...
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
unsigned getNumBases() const
Retrieves the number of base classes of this class.
llvm::iterator_range< base_class_iterator > base_class_range
llvm::iterator_range< base_class_const_iterator > base_class_const_range
bool forallBases(ForallBasesCallback BaseMatches) const
Determines if the given callback holds for all the direct or indirect base classes of this type.
An expression "T()" which creates an rvalue of a non-class type T.
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
static CXXTemporaryObjectExpr * Create(const ASTContext &Ctx, CXXConstructorDecl *Cons, QualType Ty, TypeSourceInfo *TSI, ArrayRef< Expr * > Args, SourceRange ParenOrBraceRange, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization)
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
SourceLocation getBeginLoc() const
bool isCallToStdMove() const
SourceLocation getRParenLoc() const
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
SourceLocation getBegin() const
Declaration of a class template.
void setExprNeedsCleanups(bool SideEffects)
Complex values, per C99 6.2.5p11.
QualType getElementType() const
ConditionalOperator - The ?: ternary operator.
Represents the canonical version of C arrays with a specified constant size.
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
virtual bool ValidateCandidate(const TypoCorrection &candidate)
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
virtual std::unique_ptr< CorrectionCandidateCallback > clone()=0
Clone this CorrectionCandidateCallback.
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
The results of name lookup within a DeclContext.
decl_iterator - Iterates through the declarations stored within this context.
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
A reference to a declared variable, function, enum, etc.
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Decl - This represents one declaration (or definition), e.g.
SourceLocation getEndLoc() const LLVM_READONLY
static bool isFlexibleArrayMemberLike(const ASTContext &Context, const Decl *D, QualType Ty, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution)
Whether it resembles a flexible array member.
ASTContext & getASTContext() const LLVM_READONLY
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
bool isInvalidDecl() const
SourceLocation getLocation() const
DeclContext * getDeclContext()
SourceLocation getBeginLoc() const LLVM_READONLY
The name of a declaration.
SourceLocation getBeginLoc() const LLVM_READONLY
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Represents a single C99 designator.
SourceLocation getBeginLoc() const LLVM_READONLY
SourceLocation getFieldLoc() const
SourceLocation getDotLoc() const
Represents a C99 designated initializer expression.
bool isDirectInit() const
Whether this designated initializer should result in direct-initialization of the designated subobjec...
Expr * getArrayRangeEnd(const Designator &D) const
Expr * getSubExpr(unsigned Idx) const
bool usesGNUSyntax() const
Determines whether this designated initializer used the deprecated GNU syntax for designated initiali...
Expr * getArrayRangeStart(const Designator &D) const
void ExpandDesignator(const ASTContext &C, unsigned Idx, const Designator *First, const Designator *Last)
Replaces the designator at index Idx with the series of designators in [First, Last).
MutableArrayRef< Designator > designators()
Expr * getArrayIndex(const Designator &D) const
Designator * getDesignator(unsigned Idx)
Expr * getInit() const
Retrieve the initializer value.
unsigned size() const
Returns the number of designators in this initializer.
SourceLocation getBeginLoc() const LLVM_READONLY
SourceLocation getEndLoc() const LLVM_READONLY
SourceLocation getEqualOrColonLoc() const
Retrieve the location of the '=' that precedes the initializer value itself, if present.
unsigned getNumSubExprs() const
Retrieve the total number of subexpressions in this designated initializer expression,...
static DesignatedInitExpr * Create(const ASTContext &C, ArrayRef< Designator > Designators, ArrayRef< Expr * > IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init)
InitListExpr * getUpdater() const
Designation - Represent a full designation, which is a sequence of designators.
const Designator & getDesignator(unsigned Idx) const
unsigned getNumDesignators() const
Designator - A designator in a C99 designated initializer.
static Designator CreateFieldDesignator(const IdentifierInfo *FieldName, SourceLocation DotLoc, SourceLocation FieldLoc)
Creates a field designator.
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Represents a reference to #emded data.
StringLiteral * getDataStringLiteral() const
EmbedDataStorage * getData() const
SourceLocation getLocation() const
size_t getDataElementCount() const
RAII object that enters a new expression evaluation context.
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
The return type of classify().
This represents one expression.
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
bool isValueDependent() const
Determines whether the value of this expression depends on.
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
bool refersToVectorElement() const
Returns whether this expression refers to a vector element.
bool isTypeDependent() const
Determines whether the type of this expression depends on.
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...
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
bool refersToMatrixElement() const
Returns whether this expression refers to a matrix element.
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
ExtVectorType - Extended vector type.
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
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.
Represents a function declaration or definition.
const ParmVarDecl * getParamDecl(unsigned i) const
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
QualType getReturnType() const
bool isDeleted() const
Whether this function has been deleted.
bool isDefaulted() const
Whether this function is defaulted.
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
One of these records is kept for each identifier that is lexed.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
@ StaticObjectArgumentConversion
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
static ImplicitConversionSequence getNullptrToBool(QualType SourceType, QualType DestType, bool NeedLValToRVal)
Form an "implicit" conversion sequence from nullptr_t to bool, for a direct-initialization of a bool ...
Represents an implicitly-generated value initialization of an object of a given type.
Represents a C array with an unspecified size.
Represents a field injected from an anonymous union/struct into the parent scope.
chain_iterator chain_end() const
chain_iterator chain_begin() const
ArrayRef< NamedDecl * >::const_iterator chain_iterator
Describes an C or C++ initializer list.
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
void setSyntacticForm(InitListExpr *Init)
void markError()
Mark the semantic form of the InitListExpr as error when the semantic analysis fails.
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
unsigned getNumInits() const
SourceLocation getBeginLoc() const LLVM_READONLY
void setInit(unsigned Init, Expr *expr)
SourceLocation getLBraceLoc() const
Expr * updateInit(const ASTContext &C, unsigned Init, Expr *expr)
Updates the initializer at index Init with the new expression expr, and returns the old expression at...
void setArrayFiller(Expr *filler)
InitListExpr * getSyntacticForm() const
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
SourceLocation getRBraceLoc() const
const Expr * getInit(unsigned Init) const
bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const
Is this the zero initializer {0} in a language which considers it idiomatic?
SourceLocation getEndLoc() const LLVM_READONLY
void setInitializedFieldInUnion(FieldDecl *FD)
bool isSyntacticForm() const
ArrayRef< Expr * > inits()
void setRBraceLoc(SourceLocation Loc)
void sawArrayRangeDesignator(bool ARD=true)
Expr ** getInits()
Retrieve the set of initializers.
Describes the kind of initialization being performed, along with location information for tokens rela...
@ IK_DirectList
Direct list-initialization.
@ IK_Value
Value initialization.
@ IK_Direct
Direct initialization.
@ IK_Copy
Copy initialization.
@ IK_Default
Default initialization.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
static InitializationKind CreateValue(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool isImplicit=false)
Create a value initialization.
A single step in the initialization sequence.
StepKind Kind
The kind of conversion or initialization step we are taking.
InitListExpr * WrappingSyntacticList
When Kind = SK_RewrapInitList, the syntactic form of the wrapping list.
ImplicitConversionSequence * ICS
When Kind = SK_ConversionSequence, the implicit conversion sequence.
struct F Function
When Kind == SK_ResolvedOverloadedFunction or Kind == SK_UserConversion, the function that the expres...
Describes the sequence of initializations required to initialize a given object or reference with a s...
step_iterator step_begin() const
void AddListInitializationStep(QualType T)
Add a list-initialization step.
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
void AddStringInitStep(QualType T)
Add a string init step.
void AddStdInitializerListConstructionStep(QualType T)
Add a step to construct a std::initializer_list object from an initializer list.
void AddConstructorInitializationStep(DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, bool HadMultipleCandidates, bool FromInitList, bool AsInitList)
Add a constructor-initialization step.
@ SK_StdInitializerListConstructorCall
Perform initialization via a constructor taking a single std::initializer_list argument.
@ SK_AtomicConversion
Perform a conversion adding _Atomic to a type.
@ SK_ObjCObjectConversion
An initialization that "converts" an Objective-C object (not a point to an object) to another Objecti...
@ SK_GNUArrayInit
Array initialization (from an array rvalue) as a GNU extension.
@ SK_CastDerivedToBaseLValue
Perform a derived-to-base cast, producing an lvalue.
@ SK_ProduceObjCObject
Produce an Objective-C object pointer.
@ SK_FunctionReferenceConversion
Perform a function reference conversion, see [dcl.init.ref]p4.
@ SK_BindReference
Reference binding to an lvalue.
@ SK_ArrayLoopInit
Array initialization by elementwise copy.
@ SK_ConstructorInitialization
Perform initialization via a constructor.
@ SK_OCLSamplerInit
Initialize an OpenCL sampler from an integer.
@ SK_StringInit
Initialization by string.
@ SK_ZeroInitialization
Zero-initialize the object.
@ SK_CastDerivedToBaseXValue
Perform a derived-to-base cast, producing an xvalue.
@ SK_QualificationConversionXValue
Perform a qualification conversion, producing an xvalue.
@ SK_UserConversion
Perform a user-defined conversion, either via a conversion function or via a constructor.
@ SK_CastDerivedToBasePRValue
Perform a derived-to-base cast, producing an rvalue.
@ SK_BindReferenceToTemporary
Reference binding to a temporary.
@ SK_PassByIndirectRestore
Pass an object by indirect restore.
@ SK_ParenthesizedArrayInit
Array initialization from a parenthesized initializer list.
@ SK_ParenthesizedListInit
Initialize an aggreagate with parenthesized list of values.
@ SK_ArrayInit
Array initialization (from an array rvalue).
@ SK_ExtraneousCopyToTemporary
An optional copy of a temporary object to another temporary object, which is permitted (but not requi...
@ SK_ArrayLoopIndex
Array indexing for initialization by elementwise copy.
@ SK_ConversionSequenceNoNarrowing
Perform an implicit conversion sequence without narrowing.
@ SK_RewrapInitList
Rewrap the single-element initializer list for a reference.
@ SK_CAssignment
C assignment.
@ SK_ConstructorInitializationFromList
Perform initialization via a constructor, taking arguments from a single InitListExpr.
@ SK_PassByIndirectCopyRestore
Pass an object by indirect copy-and-restore.
@ SK_ResolveAddressOfOverloadedFunction
Resolve the address of an overloaded function to a specific function declaration.
@ SK_UnwrapInitList
Unwrap the single-element initializer list for a reference.
@ SK_FinalCopy
Direct-initialization from a reference-related object in the final stage of class copy-initialization...
@ SK_QualificationConversionLValue
Perform a qualification conversion, producing an lvalue.
@ SK_StdInitializerList
Construct a std::initializer_list from an initializer list.
@ SK_QualificationConversionPRValue
Perform a qualification conversion, producing a prvalue.
@ SK_ConversionSequence
Perform an implicit conversion sequence.
@ SK_ListInitialization
Perform list-initialization without a constructor.
@ SK_OCLZeroOpaqueType
Initialize an opaque OpenCL type (event_t, queue_t, etc.) with zero.
void AddUserConversionStep(FunctionDecl *Function, DeclAccessPair FoundDecl, QualType T, bool HadMultipleCandidates)
Add a new step invoking a conversion function, which is either a constructor or a conversion function...
void SetZeroInitializationFixit(const std::string &Fixit, SourceLocation L)
Call for initializations are invalid but that would be valid zero initialzations if Fixit was applied...
InitializationSequence(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, bool TopLevelOfInitList=false, bool TreatUnavailableAsInvalid=true)
Try to perform initialization of the given entity, creating a record of the steps required to perform...
void AddQualificationConversionStep(QualType Ty, ExprValueKind Category)
Add a new step that performs a qualification conversion to the given type.
void AddFunctionReferenceConversionStep(QualType Ty)
Add a new step that performs a function reference conversion to the given type.
~InitializationSequence()
void AddDerivedToBaseCastStep(QualType BaseType, ExprValueKind Category)
Add a new step in the initialization that performs a derived-to- base cast.
FailureKind getFailureKind() const
Determine why initialization failed.
void InitializeFrom(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
void AddParenthesizedListInitStep(QualType T)
void SetFailed(FailureKind Failure)
Note that this initialization sequence failed.
bool isAmbiguous() const
Determine whether this initialization failed due to an ambiguity.
void AddUnwrapInitListInitStep(InitListExpr *Syntactic)
Only used when initializing structured bindings from an array with direct-list-initialization.
void AddOCLZeroOpaqueTypeStep(QualType T)
Add a step to initialzie an OpenCL opaque type (event_t, queue_t, etc.) from a zero constant.
void AddFinalCopy(QualType T)
Add a new step that makes a copy of the input to an object of the given type, as the final step in cl...
OverloadingResult getFailedOverloadResult() const
Get the overloading result, for when the initialization sequence failed due to a bad overload.
void setSequenceKind(enum SequenceKind SK)
Set the kind of sequence computed.
void AddObjCObjectConversionStep(QualType T)
Add an Objective-C object conversion step, which is always a no-op.
void SetOverloadFailure(FailureKind Failure, OverloadingResult Result)
Note that this initialization sequence failed due to failed overload resolution.
step_iterator step_end() const
void AddParenthesizedArrayInitStep(QualType T)
Add a parenthesized array initialization step.
void AddExtraneousCopyToTemporary(QualType T)
Add a new step that makes an extraneous copy of the input to a temporary of the same class type.
void setIncompleteTypeFailure(QualType IncompleteType)
Note that this initialization sequence failed due to an incomplete type.
void AddOCLSamplerInitStep(QualType T)
Add a step to initialize an OpenCL sampler from an integer constant.
void AddCAssignmentStep(QualType T)
Add a C assignment step.
void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy)
Add a step to pass an object by indirect copy-restore.
void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic)
Add steps to unwrap a initializer list for a reference around a single element and rewrap it at the e...
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args)
Diagnose an potentially-invalid initialization sequence.
bool Failed() const
Determine whether the initialization sequence is invalid.
void AddAtomicConversionStep(QualType Ty)
Add a new step that performs conversion from non-atomic to atomic type.
void dump() const
Dump a representation of this initialization sequence to standard error, for debugging purposes.
void AddConversionSequenceStep(const ImplicitConversionSequence &ICS, QualType T, bool TopLevelOfInitList=false)
Add a new step that applies an implicit conversion sequence.
void AddZeroInitializationStep(QualType T)
Add a zero-initialization step.
void AddProduceObjCObjectStep(QualType T)
Add a step to "produce" an Objective-C object (by retaining it).
enum SequenceKind getKind() const
Determine the kind of initialization sequence computed.
SequenceKind
Describes the kind of initialization sequence computed.
@ NormalSequence
A normal sequence.
@ FailedSequence
A failed initialization sequence.
@ DependentSequence
A dependent initialization, which could not be type-checked due to the presence of dependent types or...
void AddReferenceBindingStep(QualType T, bool BindingTemporary)
Add a new step binding a reference to an object.
FailureKind
Describes why initialization failed.
@ FK_UserConversionOverloadFailed
Overloading for a user-defined conversion failed.
@ FK_NarrowStringIntoWideCharArray
Initializing a wide char array with narrow string literal.
@ FK_ArrayTypeMismatch
Array type mismatch.
@ FK_ParenthesizedListInitForReference
Reference initialized from a parenthesized initializer list.
@ FK_NonConstLValueReferenceBindingToVectorElement
Non-const lvalue reference binding to a vector element.
@ FK_ReferenceInitDropsQualifiers
Reference binding drops qualifiers.
@ FK_InitListBadDestinationType
Initialization of some unused destination type with an initializer list.
@ FK_ConversionFromPropertyFailed
Implicit conversion failed.
@ FK_NonConstLValueReferenceBindingToUnrelated
Non-const lvalue reference binding to an lvalue of unrelated type.
@ FK_ListConstructorOverloadFailed
Overloading for list-initialization by constructor failed.
@ FK_ReferenceInitFailed
Reference binding failed.
@ FK_DesignatedInitForNonAggregate
@ FK_ArrayNeedsInitList
Array must be initialized with an initializer list.
@ FK_PlainStringIntoUTF8Char
Initializing char8_t array with plain string literal.
@ FK_NonConstantArrayInit
Non-constant array initializer.
@ FK_NonConstLValueReferenceBindingToTemporary
Non-const lvalue reference binding to a temporary.
@ FK_ConversionFailed
Implicit conversion failed.
@ FK_ArrayNeedsInitListOrStringLiteral
Array must be initialized with an initializer list or a string literal.
@ FK_ParenthesizedListInitForScalar
Scalar initialized from a parenthesized initializer list.
@ FK_PlaceholderType
Initializer has a placeholder type which cannot be resolved by initialization.
@ FK_IncompatWideStringIntoWideChar
Initializing wide char array with incompatible wide string literal.
@ FK_NonConstLValueReferenceBindingToMatrixElement
Non-const lvalue reference binding to a matrix element.
@ FK_TooManyInitsForReference
Too many initializers provided for a reference.
@ FK_NonConstLValueReferenceBindingToBitfield
Non-const lvalue reference binding to a bit-field.
@ FK_ReferenceAddrspaceMismatchTemporary
Reference with mismatching address space binding to temporary.
@ FK_ListInitializationFailed
List initialization failed at some point.
@ FK_TooManyInitsForScalar
Too many initializers for scalar.
@ FK_AddressOfOverloadFailed
Cannot resolve the address of an overloaded function.
@ FK_VariableLengthArrayHasInitializer
Variable-length array must not have an initializer.
@ FK_ArrayNeedsInitListOrWideStringLiteral
Array must be initialized with an initializer list or a wide string literal.
@ FK_RValueReferenceBindingToLValue
Rvalue reference binding to an lvalue.
@ FK_Incomplete
Initialization of an incomplete type.
@ FK_WideStringIntoCharArray
Initializing char array with wide string literal.
@ FK_ExplicitConstructor
List-copy-initialization chose an explicit constructor.
@ FK_ReferenceInitOverloadFailed
Overloading due to reference initialization failed.
@ FK_ConstructorOverloadFailed
Overloading for initialization by constructor failed.
@ FK_ReferenceBindingToInitList
Reference initialization from an initializer list.
@ FK_DefaultInitOfConst
Default-initialization of a 'const' object.
@ FK_ParenthesizedListInitFailed
Parenthesized list initialization failed at some point.
@ FK_AddressOfUnaddressableFunction
Trying to take the address of a function that doesn't support having its address taken.
@ FK_UTF8StringIntoPlainChar
Initializing char array with UTF-8 string literal.
bool isDirectReferenceBinding() const
Determine whether this initialization is a direct reference binding (C++ [dcl.init....
void AddArrayInitLoopStep(QualType T, QualType EltTy)
Add an array initialization loop step.
void AddAddressOverloadResolutionStep(FunctionDecl *Function, DeclAccessPair Found, bool HadMultipleCandidates)
Add a new step in the initialization that resolves the address of an overloaded function to a specifi...
void AddArrayInitStep(QualType T, bool IsGNUExtension)
Add an array initialization step.
bool isConstructorInitialization() const
Determine whether this initialization is direct call to a constructor.
SmallVectorImpl< Step >::const_iterator step_iterator
OverloadCandidateSet & getFailedCandidateSet()
Retrieve a reference to the candidate set when overload resolution fails.
Describes an entity that is being initialized.
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr, bool Implicit=false)
Create the initialization entity for a member subobject.
VD Variable
When Kind == EK_Variable, EK_Member, EK_Binding, or EK_TemplateParameter, the variable,...
EntityKind getKind() const
Determine the kind of initialization.
DeclarationName getName() const
Retrieve the name of the entity being initialized.
QualType getType() const
Retrieve type being initialized.
ValueDecl * getDecl() const
Retrieve the variable, parameter, or field being initialized.
bool isImplicitMemberInitializer() const
Is this the implicit initialization of a member of a class from a defaulted constructor?
const InitializedEntity * getParent() const
Retrieve the parent of the entity being initialized, when the initialization itself is occurring with...
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
bool isParameterConsumed() const
Determine whether this initialization consumes the parameter.
static InitializedEntity InitializeElement(ASTContext &Context, unsigned Index, const InitializedEntity &Parent)
Create the initialization entity for an array element.
unsigned getElementIndex() const
If this is an array, vector, or complex number element, get the element's index.
void setElementIndex(unsigned Index)
If this is already the initializer for an array or vector element, sets the element index.
SourceLocation getCaptureLoc() const
Determine the location of the capture when initializing field from a captured variable in a lambda.
bool isParamOrTemplateParamKind() const
llvm::PointerIntPair< const CXXBaseSpecifier *, 1 > Base
When Kind == EK_Base, the base specifier that provides the base class.
bool allowsNRVO() const
Determine whether this initialization allows the named return value optimization, which also applies ...
bool isParameterKind() const
void dump() const
Dump a representation of the initialized entity to standard error, for debugging purposes.
EntityKind
Specifies the kind of entity being initialized.
@ EK_Variable
The entity being initialized is a variable.
@ EK_Temporary
The entity being initialized is a temporary object.
@ EK_Binding
The entity being initialized is a structured binding of a decomposition declaration.
@ EK_BlockElement
The entity being initialized is a field of block descriptor for the copied-in c++ object.
@ EK_Parameter_CF_Audited
The entity being initialized is a function parameter; function is member of group of audited CF APIs.
@ EK_LambdaToBlockConversionBlockElement
The entity being initialized is a field of block descriptor for the copied-in lambda object that's us...
@ EK_Member
The entity being initialized is a non-static data member subobject.
@ EK_Base
The entity being initialized is a base member subobject.
@ EK_Result
The entity being initialized is the result of a function call.
@ EK_TemplateParameter
The entity being initialized is a non-type template parameter.
@ EK_StmtExprResult
The entity being initialized is the result of a statement expression.
@ EK_ParenAggInitMember
The entity being initialized is a non-static data member subobject of an object initialized via paren...
@ EK_VectorElement
The entity being initialized is an element of a vector.
@ EK_New
The entity being initialized is an object (or array of objects) allocated via new.
@ EK_CompoundLiteralInit
The entity being initialized is the initializer for a compound literal.
@ EK_Parameter
The entity being initialized is a function parameter.
@ EK_Delegating
The initialization is being done by a delegating constructor.
@ EK_ComplexElement
The entity being initialized is the real or imaginary part of a complex number.
@ EK_ArrayElement
The entity being initialized is an element of an array.
@ EK_LambdaCapture
The entity being initialized is the field that captures a variable in a lambda.
@ EK_Exception
The entity being initialized is an exception object that is being thrown.
@ EK_RelatedResult
The entity being implicitly initialized back to the formal result type.
static InitializedEntity InitializeMemberFromParenAggInit(FieldDecl *Member)
Create the initialization entity for a member subobject initialized via parenthesized aggregate init.
SourceLocation getThrowLoc() const
Determine the location of the 'throw' keyword when initializing an exception object.
unsigned Index
When Kind == EK_ArrayElement, EK_VectorElement, or EK_ComplexElement, the index of the array or vecto...
bool isVariableLengthArrayNew() const
Determine whether this is an array new with an unknown bound.
llvm::PointerIntPair< ParmVarDecl *, 1 > Parameter
When Kind == EK_Parameter, the ParmVarDecl, with the integer indicating whether the parameter is "con...
const CXXBaseSpecifier * getBaseSpecifier() const
Retrieve the base specifier.
SourceLocation getReturnLoc() const
Determine the location of the 'return' keyword when initializing the result of a function call.
TypeSourceInfo * getTypeSourceInfo() const
Retrieve complete type-source information for the object being constructed, if known.
ObjCMethodDecl * getMethodDecl() const
Retrieve the ObjectiveC method being initialized.
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'.
An lvalue reference type, per C++11 [dcl.ref].
Represents the results of name lookup.
bool empty() const
Return true if no decls were found.
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
This represents a decl that may have a name.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Represent a C++ namespace.
Represents a place-holder for an object not to be initialized by anything.
ObjCEncodeExpr, used for @encode in Objective-C.
ObjCIndirectCopyRestoreExpr - Represents the passing of a function argument by indirect copy-restore ...
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void setDestAS(LangAS AS)
llvm::MutableArrayRef< Expr * > getPersistentArgsArray(unsigned N)
Provide storage for any Expr* arg that must be preserved until deferred template candidates are deduc...
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
@ CSK_Normal
Normal lookup.
SmallVectorImpl< OverloadCandidate >::iterator iterator
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...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
SmallVector< OverloadCandidate *, 32 > CompleteCandidates(Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, SourceLocation OpLoc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
Represents a parameter to a function.
PointerType - C99 6.7.5.1 - Pointer Declarators.
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
A (possibly-)qualified type.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
bool hasQualifiers() const
Determine whether this type has any qualifiers.
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
QualType withConst() const
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
bool isNull() const
Return true if this QualType doesn't point to a type yet.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
LangAS getAddressSpace() const
Return the address space of this type.
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
QualType getCanonicalType() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
bool isConstQualified() const
Determine whether this type is const-qualified.
bool hasAddressSpace() const
Check if this type has any address space qualifier.
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
The collection of all-type qualifiers we support.
unsigned getCVRQualifiers() const
void addAddressSpace(LangAS space)
@ OCL_Weak
Reading or writing from this object requires a barrier call.
bool hasQualifiers() const
Return true if the set contains any qualifiers.
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
bool hasAddressSpace() const
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Qualifiers withoutAddressSpace() const
void removeAddressSpace()
static Qualifiers fromCVRMask(unsigned CVR)
bool hasObjCLifetime() const
LangAS getAddressSpace() const
An rvalue reference type, per C++11 [dcl.ref].
Represents a struct/union/class.
field_iterator field_end() const
field_range fields() const
bool isRandomized() const
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
bool hasUninitializedExplicitInitFields() const
specific_decl_iterator< FieldDecl > field_iterator
field_iterator field_begin() const
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Base for LValueReferenceType and RValueReferenceType.
bool isSpelledAsLValue() const
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId, bool DeferHint=false)
Emit a compatibility diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
bool transformInitList(const InitializedEntity &Entity, InitListExpr *Init)
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose=true)
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, bool Diagnose=true)
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
Sema - This implements semantic analysis and AST building for C.
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, RecordDecl *ClassDecl, const IdentifierInfo *Name)
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
bool IsStringInit(Expr *Init, const ArrayType *AT)
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
Adds a conversion function template specialization candidate to the overload set, using template argu...
Preprocessor & getPreprocessor() const
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
FunctionTemplateDecl * DeclareAggregateDeductionGuideFromInitList(TemplateDecl *Template, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc)
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init)
FPOptionsOverride CurFPFeatureOverrides()
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.
ExpressionEvaluationContextRecord & parentEvaluationContext()
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
ASTContext & getASTContext() const
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
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.
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
llvm::SmallVector< QualType, 4 > CurrentParameterCopyTypes
Stack of types that correspond to the parameter entities that are currently being copy-initialized.
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true, bool StrictPackMatch=false)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
CXXConstructorDecl * LookupDefaultConstructor(CXXRecordDecl *Class)
Look up the default constructor for the given class.
const LangOptions & getLangOpts() const
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
ExprResult PerformQualificationConversion(Expr *E, QualType Ty, ExprValueKind VK=VK_PRValue, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
bool IsAssignConvertCompatible(AssignConvertType ConvTy)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp=false)
Checks access to a constructor.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl)
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, CXXConstructionKind ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
SourceManager & getSourceManager() const
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
bool BoundsSafetyCheckInitialization(const InitializedEntity &Entity, const InitializationKind &Kind, AssignmentAction Action, QualType LHSType, Expr *RHSExpr)
Perform Bounds Safety Semantic checks for initializing a Bounds Safety pointer.
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv=nullptr)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the initializer (and its subobjects) is sufficient for initializing the en...
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
SourceManager & SourceMgr
TypeSourceInfo * SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
DiagnosticsEngine & Diags
OpenCLOptions & getOpenCLOptions()
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
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...
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
Encodes a location in the source.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isAtStartOfImmediateMacroExpansion(SourceLocation Loc, SourceLocation *MacroBegin=nullptr) const
Returns true if the given MacroID location points at the beginning of the immediate macro expansion.
A trivial tuple used to represent a source range.
void setBegin(SourceLocation b)
SourceLocation getEnd() const
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
void setFromType(QualType T)
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
void setAllToTypes(QualType T)
QualType getToType(unsigned Idx) const
Stmt - This represents one statement.
SourceLocation getEndLoc() const LLVM_READONLY
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
SourceLocation getBeginLoc() const LLVM_READONLY
StringLiteral - This represents a string literal expression, e.g.
unsigned getLength() const
StringLiteralKind getKind() const
int64_t getCodeUnitS(size_t I, uint64_t BitWidth) const
StringRef getString() const
The base class of all kinds of template declarations (e.g., class, function, etc.).
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
bool isDependent() const
Determines whether this is a dependent template name.
Represents a type template specialization; the template must be a class template, a type alias templa...
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
SourceLocation getEndLoc() const
Get the end source location.
SourceLocation getBeginLoc() const
Get the begin source location.
A container of type source information.
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
QualType getType() const
Return the type wrapped by this type source info.
The base class of the type hierarchy.
bool isBooleanType() const
bool isMFloat8Type() const
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
bool isIncompleteArrayType() const
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
bool isRValueReferenceType() const
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
bool isConstantArrayType() const
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
CXXRecordDecl * castAsCXXRecordDecl() const
bool isArrayParameterType() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
bool isEnumeralType() const
bool isScalarType() const
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
bool isSizelessBuiltinType() const
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isExtVectorType() const
bool isOCLIntelSubgroupAVCType() const
bool isLValueReferenceType() const
bool isOpenCLSpecificType() const
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
RecordDecl * castAsRecordDecl() const
bool isAnyComplexType() const
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
bool isAtomicType() const
bool isFunctionProtoType() const
EnumDecl * castAsEnumDecl() const
bool isObjCObjectType() const
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool isFunctionType() const
bool isObjCObjectPointerType() const
bool isVectorType() const
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
bool isFloatingType() const
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
const T * getAs() const
Member-template getAs<specific type>'.
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
bool isNullPtrType() const
bool isRecordType() const
bool isObjCRetainableType() const
Simple class containing the result of Sema::CorrectTypo.
DeclClass * getCorrectionDeclAs() const
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Represents a variable declaration or definition.
const Expr * getInit() const
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
StorageDuration getStorageDuration() const
Get the storage duration of this variable, per C++ [basic.stc].
Represents a C array with a specified size that is not an integer-constant-expression.
Represents a GCC generic vector type.
unsigned getNumElements() const
VectorKind getVectorKind() const
QualType getElementType() const
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
void checkInitLifetime(Sema &SemaRef, const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for initializing the ent...
The JSON file list parser is used to communicate input to InstallAPI.
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
@ OR_Deleted
Succeeded, but refers to a deleted function.
@ OR_Success
Overload resolution succeeded.
@ OR_Ambiguous
Ambiguous candidates found.
@ OR_No_Viable_Function
No viable function found.
@ ovl_fail_bad_conversion
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
@ OCD_AllCandidates
Requests that all candidates be shown.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ SD_Thread
Thread storage duration.
@ SD_Static
Static storage duration.
@ SD_Automatic
Automatic storage duration (most local variables).
@ Result
The result type of a method or function.
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
@ Template
We are parsing a template declaration.
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
@ Compatible
Compatible - the types are compatible according to the standard.
ActionResult< Expr * > ExprResult
CastKind
CastKind - The kind of operation required for a conversion.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Expr * IgnoreParensSingleStep(Expr *E)
const FunctionProtoType * T
@ NK_Not_Narrowing
Not a narrowing conversion.
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ConstructorInfo getConstructorInfo(NamedDecl *ND)
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Braces
New-expression has a C++11 list-initializer.
CheckedConversionKind
The kind of conversion being performed.
@ Implicit
An implicit conversion.
@ CStyleCast
A C-style cast.
@ OtherCast
A cast other than a C-style cast.
@ FunctionalCast
A functional-style cast.
MutableArrayRef< Expr * > MultiExprArg
CXXConstructorDecl * Constructor
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
EvalResult is a struct with detailed info about an evaluated expression.
APValue Val
Val - This is the value the expression can be folded to.
bool HadMultipleCandidates
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
bool RebuildDefaultArgOrDefaultInit
Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
std::optional< InitializationContext > DelayedDefaultInitializationContext
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.