diff --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp b/clang-tools-extra/clangd/unittests/HoverTests.cpp --- a/clang-tools-extra/clangd/unittests/HoverTests.cpp +++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp @@ -995,7 +995,7 @@ HI.LocalScope = ""; HI.Kind = index::SymbolKind::TypeAlias; HI.Definition = "template using AA = A"; - HI.Type = {"A", "type-parameter-0-0"}; // FIXME: should be 'T' + HI.Type = {"A", "T"}; HI.TemplateParameters = {{{"typename"}, std::string("T"), llvm::None}}; }}, {// Constant array diff --git a/clang/include/clang/AST/ASTNodeTraverser.h b/clang/include/clang/AST/ASTNodeTraverser.h --- a/clang/include/clang/AST/ASTNodeTraverser.h +++ b/clang/include/clang/AST/ASTNodeTraverser.h @@ -414,6 +414,10 @@ // FIXME: ElaboratedType, DependentNameType, // DependentTemplateSpecializationType, ObjCObjectType + void VisitTypedefType(const TypedefType *T) { + if (T->hasDifferentUnderlyingType()) + Visit(T->desugar()); + } void VisitTypedefDecl(const TypedefDecl *D) { Visit(D->getUnderlyingType()); } void VisitEnumConstantDecl(const EnumConstantDecl *D) { diff --git a/clang/include/clang/AST/DeclTemplate.h b/clang/include/clang/AST/DeclTemplate.h --- a/clang/include/clang/AST/DeclTemplate.h +++ b/clang/include/clang/AST/DeclTemplate.h @@ -443,6 +443,8 @@ TemplatedDecl->getSourceRange().getEnd()); } + bool isTypeAlias() const; + protected: NamedDecl *TemplatedDecl; TemplateParameterList *TemplateParams; diff --git a/clang/include/clang/AST/TemplateBase.h b/clang/include/clang/AST/TemplateBase.h --- a/clang/include/clang/AST/TemplateBase.h +++ b/clang/include/clang/AST/TemplateBase.h @@ -572,6 +572,12 @@ SourceLocation RAngleLoc) : LAngleLoc(LAngleLoc), RAngleLoc(RAngleLoc) {} + TemplateArgumentListInfo(TemplateArgumentListInfo &&) = default; + TemplateArgumentListInfo &operator=(TemplateArgumentListInfo &&) = default; + TemplateArgumentListInfo(const TemplateArgumentListInfo &) = default; + TemplateArgumentListInfo & + operator=(const TemplateArgumentListInfo &) = default; + // This can leak if used in an AST node, use ASTTemplateArgumentListInfo // instead. void *operator new(size_t bytes, ASTContext &C) = delete; diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h --- a/clang/include/clang/AST/Type.h +++ b/clang/include/clang/AST/Type.h @@ -1790,6 +1790,15 @@ unsigned NumArgs; }; + class TypedefBitfields { + friend class TypedefType; + + unsigned : NumTypeBits; + + /// True if this typedef has underlying type different from decl. + unsigned hasDifferentUnderlyingType : 1; + }; + class SubstTemplateTypeParmTypeBitfields { friend class SubstTemplateTypeParmType; @@ -1876,6 +1885,7 @@ ConstantArrayTypeBitfields ConstantArrayTypeBits; AttributedTypeBitfields AttributedTypeBits; AutoTypeBitfields AutoTypeBits; + TypedefBitfields TypedefBits; BuiltinTypeBitfields BuiltinTypeBits; FunctionTypeBitfields FunctionTypeBits; ObjCObjectTypeBitfields ObjCObjectTypeBits; @@ -4485,6 +4495,14 @@ public: TypedefNameDecl *getDecl() const { return Decl; } + bool hasDifferentUnderlyingType() const { + return TypedefBits.hasDifferentUnderlyingType; + } + QualType getUnderlyingTypeIfDifferent() { + return hasDifferentUnderlyingType() + ? *reinterpret_cast(this + 1) + : QualType(); + } bool isSugared() const { return true; } QualType desugar() const; @@ -4986,11 +5004,13 @@ // The original type parameter. const TemplateTypeParmType *Replaced; + QualType Replacement; - SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon, - Optional PackIndex) - : Type(SubstTemplateTypeParm, Canon, Canon->getDependence()), - Replaced(Param) { + SubstTemplateTypeParmType(const TemplateTypeParmType *Param, + QualType Replacement, Optional PackIndex) + : Type(SubstTemplateTypeParm, Replacement.getCanonicalType(), + Replacement->getDependence()), + Replaced(Param), Replacement(Replacement) { SubstTemplateTypeParmTypeBits.PackIndex = PackIndex ? *PackIndex + 1 : 0; } @@ -5002,9 +5022,7 @@ /// Gets the type that was substituted for the template /// parameter. - QualType getReplacementType() const { - return getCanonicalTypeInternal(); - } + QualType getReplacementType() const { return Replacement; } Optional getPackIndex() const { if (SubstTemplateTypeParmTypeBits.PackIndex == 0U) diff --git a/clang/include/clang/AST/TypeProperties.td b/clang/include/clang/AST/TypeProperties.td --- a/clang/include/clang/AST/TypeProperties.td +++ b/clang/include/clang/AST/TypeProperties.td @@ -379,16 +379,12 @@ def : Property<"declaration", DeclRef> { let Read = [{ node->getDecl() }]; } - def : Property<"canonicalType", Optional> { - let Read = [{ makeOptionalFromNullable(node->getCanonicalTypeInternal()) }]; + def : Property<"underlyingType", QualType> { + let Read = [{ node->desugar() }]; } def : Creator<[{ - QualType finalCanonicalType = - canonicalType ? ctx.getCanonicalType(*canonicalType) - : QualType(); - return ctx.getTypedefType(cast(declaration), - finalCanonicalType); + return ctx.getTypedefType(cast(declaration), underlyingType); }]>; } @@ -739,10 +735,8 @@ } def : Creator<[{ - // The call to getCanonicalType here existed in ASTReader.cpp, too. return ctx.getSubstTemplateTypeParmType( - cast(replacedParameter), - ctx.getCanonicalType(replacementType), PackIndex); + cast(replacedParameter), replacementType, PackIndex); }]>; } diff --git a/clang/include/clang/Basic/LangOptions.h b/clang/include/clang/Basic/LangOptions.h --- a/clang/include/clang/Basic/LangOptions.h +++ b/clang/include/clang/Basic/LangOptions.h @@ -469,6 +469,9 @@ /// forward slash (/) elsewhere. bool UseTargetPathSeparator = false; + /// Resugar template specializations. + bool Resugar = true; + LangOptions(); /// Set language defaults for the given input language and diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -5744,6 +5744,9 @@ LangOpts<"RecoveryASTType">, DefaultTrue, NegFlag, PosFlag>; +def fno_resugar : Flag<["-"], "fno-resugar">, + HelpText<"Do not resugar template specializations">, + MarshallingInfoNegativeFlag>; let Group = Action_Group in { diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -7841,9 +7841,9 @@ void NoteAllFoundTemplates(TemplateName Name); - QualType CheckTemplateIdType(TemplateName Template, + QualType CheckTemplateIdType(NestedNameSpecifier *NNS, TemplateName Template, SourceLocation TemplateLoc, - TemplateArgumentListInfo &TemplateArgs); + TemplateArgumentListInfo &TemplateArgs); TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, @@ -7994,14 +7994,13 @@ CTAK_DeducedFromArrayBound }; - bool CheckTemplateArgument(NamedDecl *Param, - TemplateArgumentLoc &Arg, - NamedDecl *Template, - SourceLocation TemplateLoc, + bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, + NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, - SmallVectorImpl &Converted, - CheckTemplateArgumentKind CTAK = CTAK_Specified); + SmallVectorImpl &Converted, + CheckTemplateArgumentKind CTAK, + bool DontCanonicalize); /// Check that the given template arguments can be be provided to /// the given template, converting the arguments along the way. @@ -8038,17 +8037,20 @@ bool PartialTemplateArgs, SmallVectorImpl &Converted, bool UpdateArgsWithConversions = true, - bool *ConstraintsNotSatisfied = nullptr); + bool *ConstraintsNotSatisfied = nullptr, + bool DontCanonicalize = false); bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, - SmallVectorImpl &Converted); + SmallVectorImpl &Converted, + bool DontCanonizalize); bool CheckTemplateArgument(TypeSourceInfo *Arg); ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType InstantiatedParamType, Expr *Arg, TemplateArgument &Converted, - CheckTemplateArgumentKind CTAK = CTAK_Specified); + CheckTemplateArgumentKind CTAK, + bool DontCanonizalize); bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg); @@ -8661,7 +8663,8 @@ TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, - sema::TemplateDeductionInfo &Info); + sema::TemplateDeductionInfo &Info, + bool DontCanonicalize = false); TemplateDeductionResult DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, @@ -9533,6 +9536,10 @@ } }; + QualType resugar(const NestedNameSpecifier *NNS, QualType T); + bool Sema::resugarTemplateArguments(NestedNameSpecifier *NNS, + TemplateArgumentListInfo &Args); + void PerformPendingInstantiations(bool LocalOnly = false); TypeSourceInfo *SubstType(TypeSourceInfo *T, diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp --- a/clang/lib/AST/ASTContext.cpp +++ b/clang/lib/AST/ASTContext.cpp @@ -2358,12 +2358,12 @@ return getTypeInfo(cast(T)->desugar().getTypePtr()); case Type::Typedef: { - const TypedefNameDecl *Typedef = cast(T)->getDecl(); - TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); + const auto *TT = cast(T); + TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr()); // If the typedef has an aligned attribute on it, it overrides any computed // alignment we have. This violates the GCC documentation (which says that // attribute(aligned) can only round up) but matches its implementation. - if (unsigned AttrAlign = Typedef->getMaxAlignment()) { + if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) { Align = AttrAlign; AlignRequirement = AlignRequirementKind::RequiredByTypedef; } else { @@ -4617,14 +4617,24 @@ /// specified typedef name decl. QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl, QualType Underlying) const { - if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); - + if (!Decl->TypeForDecl) { + if (Underlying.isNull()) + Underlying = Decl->getUnderlyingType(); + auto *newType = new (*this, TypeAlignment) TypedefType( + Type::Typedef, Decl, QualType(), getCanonicalType(Underlying)); + Decl->TypeForDecl = newType; + Types.push_back(newType); + return QualType(newType, 0); + } if (Underlying.isNull()) - Underlying = Decl->getUnderlyingType(); - QualType Canonical = getCanonicalType(Underlying); - auto *newType = new (*this, TypeAlignment) - TypedefType(Type::Typedef, Decl, Underlying, Canonical); - Decl->TypeForDecl = newType; + return QualType(Decl->TypeForDecl, 0); + if (Decl->getUnderlyingType() == Underlying) + return QualType(Decl->TypeForDecl, 0); + + // FIXME: Unique + void *Mem = Allocate(sizeof(TypedefType) + sizeof(QualType), TypeAlignment); + auto *newType = new (Mem) TypedefType(Type::Typedef, Decl, Underlying, + getCanonicalType(Underlying)); Types.push_back(newType); return QualType(newType, 0); } @@ -4737,9 +4747,6 @@ ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, QualType Replacement, Optional PackIndex) const { - assert(Replacement.isCanonical() - && "replacement types must always be canonical"); - llvm::FoldingSetNodeID ID; SubstTemplateTypeParmType::Profile(ID, Parm, Replacement, PackIndex); void *InsertPos = nullptr; @@ -4879,8 +4886,8 @@ if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) Template = QTN->getUnderlyingTemplate(); - bool IsTypeAlias = - isa_and_nonnull(Template.getAsTemplateDecl()); + const auto *TD = Template.getAsTemplateDecl(); + bool IsTypeAlias = TD && TD->isTypeAlias(); QualType CanonType; if (!Underlying.isNull()) CanonType = getCanonicalType(Underlying); @@ -7194,8 +7201,7 @@ void ASTContext::setCFConstantStringType(QualType T) { const auto *TD = T->castAs(); CFConstantStringTypeDecl = cast(TD->getDecl()); - const auto *TagType = - CFConstantStringTypeDecl->getUnderlyingType()->castAs(); + const auto *TagType = TD->castAs(); CFConstantStringTagDecl = TagType->getDecl(); } diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp --- a/clang/lib/AST/ASTImporter.cpp +++ b/clang/lib/AST/ASTImporter.cpp @@ -1361,8 +1361,12 @@ Expected ToDeclOrErr = import(T->getDecl()); if (!ToDeclOrErr) return ToDeclOrErr.takeError(); + ExpectedType ToUnderlyingTypeOrErr = import(T->desugar()); + if (!ToUnderlyingTypeOrErr) + return ToUnderlyingTypeOrErr.takeError(); - return Importer.getToContext().getTypeDeclType(*ToDeclOrErr); + return Importer.getToContext().getTypedefType(*ToDeclOrErr, + *ToUnderlyingTypeOrErr); } ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) { @@ -1529,8 +1533,7 @@ return ToReplacementTypeOrErr.takeError(); return Importer.getToContext().getSubstTemplateTypeParmType( - *ReplacedOrErr, ToReplacementTypeOrErr->getCanonicalType(), - T->getPackIndex()); + *ReplacedOrErr, *ToReplacementTypeOrErr, T->getPackIndex()); } ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmPackType( diff --git a/clang/lib/AST/ASTStructuralEquivalence.cpp b/clang/lib/AST/ASTStructuralEquivalence.cpp --- a/clang/lib/AST/ASTStructuralEquivalence.cpp +++ b/clang/lib/AST/ASTStructuralEquivalence.cpp @@ -961,7 +961,9 @@ case Type::Typedef: if (!IsStructurallyEquivalent(Context, cast(T1)->getDecl(), - cast(T2)->getDecl())) + cast(T2)->getDecl()) || + !IsStructurallyEquivalent(Context, cast(T1)->desugar(), + cast(T2)->desugar())) return false; break; diff --git a/clang/lib/AST/DeclTemplate.cpp b/clang/lib/AST/DeclTemplate.cpp --- a/clang/lib/AST/DeclTemplate.cpp +++ b/clang/lib/AST/DeclTemplate.cpp @@ -250,6 +250,23 @@ return false; } +bool TemplateDecl::isTypeAlias() const { + switch (getKind()) { + case TemplateDecl::TypeAliasTemplate: + return true; + case TemplateDecl::BuiltinTemplate: { + const auto *BT = cast(this); + if (BT->getBuiltinTemplateKind() == + BuiltinTemplateKind::BTK__make_integer_seq) + return true; + return false; + } + default: + return false; + }; + llvm_unreachable("unknown template kind"); +} + //===----------------------------------------------------------------------===// // RedeclarableTemplateDecl Implementation //===----------------------------------------------------------------------===// diff --git a/clang/lib/AST/FormatString.cpp b/clang/lib/AST/FormatString.cpp --- a/clang/lib/AST/FormatString.cpp +++ b/clang/lib/AST/FormatString.cpp @@ -976,10 +976,10 @@ bool FormatSpecifier::namedTypeToLengthModifier(QualType QT, LengthModifier &LM) { assert(isa(QT) && "Expected a TypedefType"); - const TypedefNameDecl *Typedef = cast(QT)->getDecl(); + const auto *TT = cast(QT); - for (;;) { - const IdentifierInfo *Identifier = Typedef->getIdentifier(); + do { + const IdentifierInfo *Identifier = TT->getDecl()->getIdentifier(); if (Identifier->getName() == "size_t") { LM.setKind(LengthModifier::AsSizeT); return true; @@ -997,12 +997,6 @@ LM.setKind(LengthModifier::AsPtrDiff); return true; } - - QualType T = Typedef->getUnderlyingType(); - if (!isa(T)) - break; - - Typedef = cast(T)->getDecl(); - } + } while ((TT = TT->desugar()->getAs())); return false; } diff --git a/clang/lib/AST/JSONNodeDumper.cpp b/clang/lib/AST/JSONNodeDumper.cpp --- a/clang/lib/AST/JSONNodeDumper.cpp +++ b/clang/lib/AST/JSONNodeDumper.cpp @@ -530,6 +530,8 @@ void JSONNodeDumper::VisitTypedefType(const TypedefType *TT) { JOS.attribute("decl", createBareDeclRef(TT->getDecl())); + if (TT->hasDifferentUnderlyingType()) + JOS.attribute("type", createQualType(TT->desugar())); } void JSONNodeDumper::VisitFunctionType(const FunctionType *T) { diff --git a/clang/lib/AST/QualTypeNames.cpp b/clang/lib/AST/QualTypeNames.cpp --- a/clang/lib/AST/QualTypeNames.cpp +++ b/clang/lib/AST/QualTypeNames.cpp @@ -253,6 +253,8 @@ true /*FullyQualified*/, WithGlobalNsPrefix); } else if (const auto *TDD = dyn_cast(Type)) { + if (TDD->hasDifferentUnderlyingType()) + return Scope; return TypeName::createNestedNameSpecifier(Ctx, TDD->getDecl(), true /*FullyQualified*/, WithGlobalNsPrefix); @@ -325,7 +327,10 @@ Decl *Decl = nullptr; // There are probably other cases ... if (const auto *TDT = dyn_cast(TypePtr)) { - Decl = TDT->getDecl(); + if (TDT->hasDifferentUnderlyingType()) + Decl = TypePtr->getAsCXXRecordDecl(); + else + Decl = TDT->getDecl(); } else if (const auto *TagDeclType = dyn_cast(TypePtr)) { Decl = TagDeclType->getDecl(); } else if (const auto *TST = dyn_cast(TypePtr)) { diff --git a/clang/lib/AST/TextNodeDumper.cpp b/clang/lib/AST/TextNodeDumper.cpp --- a/clang/lib/AST/TextNodeDumper.cpp +++ b/clang/lib/AST/TextNodeDumper.cpp @@ -1546,7 +1546,10 @@ } void TextNodeDumper::VisitTypedefType(const TypedefType *T) { - dumpDeclRef(T->getDecl()); + const TypedefNameDecl *D = T->getDecl(); + dumpDeclRef(D); + if (T->hasDifferentUnderlyingType()) + dumpType(T->desugar()); } void TextNodeDumper::VisitUnaryTransformType(const UnaryTransformType *T) { diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp --- a/clang/lib/AST/Type.cpp +++ b/clang/lib/AST/Type.cpp @@ -3434,14 +3434,19 @@ } TypedefType::TypedefType(TypeClass tc, const TypedefNameDecl *D, - QualType underlying, QualType can) - : Type(tc, can, toSemanticDependence(underlying->getDependence())), + QualType Underlying, QualType can) + : Type(tc, can, toSemanticDependence(can->getDependence())), Decl(const_cast(D)) { assert(!isa(can) && "Invalid canonical type"); + TypedefBits.hasDifferentUnderlyingType = !Underlying.isNull(); + if (hasDifferentUnderlyingType()) + *reinterpret_cast(this + 1) = Underlying; } QualType TypedefType::desugar() const { - return getDecl()->getUnderlyingType(); + return hasDifferentUnderlyingType() + ? *reinterpret_cast(this + 1) + : Decl->getUnderlyingType(); } UsingType::UsingType(const UsingShadowDecl *Found, QualType Underlying, diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp --- a/clang/lib/CodeGen/CGDebugInfo.cpp +++ b/clang/lib/CodeGen/CGDebugInfo.cpp @@ -1264,10 +1264,11 @@ assert(Ty->isTypeAlias()); llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit); - auto *AliasDecl = - cast(Ty->getTemplateName().getAsTemplateDecl()) - ->getTemplatedDecl(); + const TemplateDecl *TD = Ty->getTemplateName().getAsTemplateDecl(); + if (isa(TD)) + return Src; + const auto *AliasDecl = cast(TD)->getTemplatedDecl(); if (AliasDecl->hasAttr()) return Src; diff --git a/clang/lib/Sema/SemaCXXScopeSpec.cpp b/clang/lib/Sema/SemaCXXScopeSpec.cpp --- a/clang/lib/Sema/SemaCXXScopeSpec.cpp +++ b/clang/lib/Sema/SemaCXXScopeSpec.cpp @@ -736,6 +736,7 @@ QualType T = Context.getTypeDeclType(cast(SD->getUnderlyingDecl())); + T = resugar(SS.getScopeRep(), T); if (T->isEnumeralType()) Diag(IdInfo.IdentifierLoc, diag::warn_cxx98_compat_enum_nested_name_spec); @@ -875,17 +876,19 @@ QualType T = BuildDecltypeType(DS.getRepAsExpr()); if (T.isNull()) return true; + T = resugar(SS.getScopeRep(), T); + + TypeLocBuilder TLB; + DecltypeTypeLoc DecltypeTL = TLB.push(T); + DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); + DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd()); if (!T->isDependentType() && !T->getAs()) { Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace) - << T << getLangOpts().CPlusPlus; + << T << getLangOpts().CPlusPlus; return true; } - TypeLocBuilder TLB; - DecltypeTypeLoc DecltypeTL = TLB.push(T); - DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); - DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd()); SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T), ColonColonLoc); return false; @@ -931,6 +934,7 @@ // Handle a dependent template specialization for which we cannot resolve // the template name. assert(DTN->getQualifier() == SS.getScopeRep()); + resugarTemplateArguments(SS.getScopeRep(), TemplateArgs); QualType T = Context.getDependentTemplateSpecializationType(ETK_None, DTN->getQualifier(), DTN->getIdentifier(), @@ -975,18 +979,11 @@ // We were able to resolve the template name to an actual template. // Build an appropriate nested-name-specifier. - QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs); + QualType T = CheckTemplateIdType(SS.getScopeRep(), Template, TemplateNameLoc, + TemplateArgs); if (T.isNull()) return true; - // Alias template specializations can produce types which are not valid - // nested name specifiers. - if (!T->isDependentType() && !T->getAs()) { - Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T; - NoteAllFoundTemplates(Template); - return true; - } - // Provide source-location information for the template specialization type. TypeLocBuilder Builder; TemplateSpecializationTypeLoc SpecTL @@ -998,6 +995,13 @@ for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); + // Alias template specializations can produce types which are not valid + // nested name specifiers. + if (!T->isDependentType() && !T->getAs()) { + Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T; + NoteAllFoundTemplates(Template); + return true; + } SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T), CCLoc); diff --git a/clang/lib/Sema/SemaCoroutine.cpp b/clang/lib/Sema/SemaCoroutine.cpp --- a/clang/lib/Sema/SemaCoroutine.cpp +++ b/clang/lib/Sema/SemaCoroutine.cpp @@ -92,7 +92,7 @@ // Build the template-id. QualType CoroTrait = - S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args); + S.CheckTemplateIdType(nullptr, TemplateName(CoroTraits), KwLoc, Args); if (CoroTrait.isNull()) return QualType(); if (S.RequireCompleteType(KwLoc, CoroTrait, @@ -170,7 +170,7 @@ // Build the template-id. QualType CoroHandleType = - S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args); + S.CheckTemplateIdType(nullptr, TemplateName(CoroHandle), Loc, Args); if (CoroHandleType.isNull()) return QualType(); if (S.RequireCompleteType(Loc, CoroHandleType, diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -491,6 +491,8 @@ DiagnoseUseOfDecl(IIDecl, NameLoc); T = Context.getTypeDeclType(TD); + if (SS && SS->isValid()) + T = resugar(SS->getScopeRep(), T); MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); } else if (ObjCInterfaceDecl *IDecl = dyn_cast(IIDecl)) { (void)DiagnoseUseOfDecl(IDecl, NameLoc); diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp --- a/clang/lib/Sema/SemaDeclCXX.cpp +++ b/clang/lib/Sema/SemaDeclCXX.cpp @@ -1031,7 +1031,8 @@ } // Build the template-id. - QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); + QualType TraitTy = + S.CheckTemplateIdType(nullptr, TemplateName(TraitTD), Loc, Args); if (TraitTy.isNull()) return true; if (!S.isCompleteType(Loc, TraitTy)) { @@ -11563,8 +11564,8 @@ Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), Context.getTrivialTypeSourceInfo(Element, Loc))); - return Context.getCanonicalType( - CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); + return Context.getCanonicalType(CheckTemplateIdType( + nullptr, TemplateName(StdInitializerList), Loc, Args)); } bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { diff --git a/clang/lib/Sema/SemaLookup.cpp b/clang/lib/Sema/SemaLookup.cpp --- a/clang/lib/Sema/SemaLookup.cpp +++ b/clang/lib/Sema/SemaLookup.cpp @@ -3470,8 +3470,9 @@ SmallVector Checked; TemplateArgumentLoc Arg(TemplateArgument(StringLit), StringLit); if (CheckTemplateArgument(Params->getParam(0), Arg, FD, - R.getNameLoc(), R.getNameLoc(), 0, - Checked) || + R.getNameLoc(), R.getNameLoc(), 0, Checked, + CTAK_Specified, + /*DontCanonicalize=*/true) || Trap.hasErrorOccurred()) IsTemplate = false; } diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp --- a/clang/lib/Sema/SemaOverload.cpp +++ b/clang/lib/Sema/SemaOverload.cpp @@ -5685,9 +5685,6 @@ Sema::CCEKind CCE, bool RequireInt, NamedDecl *Dest) { - assert(S.getLangOpts().CPlusPlus11 && - "converted constant expression outside C++11"); - if (checkPlaceholderForOverload(S, From)) return ExprError(); diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -11,6 +11,7 @@ #include "TreeTransform.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" +#include "clang/AST/ASTLambda.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclFriend.h" #include "clang/AST/DeclTemplate.h" @@ -90,6 +91,898 @@ return Depth; } +namespace { +class Resugarer : public TreeTransform { + using inherited = TreeTransform; + + struct ArgList { + Optional> Inner; + SmallVector DCs; + }; + const ArgList *MLTAL = nullptr; + + using DCToArgsMap = + llvm::DenseMap>; + DCToArgsMap *DCToArgs = nullptr; + SmallVector, 4> ConvertedArgsBuf; + + ArrayRef getArgs(unsigned Depth) { + unsigned Top = MLTAL->DCs.size(); + if (MLTAL->Inner) { + if (Depth == Top) + return *MLTAL->Inner; + } + --Top; + assert(Depth <= Top); + auto It = DCToArgs->find(MLTAL->DCs[Top - Depth]); + return It != DCToArgs->end() ? It->second : ArrayRef(); + } + +public: + struct BuildMLTALRAII { + BuildMLTALRAII(Resugarer &R, const DeclContext *DC) + : BuildMLTALRAII(R, DC, nullptr, nullptr){}; + BuildMLTALRAII(Resugarer &R, TemplateDecl *TD, + const TemplateArgumentListInfo &Args) + : BuildMLTALRAII(R, TD->getDeclContext(), + const_cast(&Args), TD){}; + ~BuildMLTALRAII() { + R->MLTAL = OldMLTAL; + R->ConvertedArgsBuf.resize(OldConvertedArgsBufSize); + } + + private: + BuildMLTALRAII(Resugarer &R, const DeclContext *DC, + TemplateArgumentListInfo *Args, TemplateDecl *TD) + : R(&R), OldMLTAL(std::exchange(R.MLTAL, &MLTAL)), + OldConvertedArgsBufSize(R.ConvertedArgsBuf.size()) { + if (Args) { + if (Args->size() != 0) { + auto &ConvertedArgs = R.ConvertedArgsBuf.emplace_back(); + if (R.SemaRef.CheckTemplateArgumentList( + TD, SourceLocation(), *Args, false, ConvertedArgs, + /*UpdateArgsWithConversions=*/false, + /*ConstrantsNotSatisfied=*/nullptr, + /*DontCanonicalize=*/true)) + llvm_unreachable("Unexpected conversion failure"); + MLTAL.Inner = ConvertedArgs; + } else { + MLTAL.Inner = ArrayRef(); + } + } + auto addDC = [&](const DeclContext *DC) { MLTAL.DCs.emplace_back(DC); }; + while (DC) { + switch (Decl::Kind DK = DC->getDeclKind()) { + case Decl::Kind::ClassTemplatePartialSpecialization: + case Decl::Kind::ClassTemplateSpecialization: { + const auto *CTS = cast(DC); + if (!CTS->isClassScopeExplicitSpecialization()) { + if (CTS->getSpecializationKind() == TSK_ExplicitSpecialization && + DK != Decl::Kind::ClassTemplatePartialSpecialization) + return; + addDC(DC); + if (CTS->getSpecializedTemplate()->isMemberSpecialization()) + return; + break; + } + LLVM_FALLTHROUGH; + } + case Decl::Kind::CXXRecord: { + const auto *RD = cast(DC); + if (const auto *CT = RD->getDescribedClassTemplate()) { + addDC(DC); + if (CT->isMemberSpecialization()) + return; + } + break; + } + case Decl::Kind::CXXConstructor: + case Decl::Kind::CXXDestructor: + case Decl::Kind::CXXConversion: + case Decl::Kind::CXXMethod: + case Decl::Kind::CXXDeductionGuide: + case Decl::Kind::Function: { + const auto *FD = cast(DC); + if (FD->getTemplateSpecializationKindForInstantiation() == + TSK_ExplicitSpecialization) + return; + + if (FD->getTemplateSpecializationKind() == + TSK_ExplicitSpecialization) { + } else if (const TemplateArgumentList *TemplateArgs = + FD->getTemplateSpecializationArgs()) { + addDC(DC); + if (FD->getPrimaryTemplate()->isMemberSpecialization() || + isGenericLambdaCallOperatorOrStaticInvokerSpecialization(FD)) + return; + } else if (FD->getDescribedFunctionTemplate()) { + addDC(DC); + } + if (FD->getFriendObjectKind() && + FD->getDeclContext()->isFileContext()) { + DC = FD->getLexicalDeclContext(); + continue; + } + break; + } + case Decl::Kind::TranslationUnit: + case Decl::Kind::Namespace: + case Decl::Kind::Export: + return; + case Decl::Kind::LinkageSpec: + break; + default: + cast(DC)->dumpColor(); + llvm_unreachable("Unexpected Decl Kind"); + } + DC = DC->getParent(); + } + } + + Resugarer *R; + ArgList MLTAL; + const ArgList *OldMLTAL; + size_t OldConvertedArgsBufSize; + }; + + struct NamingContextBase { + NamingContextBase(Resugarer &R) + : R(&R), OldMap(std::exchange(R.DCToArgs, &Map)), + OldConvertedArgsBufSize(R.ConvertedArgsBuf.size()) {} + ~NamingContextBase() { + R->DCToArgs = OldMap; + R->ConvertedArgsBuf.resize(OldConvertedArgsBufSize); + } + + protected: + void insertDCToMap(bool Reverse, const DeclContext *DC, + ArrayRef Args = {}) { + if (Reverse || Args.empty()) + R->DCToArgs->try_emplace(DC, Args); + else + (*R->DCToArgs)[DC] = Args; + } + + void deduceClassTemplatePartialSpecialization( + ClassTemplatePartialSpecializationDecl *D, bool Reverse, + ArrayRef Args, const DeclContext *DC) { + TemplateParameterList *TPL = D->getTemplateParameters(); + TemplateDeductionInfo Info(SourceLocation{}, TPL->getDepth()); + // FIXME: We can't deal very well with non-canonical template + // arguments so this will fail sometimes. + Sema::TemplateDeductionResult Res = R->SemaRef.DeduceTemplateArguments( + D, TemplateArgumentList(TemplateArgumentList::OnStackType{}, Args), + Info, + /*DontCaninicalize=*/true); + return insertDCToMap(Reverse, DC, + Res == Sema::TDK_Success + ? Info.take()->asArray() + : ArrayRef()); + } + + void addTypeToMap(bool Reverse, const Type *T) { + struct { + DeclContext *DC; + const TemplateSpecializationType *TS; + } Entity; + { + QualType TCanon = T->getCanonicalTypeInternal(); + switch (TCanon->getTypeClass()) { + case Type::Record: { + const auto *TS = T->getAs(); + while (TS && TS->isTypeAlias()) + TS = TS->getAliasedType()->getAs(); + Entity = {T->getAsRecordDecl(), TS}; + break; + } + case Type::InjectedClassName: { + const auto *ICN = cast(TCanon); + Entity = {ICN->getDecl(), ICN->getInjectedTST()}; + break; + } + case Type::TemplateSpecialization: + case Type::DependentTemplateSpecialization: + case Type::TemplateTypeParm: + case Type::DependentName: + return; + default: + TCanon.dump(); + llvm_unreachable(""); + } + } + switch (auto DCK = Entity.DC->getDeclKind()) { + default: + llvm::outs() << "Kind: " << DCK << "\n"; + llvm_unreachable(""); + case Decl::CXXRecord: + return; + case Decl::ClassTemplateSpecialization: + case Decl::ClassTemplatePartialSpecialization: + if (!Entity.TS) + return insertDCToMap(Reverse, Entity.DC); + assert(!Entity.TS->isTypeAlias()); + ArrayRef Args = Entity.TS->template_arguments(); + + if (DCK == Decl::ClassTemplatePartialSpecialization) + return deduceClassTemplatePartialSpecialization( + cast(Entity.DC), Reverse, + Args, Entity.DC); + + auto *CTSD = cast(Entity.DC); + TemplateArgumentListInfo ArgsInfo; + for (auto &&I : Args) + ArgsInfo.addArgument(R->SemaRef.getTrivialTemplateArgumentLoc( + I, /*NTTPType=*/QualType(), SourceLocation())); + + SmallVector ConvertedArgs; + if (R->SemaRef.CheckTemplateArgumentList( + CTSD->getSpecializedTemplate(), SourceLocation(), ArgsInfo, + false, ConvertedArgs, + /*UpdateArgsWithConversions=*/false, + /*ConstrantsNotSatisfied=*/nullptr, + /*DontCanonicalize=*/true)) + llvm_unreachable("Unexpected conversion failure"); + if (auto *CTPSD = + CTSD->getSpecializedTemplateOrPartial() + .dyn_cast()) + return deduceClassTemplatePartialSpecialization( + CTPSD, Reverse, ConvertedArgs, Entity.DC); + return insertDCToMap( + Reverse, Entity.DC, + R->ConvertedArgsBuf.emplace_back(std::move(ConvertedArgs))); + } + llvm_unreachable("Unhandled IDC Kind"); + } + + Resugarer *R; + DCToArgsMap Map, *OldMap; + + private: + size_t OldConvertedArgsBufSize; + }; + + struct NamingContextRAII : NamingContextBase { + NamingContextRAII(Resugarer &R, const NestedNameSpecifier *NNS) + : NamingContextBase(R) { + for (/**/; NNS; NNS = NNS->getPrefix()) + switch (auto NNSK = NNS->getKind()) { + case NestedNameSpecifier::Global: + case NestedNameSpecifier::Namespace: + case NestedNameSpecifier::NamespaceAlias: + return; + case NestedNameSpecifier::Identifier: + case NestedNameSpecifier::Super: + continue; + case NestedNameSpecifier::TypeSpec: + case NestedNameSpecifier::TypeSpecWithTemplate: + addTypeToMap(/*Reverse=*/false, NNS->getAsType()); + continue; + default: + llvm::outs() << "Kind: " << NNSK << "\n"; + llvm_unreachable(""); + } + if (OldMap) + for (auto &&I : *OldMap) { + auto &R = Map[I.first]; + if (R.empty()) + R = I.second; + } + } + }; + + struct NamingContextTransformRAII : NamingContextBase { + NamingContextTransformRAII(Resugarer &R, NestedNameSpecifierLoc &NNS) + : NamingContextBase(R) { + CXXScopeSpec SS; + Qseq Qs = getQualifiers(NNS); + for (const NestedNameSpecifierLoc &Q : llvm::reverse(Qs)) { + const auto *Qnns = Q.getNestedNameSpecifier(); + switch (Qnns->getKind()) { + case NestedNameSpecifier::Global: + SS.MakeGlobal(R.SemaRef.Context, Q.getBeginLoc()); + break; + case NestedNameSpecifier::Namespace: + SS.Extend(R.SemaRef.Context, Qnns->getAsNamespace(), + Q.getLocalBeginLoc(), Q.getLocalEndLoc()); + break; + case NestedNameSpecifier::NamespaceAlias: + SS.Extend(R.SemaRef.Context, Qnns->getAsNamespaceAlias(), + Q.getLocalBeginLoc(), Q.getLocalEndLoc()); + break; + case NestedNameSpecifier::Identifier: + SS.Extend(R.SemaRef.Context, Qnns->getAsIdentifier(), + Q.getLocalBeginLoc(), Q.getLocalEndLoc()); + break; + case NestedNameSpecifier::Super: + SS.MakeSuper(R.SemaRef.Context, Qnns->getAsRecordDecl(), + Q.getBeginLoc(), Q.getEndLoc()); + break; + case NestedNameSpecifier::TypeSpec: + case NestedNameSpecifier::TypeSpecWithTemplate: { + TypeLocBuilder TLB; + TypeLoc TL = Q.getTypeLoc(); + TLB.reserve(TL.getFullDataSize()); + QualType T = R.TransformType(TLB, TL); + addTypeToMap(/*Reverse=*/true, T.getTypePtr()); + SS.Extend(R.SemaRef.Context, /*FIXME:*/ SourceLocation(), + TLB.getTypeSourceInfo(R.SemaRef.Context, T)->getTypeLoc(), + Q.getLocalEndLoc()); + break; + } + default: + llvm_unreachable(""); + } + } + if (SS.getScopeRep() == NNS.getNestedNameSpecifier()) + return; + if (llvm::equal( + ArrayRef(SS.location_data(), SS.location_size()), + ArrayRef((char *)NNS.getOpaqueData(), NNS.getDataLength()))) + NNS = NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData()); + else + NNS = SS.getWithLocInContext(R.SemaRef.Context); + } + + private: + using Qseq = SmallVector; + + Qseq getQualifiers(NestedNameSpecifierLoc NNS) { + Qseq Qs; + bool InheritOldMap = true; + for (/**/; NNS; NNS = NNS.getPrefix()) { + NestedNameSpecifier::SpecifierKind K = + NNS.getNestedNameSpecifier()->getKind(); + if (K == NestedNameSpecifier::Global || + K == NestedNameSpecifier::Namespace || + K == NestedNameSpecifier::NamespaceAlias) + InheritOldMap = false; + Qs.push_back(NNS); + } + // If we did not see the global / namespace prefix, + // inherit the old map. + if (InheritOldMap && OldMap) + Map.copyFrom(*OldMap); + return Qs; + } + }; + + Resugarer(Sema &SemaRef) : inherited(SemaRef) {} + + bool AlwaysRebuild() { return false; } + bool ReplacingOriginal() { return false; } + + QualType TransformElaboratedType(TypeLocBuilder &TLB, ElaboratedTypeLoc TL) { + NestedNameSpecifierLoc QualifierLoc = TL.getQualifierLoc(); + NamingContextTransformRAII NamingScope(*this, QualifierLoc); + QualType NamedT = TransformType(TLB, TL.getNamedTypeLoc()); + + const ElaboratedType *T = TL.getTypePtr(); + QualType Result = + QualifierLoc != TL.getQualifierLoc() || NamedT != T->getNamedType() + ? SemaRef.Context.getElaboratedType( + T->getKeyword(), QualifierLoc.getNestedNameSpecifier(), + NamedT) + : TL.getType(); + + ElaboratedTypeLoc NewTL = TLB.push(Result); + NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc()); + NewTL.setQualifierLoc(QualifierLoc); + return Result; + } + + Decl *TransformDecl(SourceLocation Loc, Decl *D) const { return D; } + + QualType TransformSubstTemplateTypeParmType(QualType QT) { + if (!MLTAL) + return QT; + + const auto *T = cast(QT); + const TemplateTypeParmType *Replaced = T->getReplacedParameter(); + + ArrayRef Args = getArgs(Replaced->getDepth()); + if (Args.size() == 0) + return QT; + assert(Replaced->getIndex() < Args.size()); + const TemplateArgument &ReplacementArg = Args[Replaced->getIndex()]; + QualType Replacement; + auto PackIndex = T->getPackIndex(); + if (PackIndex) + Replacement = ReplacementArg.getPackAsArray()[*PackIndex] + .getAsType() + .getNonPackExpansionType(); + else + Replacement = ReplacementArg.getAsType().getNonPackExpansionType(); + + if (0 && !SemaRef.Context.hasSameType(Replacement, T->getReplacementType())/* && + Replacement->getTypeClass() != Type::Decltype && + T->getReplacementType()->getTypeClass() != Type::Decltype*/) { + Replacement.dump(); + T->getReplacementType().dump(); + assert(false); + } + + return SemaRef.Context.getSubstTemplateTypeParmType(Replaced, Replacement, + PackIndex); + } + + QualType TransformSubstTemplateTypeParmType(TypeLocBuilder &TLB, + SubstTemplateTypeParmTypeLoc TL) { + QualType Result = TransformSubstTemplateTypeParmType(TL.getType()); + auto NewTL = TLB.push(Result); + NewTL.setNameLoc(TL.getNameLoc()); + return Result; + } + + using inherited::TransformTemplateSpecializationType; + + template + QualType TransformTemplateSpecializationType( + TemplateName N, bool IsTypeAlias, ArgIterator First, ArgIterator Last, + TemplateArgumentListInfo &NewArgs, QualType Underlying) { + if (const SubstTemplateTemplateParmStorage *STTP = + N.getAsSubstTemplateTemplateParm()) { + // FIXME: Resugar default arguments on template template parameters. + // The AST currently cannot represent this. + Resugarer::BuildMLTALRAII SubstitutionScope(*this, STTP->getParameter(), + TemplateArgumentListInfo()); + if (TransformTemplateArguments(First, Last, NewArgs)) + llvm_unreachable(""); + } else { + if (TransformTemplateArguments(First, Last, NewArgs)) + llvm_unreachable(""); + } + if (IsTypeAlias) { + BuildMLTALRAII SubstScope(*this, N.getAsTemplateDecl(), NewArgs); + Underlying = TransformType(Underlying); + } + return SemaRef.Context.getTemplateSpecializationType(N, NewArgs, + Underlying); + } + + QualType TransformTemplateSpecializationType(TypeLocBuilder &TLB, + TemplateSpecializationTypeLoc TL, + TemplateName N) { + const TemplateSpecializationType *T = TL.getTypePtr(); + + TemplateArgumentListInfo NewArgs; + NewArgs.setLAngleLoc(TL.getLAngleLoc()); + NewArgs.setRAngleLoc(TL.getRAngleLoc()); + using Iter = + TemplateArgumentLocContainerIterator; + QualType Result = TransformTemplateSpecializationType( + N, T->isTypeAlias(), Iter(TL, 0), Iter(TL, TL.getNumArgs()), NewArgs, + T->desugar()); + TemplateSpecializationTypeLoc NewTL = + TLB.push(Result); + NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc()); + NewTL.setTemplateNameLoc(TL.getTemplateNameLoc()); + NewTL.setLAngleLoc(TL.getLAngleLoc()); + NewTL.setRAngleLoc(TL.getRAngleLoc()); + for (unsigned i = 0, e = NewArgs.size(); i != e; ++i) + NewTL.setArgLocInfo(i, NewArgs[i].getLocInfo()); + return Result; + } + + template + QualType TransformDependentTemplateSpecializationType( + ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, + const IdentifierInfo *ID, ArgIterator First, ArgIterator Last, + TemplateArgumentListInfo &NewArgs) { + if (TransformTemplateArguments(First, Last, NewArgs)) + llvm_unreachable(""); + // FIXME: don't rebuild if nothing changed. + return SemaRef.Context.getDependentTemplateSpecializationType(Keyword, NNS, + ID, NewArgs); + } + + template + QualType TransformDependentTemplateSpecializationType( + ElaboratedTypeKeyword Keyword, NestedNameSpecifierLoc &NNS, + const IdentifierInfo *ID, ArgIterator First, ArgIterator Last, + TemplateArgumentListInfo &NewArgs) { + NamingContextTransformRAII NamingScope(*this, NNS); + return TransformDependentTemplateSpecializationType( + Keyword, NNS.getNestedNameSpecifier(), ID, First, Last, NewArgs); + } + + QualType TransformDependentTemplateSpecializationType( + TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL) { + const DependentTemplateSpecializationType *T = TL.getTypePtr(); + TemplateArgumentListInfo NewArgs; + NewArgs.setLAngleLoc(TL.getLAngleLoc()); + NewArgs.setRAngleLoc(TL.getRAngleLoc()); + + using Iter = TemplateArgumentLocContainerIterator< + DependentTemplateSpecializationTypeLoc>; + NestedNameSpecifierLoc NNS = TL.getQualifierLoc(); + QualType Result = TransformDependentTemplateSpecializationType( + T->getKeyword(), NNS, T->getIdentifier(), Iter(TL, 0), + Iter(TL, TL.getNumArgs()), NewArgs); + + DependentTemplateSpecializationTypeLoc NewTL = + TLB.push(Result); + NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc()); + NewTL.setQualifierLoc(NNS); + NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc()); + NewTL.setTemplateNameLoc(TL.getTemplateNameLoc()); + NewTL.setLAngleLoc(TL.getLAngleLoc()); + NewTL.setRAngleLoc(TL.getRAngleLoc()); + for (unsigned i = 0, e = NewArgs.size(); i != e; ++i) + NewTL.setArgLocInfo(i, NewArgs[i].getLocInfo()); + return Result; + } + + TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType, NamedDecl *, + CXXScopeSpec &) { + llvm_unreachable("unused"); + } + + QualType TransformDependentTemplateSpecializationType( + TypeLocBuilder &, DependentTemplateSpecializationTypeLoc, TemplateName, + CXXScopeSpec &) { + llvm_unreachable("unused"); + } + + TemplateName TransformTemplateName(CXXScopeSpec &SS, TemplateName Name, + SourceLocation NameLoc, + QualType ObjectType = QualType(), + NamedDecl *FirstQualifierInScope = nullptr, + bool AllowInjectedClassName = false) { + if (Name.getKind() == TemplateName::NameKind::SubstTemplateTemplateParm) + return Name; // FIXME: resugar these + return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType, + FirstQualifierInScope, + AllowInjectedClassName); + } + + QualType TransformDependentNameType(TypeLocBuilder &TLB, + DependentNameTypeLoc TL, + bool DeducedTSTContext = false) { + const DependentNameType *T = TL.getTypePtr(); + + NestedNameSpecifierLoc QualifierLoc = TL.getQualifierLoc(); + NamingContextTransformRAII NamingContext(*this, QualifierLoc); + assert(QualifierLoc); + assert(QualifierLoc.getNestedNameSpecifier()->isDependent()); + QualType Result = SemaRef.Context.getDependentNameType( + T->getKeyword(), QualifierLoc.getNestedNameSpecifier(), + T->getIdentifier()); + DependentNameTypeLoc NewTL = TLB.push(Result); + NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc()); + NewTL.setQualifierLoc(QualifierLoc); + NewTL.setNameLoc(TL.getNameLoc()); + return Result; + } + + QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) { + const TypedefType *T = TL.getTypePtr(); + const TypedefNameDecl *D = T->getDecl(); + QualType Underlying = D->getUnderlyingType(); + BuildMLTALRAII DCScope(*this, D->getDeclContext()); + QualType NewUnderlying = TransformType(D->getUnderlyingType()); + QualType Result = TL.getType(); + if (NewUnderlying != Underlying) + Result = SemaRef.Context.getTypedefType(D, NewUnderlying); + TypedefTypeLoc NewTL = TLB.push(Result); + NewTL.setNameLoc(TL.getNameLoc()); + return Result; + } + + ExprResult TransformExpr(Expr *E) { return E; } + + bool TransformTemplateArgument(const TemplateArgumentLoc &Input, + TemplateArgumentLoc &Output, bool) { + const TemplateArgument &Arg = Input.getArgument(); + switch (Arg.getKind()) { + case TemplateArgument::Null: + llvm_unreachable("Unexpected Null TemplateArgument"); + case TemplateArgument::Pack: { + TemplateArgumentListInfo Ins; + for (auto &&I : Arg.getPackAsArray()) { + TemplateArgumentLocInfo Info; + switch (I.getKind()) { + case TemplateArgument::Type: + Info = (TypeSourceInfo *)nullptr; + break; + case TemplateArgument::Template: + case TemplateArgument::TemplateExpansion: + Info = + TemplateArgumentLocInfo(SemaRef.Context, NestedNameSpecifierLoc(), + SourceLocation(), SourceLocation()); + break; + default: + break; + } + Ins.addArgument(TemplateArgumentLoc(I, Info)); + } + TemplateArgumentListInfo Outs; + TransformTemplateArguments(Ins.arguments().begin(), Ins.arguments().end(), + Outs); + SmallVector ROuts(Outs.size()); + for (unsigned I = 0; I < Outs.size(); ++I) + ROuts[I] = Outs[I].getArgument(); + Output = TemplateArgumentLoc( + TemplateArgument::CreatePackCopy(SemaRef.Context, ROuts), + Input.getLocInfo()); + return false; + } + case TemplateArgument::Integral: + case TemplateArgument::NullPtr: + case TemplateArgument::Declaration: { + // Transform a resolved template argument straight to a resolved template + // argument. We get here when substituting into an already-substituted + // template type argument during concept satisfaction checking. + QualType T = Arg.getNonTypeTemplateArgumentType(); + QualType NewT = TransformType(T); + assert(!NewT.isNull()); + if (NewT == T) + Output = Input; + else if (Arg.getKind() == TemplateArgument::Integral) + Output = TemplateArgumentLoc( + TemplateArgument(SemaRef.Context, Arg.getAsIntegral(), NewT), + Input.getLocInfo()); + else if (Arg.getKind() == TemplateArgument::NullPtr) + Output = TemplateArgumentLoc(TemplateArgument(NewT, /*IsNullPtr=*/true), + Input.getLocInfo()); + else + Output = TemplateArgumentLoc(TemplateArgument(Arg.getAsDecl(), NewT), + Input.getLocInfo()); + return false; + } + + case TemplateArgument::Type: { + if (Arg.isPackExpansion()) { + QualType T = TransformType(Arg.getAsType()); + assert(!T.isNull()); + Output = TemplateArgumentLoc(TemplateArgument(T), Input.getLocInfo()); + return false; + } + TypeSourceInfo *DI = Input.getTypeSourceInfo(); + if (!DI) + DI = InventTypeSourceInfo(Arg.getAsType()); + + DI = TransformType(DI); + if (!DI) + return true; + + Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI); + return false; + } + + case TemplateArgument::Template: { + NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc(); + NamingContextTransformRAII NamingContext(*this, QualifierLoc); + + CXXScopeSpec SS; + SS.Adopt(QualifierLoc); + TemplateName Template = TransformTemplateName(SS, Arg.getAsTemplate(), + Input.getTemplateNameLoc()); + assert(!Template.isNull()); + + Output = TemplateArgumentLoc(SemaRef.Context, TemplateArgument(Template), + QualifierLoc, Input.getTemplateNameLoc()); + return false; + } + + case TemplateArgument::TemplateExpansion: { + Output = TemplateArgumentLoc( + TemplateArgument(Arg.getAsTemplateOrTemplatePattern(), + Arg.getNumTemplateExpansions()), + Input.getLocInfo()); + return false; + } + case TemplateArgument::Expression: { + // FIXME: convert the type of these. + Output = Input; + return false; + } + } + llvm_unreachable("Unexpected TemplateArgument kind"); + } + + template + bool TransformTemplateArguments(InputIterator First, InputIterator Last, + TemplateArgumentListInfo &Outputs, + bool Uneval = true) { + for (; First != Last; ++First) { + TemplateArgumentLoc Out; + if (TransformTemplateArgument(*First, Out, Uneval)) + llvm_unreachable(""); + Outputs.addArgument(Out); + } + return false; + } + + QualType TransformPackExpansionType(TypeLocBuilder &TLB, + PackExpansionTypeLoc TL) { + QualType Pattern = TransformType(TLB, TL.getPatternLoc()); + assert(!Pattern.isNull()); + + QualType Result = TL.getType(); + if (Pattern != TL.getPatternLoc().getType()) { + Result = SemaRef.Context.getPackExpansionType( + Pattern, TL.getTypePtr()->getNumExpansions(), + /*ExpectPackInType=*/false); + } + + PackExpansionTypeLoc NewT = TLB.push(Result); + NewT.setEllipsisLoc(TL.getEllipsisLoc()); + return Result; + } + + bool TransformTypes(llvm::ArrayRef In, + SmallVectorImpl &Out) { + bool Changed = false; + for (unsigned i = 0; i != In.size(); ++i) { + QualType OldType = In[i]; + QualType NewType = TransformType(OldType); + assert(!NewType.isNull()); + Changed |= NewType != OldType; + Out[i] = NewType; + } + return Changed; + } + + QualType TransformFunctionProtoType(TypeLocBuilder &TLB, + FunctionProtoTypeLoc TL) { + const FunctionProtoType *T = TL.getTypePtr(); + + QualType ResultType = TransformType(TLB, TL.getReturnLoc()); + assert(!ResultType.isNull()); + + bool Changed = ResultType != TL.getReturnLoc().getType(); + + SmallVector ParamTypes(T->getNumParams()); + Changed |= TransformTypes(llvm::ArrayRef(T->param_types().begin(), + T->param_types().end()), + ParamTypes); + + FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo(); + + assert(EPI.ExceptionSpec.Type != EST_Uninstantiated && + EPI.ExceptionSpec.Type != EST_Unevaluated); + SmallVector ExceptionStorage( + EPI.ExceptionSpec.Exceptions.size()); + Changed |= TransformTypes(EPI.ExceptionSpec.Exceptions, ParamTypes); + EPI.ExceptionSpec.Exceptions = ExceptionStorage; + + QualType Result = + Changed ? SemaRef.Context.getFunctionType(ResultType, ParamTypes, EPI) + : TL.getType(); + + FunctionProtoTypeLoc NewTL = TLB.push(Result); + NewTL.setLocalRangeBegin(TL.getLocalRangeBegin()); + NewTL.setLParenLoc(TL.getLParenLoc()); + NewTL.setRParenLoc(TL.getRParenLoc()); + NewTL.setExceptionSpecRange(TL.getExceptionSpecRange()); + NewTL.setLocalRangeEnd(TL.getLocalRangeEnd()); + for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i) + NewTL.setParam(i, TL.getParam(i)); + return Result; + } + + bool TransformFunctionTypeParams(ArrayRef ParamTypes, + SmallVectorImpl &OutParamTypes) { + for (unsigned i = 0; i != ParamTypes.size(); ++i) { + QualType NewType = TransformType(ParamTypes[i]); + assert(!NewType.isNull()); + OutParamTypes.push_back(NewType); + } + return false; + } + + QualType TransformAttributedType(TypeLocBuilder &TLB, AttributedTypeLoc TL) { + const AttributedType *T = TL.getTypePtr(); + QualType MT = TransformType(TLB, TL.getModifiedLoc()); + assert(!MT.isNull()); + + const Attr *OldAttr = TL.getAttr(); + const Attr *NewAttr = OldAttr ? TransformAttr(OldAttr) : nullptr; + assert(!OldAttr == !NewAttr); + + // FIXME: Rebuild if Attr changes? + QualType Result = TL.getType(); + if (MT != T->getModifiedType()) { + Result = SemaRef.Context.getAttributedType(TL.getAttrKind(), MT, + T->getEquivalentType()); + } + + AttributedTypeLoc newTL = TLB.push(Result); + newTL.setAttr(NewAttr); + return Result; + } + + QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) { + NestedNameSpecifierLoc NNS; + const AutoType *T = TL.getTypePtr(); + + TemplateArgumentListInfo NewArgs; + if (T->isConstrained()) { + NewArgs.setLAngleLoc(TL.getLAngleLoc()); + NewArgs.setRAngleLoc(TL.getRAngleLoc()); + using Iter = TemplateArgumentLocContainerIterator; + if (TransformTemplateArguments(Iter(TL, 0), Iter(TL, TL.getNumArgs()), + NewArgs)) + llvm_unreachable(""); + } + + QualType Deduced = !T->getDeducedType().isNull() + ? TransformType(T->getDeducedType()) + : QualType(); + + QualType Result = TL.getType(); + if (Deduced != T->getDeducedType()) { + NNS = TL.getNestedNameSpecifierLoc(); + NamingContextTransformRAII NamingContext(*this, NNS); + // FIXME: Maybe don't rebuild if all template arguments are the same. + llvm::SmallVector TypeConstraintArgs(NewArgs.size()); + for (const auto &ArgLoc : NewArgs.arguments()) + TypeConstraintArgs.push_back(ArgLoc.getArgument()); + Result = SemaRef.Context.getAutoType( + Deduced, T->getKeyword(), T->isInstantiationDependentType(), + T->containsUnexpandedParameterPack(), T->getTypeConstraintConcept(), + TypeConstraintArgs); + } + + AutoTypeLoc NewTL = TLB.push(Result); + NewTL.setNameLoc(TL.getNameLoc()); + NewTL.setNestedNameSpecifierLoc(NNS); + NewTL.setTemplateKWLoc(TL.getTemplateKWLoc()); + NewTL.setConceptNameLoc(TL.getConceptNameLoc()); + NewTL.setFoundDecl(TL.getFoundDecl()); + NewTL.setLAngleLoc(TL.getLAngleLoc()); + NewTL.setRAngleLoc(TL.getRAngleLoc()); + NewTL.setRParenLoc(TL.getRParenLoc()); + for (unsigned I = 0; I < NewTL.getNumArgs(); ++I) + NewTL.setArgLocInfo(I, NewArgs[I].getLocInfo()); + return Result; + } +}; +} // namespace + +QualType Sema::resugar(const NestedNameSpecifier *NNS, QualType T) { + if (!getLangOpts().Resugar) + return T; + Resugarer R(*this); + Resugarer::NamingContextRAII NamingScope(R, NNS); + return R.TransformType(T); +} + +bool Sema::resugarTemplateArguments(NestedNameSpecifier *NNS, + TemplateArgumentListInfo &Args) { + if (!getLangOpts().Resugar) + return false; + + Resugarer R(*this); + Resugarer::NamingContextRAII NamingScope(R, NNS); + TemplateArgumentListInfo NewArgs; + if (R.TransformTemplateArguments(Args.arguments().begin(), + Args.arguments().end(), NewArgs)) + llvm_unreachable("Unexpected failure"); + for (unsigned I = 0; I < Args.size(); ++I) + if (!Args[I].getArgument().structurallyEquals(NewArgs[I].getArgument())) { + Args = std::move(NewArgs); + return true; + } + return false; +} + +static QualType getResugaredTemplateSpecializationType( + Sema &S, NestedNameSpecifier *NNS, TemplateName Template, + TemplateArgumentListInfo &Args, QualType Underlying = QualType()) { + if (!S.getLangOpts().Resugar) + return S.Context.getTemplateSpecializationType(Template, Args, Underlying); + Resugarer R(S); + Resugarer::NamingContextRAII NamingScope(R, NNS); + const auto *TD = Template.getAsTemplateDecl(); + TemplateArgumentListInfo NewArgs; + QualType Result = R.TransformTemplateSpecializationType( + Template, TD && TD->isTypeAlias(), Args.arguments().begin(), + Args.arguments().end(), NewArgs, Underlying); + Args = std::move(NewArgs); + return Result; +} + /// \brief Determine whether the declaration found is acceptable as the name /// of a template and, if so, return that template declaration. Otherwise, /// returns null. @@ -1591,7 +2484,8 @@ TemplateArgument Converted; ExprResult DefaultRes = - CheckTemplateArgument(Param, Param->getType(), Default, Converted); + CheckTemplateArgument(Param, Param->getType(), Default, Converted, + CTAK_Specified, /*DontCanonicalize=*/false); if (DefaultRes.isInvalid()) { Param->setInvalidDecl(); return Param; @@ -3442,7 +4336,8 @@ } static QualType -checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD, +checkBuiltinTemplateIdType(Sema &SemaRef, NestedNameSpecifier *NNS, + TemplateName Name, BuiltinTemplateDecl *BTD, const SmallVectorImpl &Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs) { @@ -3474,7 +4369,17 @@ TemplateArgumentListInfo SyntheticTemplateArgs; // The type argument gets reused as the first template argument in the // synthetic template argument list. - SyntheticTemplateArgs.addArgument(TemplateArgs[1]); + auto *TTPD = + cast(BTD->getTemplateParameters()->getParam(1)); + const auto *TTP = cast( + SemaRef.Context.getTemplateTypeParmType(0, 1, false, TTPD)); + QualType OrigType = TemplateArgs[1].getArgument().getAsType(); + QualType SyntheticType = + SemaRef.Context.getSubstTemplateTypeParmType(TTP, OrigType, None); + SyntheticTemplateArgs.addArgument( + TemplateArgumentLoc(TemplateArgument(SyntheticType), + SemaRef.Context.getTrivialTypeSourceInfo( + SyntheticType, TemplateArgs[1].getLocation()))); // Expand N into 0 ... N-1. for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned()); I < NumArgs; ++I) { @@ -3484,8 +4389,10 @@ } // The first template argument will be reused as the template decl that // our synthetic template arguments will be applied to. - return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(), - TemplateLoc, SyntheticTemplateArgs); + QualType Result = SemaRef.CheckTemplateIdType( + NNS, Converted[0].getAsTemplate(), TemplateLoc, SyntheticTemplateArgs); + return SemaRef.Context.getTemplateSpecializationType(Name, TemplateArgs, + Result); } case BTK__type_pack_element: @@ -3507,8 +4414,10 @@ } // We simply return the type at index `Index`. + // FIXME: test this auto Nth = std::next(Ts.pack_begin(), Index.getExtValue()); - return Nth->getAsType(); + return getResugaredTemplateSpecializationType( + SemaRef, NNS, Name, TemplateArgs, Nth->getAsType()); } llvm_unreachable("unexpected BuiltinTemplateDecl!"); } @@ -3652,20 +4561,20 @@ return { FailedCond, Description }; } -QualType Sema::CheckTemplateIdType(TemplateName Name, +QualType Sema::CheckTemplateIdType(NestedNameSpecifier *NNS, TemplateName Name, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs) { DependentTemplateName *DTN = Name.getUnderlying().getAsDependentTemplateName(); - if (DTN && DTN->isIdentifier()) + if (DTN && DTN->isIdentifier()) { // When building a template-id where the template-name is dependent, // assume the template is a type template. Either our assumption is // correct, or the code is ill-formed and will be diagnosed when the // dependent name is substituted. - return Context.getDependentTemplateSpecializationType(ETK_None, - DTN->getQualifier(), - DTN->getIdentifier(), - TemplateArgs); + resugarTemplateArguments(NNS, TemplateArgs); + return Context.getDependentTemplateSpecializationType( + ETK_None, DTN->getQualifier(), DTN->getIdentifier(), TemplateArgs); + } if (Name.getAsAssumedTemplateName() && resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc)) @@ -3677,7 +4586,8 @@ // We might have a substituted template template parameter pack. If so, // build a template specialization type for it. if (Name.getAsSubstTemplateTemplateParmPack()) - return Context.getTemplateSpecializationType(Name, TemplateArgs); + return getResugaredTemplateSpecializationType(*this, NNS, Name, + TemplateArgs); Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name; @@ -3843,14 +4753,15 @@ assert(isa(CanonType) && "type of non-dependent specialization is not a RecordType"); } else if (auto *BTD = dyn_cast(Template)) { - CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc, - TemplateArgs); + return checkBuiltinTemplateIdType(*this, NNS, Name, BTD, Converted, + TemplateLoc, TemplateArgs); } // Build the fully-sugared type for this class template // specialization, which refers back to the class template // specialization we created or found. - return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType); + return getResugaredTemplateSpecializationType(*this, NNS, Name, TemplateArgs, + CanonType); } void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName, @@ -3915,9 +4826,9 @@ if (SS.isInvalid()) return true; - if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) { - DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false); + const auto *LookupCtx = computeDeclContext(SS, /*EnteringContext*/ false); + if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) { // C++ [temp.res]p3: // A qualified-id that refers to a type and in which the // nested-name-specifier depends on a template-parameter (14.6.2) @@ -3961,6 +4872,8 @@ translateTemplateArguments(TemplateArgsIn, TemplateArgs); if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { + assert(SS.getScopeRep() == DTN->getQualifier()); + resugarTemplateArguments(SS.getScopeRep(), TemplateArgs); QualType T = Context.getDependentTemplateSpecializationType(ETK_None, DTN->getQualifier(), @@ -3981,14 +4894,15 @@ return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); } - QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs); - if (Result.isNull()) + QualType T = CheckTemplateIdType(SS.getScopeRep(), Template, TemplateIILoc, + TemplateArgs); + if (T.isNull()) return true; // Build type-source information. TypeLocBuilder TLB; - TemplateSpecializationTypeLoc SpecTL - = TLB.push(Result); + TemplateSpecializationTypeLoc SpecTL = + TLB.push(T); SpecTL.setTemplateKeywordLoc(TemplateKWLoc); SpecTL.setTemplateNameLoc(TemplateIILoc); SpecTL.setLAngleLoc(LAngleLoc); @@ -4000,14 +4914,12 @@ // constructor or destructor name (in such a case, the scope specifier // will be attached to the enclosing Decl or Expr node). if (SS.isNotEmpty() && !IsCtorOrDtorName) { - // Create an elaborated-type-specifier containing the nested-name-specifier. - Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result); - ElaboratedTypeLoc ElabTL = TLB.push(Result); + T = Context.getElaboratedType(ETK_None, SS.getScopeRep(), T); + ElaboratedTypeLoc ElabTL = TLB.push(T); ElabTL.setElaboratedKeywordLoc(SourceLocation()); ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); } - - return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); + return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); } TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK, @@ -4035,6 +4947,8 @@ = TypeWithKeyword::getKeywordForTagTypeKind(TagKind); if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { + assert(SS.getScopeRep() == DTN->getQualifier()); + resugarTemplateArguments(SS.getScopeRep(), TemplateArgs); QualType T = Context.getDependentTemplateSpecializationType(Keyword, DTN->getQualifier(), DTN->getIdentifier(), @@ -4066,30 +4980,15 @@ Diag(TAT->getLocation(), diag::note_declared_at); } - QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); - if (Result.isNull()) + QualType T = CheckTemplateIdType(SS.getScopeRep(), Template, TemplateLoc, + TemplateArgs); + if (T.isNull()) return TypeResult(true); - // Check the tag kind - if (const RecordType *RT = Result->getAs()) { - RecordDecl *D = RT->getDecl(); - - IdentifierInfo *Id = D->getIdentifier(); - assert(Id && "templated class must have an identifier"); - - if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition, - TagLoc, Id)) { - Diag(TagLoc, diag::err_use_with_wrong_tag) - << Result - << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName()); - Diag(D->getLocation(), diag::note_previous_use); - } - } - // Provide source-location information for the template specialization. TypeLocBuilder TLB; - TemplateSpecializationTypeLoc SpecTL - = TLB.push(Result); + TemplateSpecializationTypeLoc SpecTL = + TLB.push(T); SpecTL.setTemplateKeywordLoc(TemplateKWLoc); SpecTL.setTemplateNameLoc(TemplateLoc); SpecTL.setLAngleLoc(LAngleLoc); @@ -4099,11 +4998,29 @@ // Construct an elaborated type containing the nested-name-specifier (if any) // and tag keyword. - Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result); - ElaboratedTypeLoc ElabTL = TLB.push(Result); + T = Context.getElaboratedType(Keyword, SS.getScopeRep(), T); + ElaboratedTypeLoc ElabTL = TLB.push(T); ElabTL.setElaboratedKeywordLoc(TagLoc); ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); - return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); + + // Check the tag kind + if (const RecordType *RT = T->getAs()) { + RecordDecl *D = RT->getDecl(); + + IdentifierInfo *Id = D->getIdentifier(); + assert(Id && "templated class must have an identifier"); + + if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition, TagLoc, + Id)) { + Diag(TagLoc, diag::err_use_with_wrong_tag) + << T + << FixItHint::CreateReplacement(SourceRange(TagLoc), + D->getKindName()); + Diag(D->getLocation(), diag::note_previous_use); + } + } + + return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); } static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, @@ -4955,9 +5872,9 @@ return TNK_Non_template; } -bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, - TemplateArgumentLoc &AL, - SmallVectorImpl &Converted) { +bool Sema::CheckTemplateTypeArgument( + TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL, + SmallVectorImpl &Converted, bool DontCanonicalize) { const TemplateArgument &Arg = AL.getArgument(); QualType ArgType; TypeSourceInfo *TSI = nullptr; @@ -5051,7 +5968,8 @@ return true; // Add the converted template type argument. - ArgType = Context.getCanonicalType(ArgType); + if (!DontCanonicalize) + ArgType = Context.getCanonicalType(ArgType); // Objective-C ARC: // If an explicitly-specified template argument type is a lifetime type @@ -5370,17 +6288,14 @@ /// explicitly written, deduced, etc. /// /// \returns true on error, false otherwise. -bool Sema::CheckTemplateArgument(NamedDecl *Param, - TemplateArgumentLoc &Arg, - NamedDecl *Template, - SourceLocation TemplateLoc, - SourceLocation RAngleLoc, - unsigned ArgumentPackIndex, - SmallVectorImpl &Converted, - CheckTemplateArgumentKind CTAK) { +bool Sema::CheckTemplateArgument( + NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, + SourceLocation TemplateLoc, SourceLocation RAngleLoc, + unsigned ArgumentPackIndex, SmallVectorImpl &Converted, + CheckTemplateArgumentKind CTAK, bool DontCanonizalize) { // Check template type parameters. if (TemplateTypeParmDecl *TTP = dyn_cast(Param)) - return CheckTemplateTypeArgument(TTP, Arg, Converted); + return CheckTemplateTypeArgument(TTP, Arg, Converted, DontCanonizalize); // Check non-type template parameters. if (NonTypeTemplateParmDecl *NTTP =dyn_cast(Param)) { @@ -5433,11 +6348,16 @@ llvm_unreachable("Should never see a NULL template argument here"); case TemplateArgument::Expression: { + Expr *E = Arg.getArgument().getAsExpr(); + // FIXME: Workaround for double conversion + if (isa(E)) { + Converted.push_back(Arg.getArgument()); + break; + } TemplateArgument Result; unsigned CurSFINAEErrors = NumSFINAEErrors; - ExprResult Res = - CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(), - Result, CTAK); + ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK, + DontCanonizalize); if (Res.isInvalid()) return true; // If the current template argument causes an error, give up now. @@ -5497,7 +6417,8 @@ } TemplateArgument Result; - E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result); + E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result, + CTAK_Specified, DontCanonizalize); if (E.isInvalid()) return true; @@ -5659,7 +6580,8 @@ TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl &Converted, - bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) { + bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied, + bool DontCanonicalize) { if (ConstraintsNotSatisfied) *ConstraintsNotSatisfied = false; @@ -5717,9 +6639,9 @@ if (ArgIdx < NumArgs) { // Check the template argument we were given. - if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, - TemplateLoc, RAngleLoc, - ArgumentPack.size(), Converted)) + if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc, + RAngleLoc, ArgumentPack.size(), Converted, + CTAK_Specified, DontCanonicalize)) return true; bool PackExpansionIntoNonPack = @@ -5878,8 +6800,8 @@ return true; // Check the default template argument. - if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, - RAngleLoc, 0, Converted)) + if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0, + Converted, CTAK_Specified, DontCanonicalize)) return true; // Core issue 150 (assumed resolution): if this is a template template @@ -6404,12 +7326,9 @@ /// Checks whether the given template argument is the address /// of an object or function according to C++ [temp.arg.nontype]p1. -static bool -CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, - NonTypeTemplateParmDecl *Param, - QualType ParamType, - Expr *ArgIn, - TemplateArgument &Converted) { +static bool CheckTemplateArgumentAddressOfObjectOrFunction( + Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, + TemplateArgument &Converted, bool DontCanonicalize) { bool Invalid = false; Expr *Arg = ArgIn; QualType ArgType = Arg->getType(); @@ -6513,8 +7432,9 @@ Entity)) { case NPV_NullPointer: S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); - Converted = TemplateArgument(S.Context.getCanonicalType(ParamType), - /*isNullPtr=*/true); + Converted = TemplateArgument( + DontCanonicalize ? ParamType : S.Context.getCanonicalType(ParamType), + /*isNullPtr=*/true); return false; case NPV_Error: @@ -6658,19 +7578,18 @@ return true; // Create the template argument. - Converted = TemplateArgument(cast(Entity->getCanonicalDecl()), - S.Context.getCanonicalType(ParamType)); + Converted = TemplateArgument( + cast(DontCanonicalize ? Entity : Entity->getCanonicalDecl()), + DontCanonicalize ? ParamType : S.Context.getCanonicalType(ParamType)); S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false); return false; } /// Checks whether the given template argument is a pointer to /// member constant according to C++ [temp.arg.nontype]p1. -static bool CheckTemplateArgumentPointerToMember(Sema &S, - NonTypeTemplateParmDecl *Param, - QualType ParamType, - Expr *&ResultArg, - TemplateArgument &Converted) { +static bool CheckTemplateArgumentPointerToMember( + Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, + Expr *&ResultArg, TemplateArgument &Converted, bool DontCanonicalize) { bool Invalid = false; Expr *Arg = ResultArg; @@ -6720,8 +7639,10 @@ if (Arg->isTypeDependent() || Arg->isValueDependent()) { Converted = TemplateArgument(Arg); } else { - VD = cast(VD->getCanonicalDecl()); - Converted = TemplateArgument(VD, ParamType); + Converted = TemplateArgument( + cast(DontCanonicalize ? VD : VD->getCanonicalDecl()), + DontCanonicalize ? ParamType + : S.Context.getCanonicalType(ParamType)); } return Invalid; } @@ -6739,8 +7660,9 @@ return true; case NPV_NullPointer: S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); - Converted = TemplateArgument(S.Context.getCanonicalType(ParamType), - /*isNullPtr*/true); + Converted = TemplateArgument( + DontCanonicalize ? ParamType : S.Context.getCanonicalType(ParamType), + /*isNullPtr*/ true); return false; case NPV_NotNullPointer: break; @@ -6779,8 +7701,10 @@ if (Arg->isTypeDependent() || Arg->isValueDependent()) { Converted = TemplateArgument(Arg); } else { - ValueDecl *D = cast(DRE->getDecl()->getCanonicalDecl()); - Converted = TemplateArgument(D, S.Context.getCanonicalType(ParamType)); + ValueDecl *D = DRE->getDecl(); + Converted = TemplateArgument( + DontCanonicalize ? D : cast(D->getCanonicalDecl()), + DontCanonicalize ? ParamType : S.Context.getCanonicalType(ParamType)); } return Invalid; } @@ -6802,7 +7726,8 @@ ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *Arg, TemplateArgument &Converted, - CheckTemplateArgumentKind CTAK) { + CheckTemplateArgumentKind CTAK, + bool DontCanonicalize) { SourceLocation StartLoc = Arg->getBeginLoc(); // If the parameter type somehow involves auto, deduce the type now. @@ -6947,7 +7872,8 @@ Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) { NamedDecl *ND = cast(InnerArg)->getDecl(); if (auto *TPO = dyn_cast(ND)) { - Converted = TemplateArgument(TPO, CanonParamType); + Converted = TemplateArgument(TPO, DontCanonicalize ? ParamType + : CanonParamType); return Arg; } if (isa(ND)) { @@ -6976,14 +7902,17 @@ switch (Value.getKind()) { case APValue::None: assert(ParamType->isNullPtrType()); - Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true); + Converted = TemplateArgument( + DontCanonicalize ? ParamType : CanonParamType, /*isNullPtr*/ true); break; case APValue::Indeterminate: llvm_unreachable("result of constant evaluation should be initialized"); break; case APValue::Int: assert(ParamType->isIntegralOrEnumerationType()); - Converted = TemplateArgument(Context, Value.getInt(), CanonParamType); + Converted = + TemplateArgument(Context, Value.getInt(), + DontCanonicalize ? ParamType : CanonParamType); break; case APValue::MemberPointer: { assert(ParamType->isMemberPointerType()); @@ -6997,9 +7926,10 @@ return ExprError(); } + QualType T = DontCanonicalize ? ParamType : CanonParamType; auto *VD = const_cast(Value.getMemberPointerDecl()); - Converted = VD ? TemplateArgument(VD, CanonParamType) - : TemplateArgument(CanonParamType, /*isNullPtr*/true); + Converted = VD ? TemplateArgument(VD, T) + : TemplateArgument(T, /*isNullPtr=*/true); break; } case APValue::LValue: { @@ -7039,17 +7969,19 @@ "null reference should not be a constant expression"); assert((!VD || !ParamType->isNullPtrType()) && "non-null value of type nullptr_t?"); - Converted = VD ? TemplateArgument(VD, CanonParamType) - : TemplateArgument(CanonParamType, /*isNullPtr*/true); + QualType T = DontCanonicalize ? ParamType : CanonParamType; + Converted = VD ? TemplateArgument(VD, T) + : TemplateArgument(T, /*isNullPtr=*/true); break; } case APValue::Struct: - case APValue::Union: + case APValue::Union: { // Get or create the corresponding template parameter object. - Converted = TemplateArgument( - Context.getTemplateParamObjectDecl(CanonParamType, Value), - CanonParamType); + QualType T = DontCanonicalize ? ParamType : CanonParamType; + Converted = + TemplateArgument(Context.getTemplateParamObjectDecl(T, Value), T); break; + } case APValue::AddrLabelDiff: return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff); case APValue::FixedPoint: @@ -7113,8 +8045,9 @@ ? Context.getIntWidth(IntegerType) : Context.getTypeSize(IntegerType)); - Converted = TemplateArgument(Context, Value, - Context.getCanonicalType(ParamType)); + Converted = TemplateArgument( + Context, Value, + DontCanonicalize ? ParamType : Context.getCanonicalType(ParamType)); return ArgResult; } @@ -7188,9 +8121,13 @@ return Arg; } - QualType IntegerType = Context.getCanonicalType(ParamType); - if (const EnumType *Enum = IntegerType->getAs()) - IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType()); + QualType IntegerType = + DontCanonicalize ? ParamType : Context.getCanonicalType(ParamType); + if (const EnumType *Enum = IntegerType->getAs()) { + IntegerType = Enum->getDecl()->getIntegerType(); + if (!DontCanonicalize) + IntegerType = Context.getCanonicalType(IntegerType); + } if (ParamType->isBooleanType()) { // Value must be zero or one. @@ -7236,10 +8173,10 @@ } } + QualType T = + DontCanonicalize ? ParamType : Context.getCanonicalType(ParamType); Converted = TemplateArgument(Context, Value, - ParamType->isEnumeralType() - ? Context.getCanonicalType(ParamType) - : IntegerType); + ParamType->isEnumeralType() ? T : IntegerType); return Arg; } @@ -7284,15 +8221,14 @@ } if (!ParamType->isMemberPointerType()) { - if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, - ParamType, - Arg, Converted)) + if (CheckTemplateArgumentAddressOfObjectOrFunction( + *this, Param, ParamType, Arg, Converted, DontCanonicalize)) return ExprError(); return Arg; } if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg, - Converted)) + Converted, DontCanonicalize)) return ExprError(); return Arg; } @@ -7305,9 +8241,8 @@ assert(ParamType->getPointeeType()->isIncompleteOrObjectType() && "Only object pointers allowed here"); - if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, - ParamType, - Arg, Converted)) + if (CheckTemplateArgumentAddressOfObjectOrFunction( + *this, Param, ParamType, Arg, Converted, DontCanonicalize)) return ExprError(); return Arg; } @@ -7336,9 +8271,8 @@ return ExprError(); } - if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, - ParamType, - Arg, Converted)) + if (CheckTemplateArgumentAddressOfObjectOrFunction( + *this, Param, ParamType, Arg, Converted, DontCanonicalize)) return ExprError(); return Arg; } @@ -7362,8 +8296,9 @@ case NPV_NullPointer: Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); - Converted = TemplateArgument(Context.getCanonicalType(ParamType), - /*isNullPtr*/true); + Converted = TemplateArgument( + DontCanonicalize ? ParamType : Context.getCanonicalType(ParamType), + /*isNullPtr*/ true); return Arg; } } @@ -7373,7 +8308,7 @@ assert(ParamType->isMemberPointerType() && "Only pointers to members remain"); if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg, - Converted)) + Converted, DontCanonicalize)) return ExprError(); return Arg; } @@ -10425,7 +11360,7 @@ // Strangely, non-type results are not ignored by this lookup, so the // program is ill-formed if it finds an injected-class-name. if (TypenameLoc.isValid()) { - auto *LookupRD = + const auto *LookupRD = dyn_cast_or_null(computeDeclContext(SS, false)); if (LookupRD && LookupRD->getIdentifier() == TemplateII) { Diag(TemplateIILoc, @@ -10444,6 +11379,7 @@ // Construct a dependent template specialization type. assert(DTN && "dependent template has non-dependent name?"); assert(DTN->getQualifier() == SS.getScopeRep()); + resugarTemplateArguments(SS.getScopeRep(), TemplateArgs); QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename, DTN->getQualifier(), DTN->getIdentifier(), @@ -10464,7 +11400,8 @@ return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); } - QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs); + QualType T = CheckTemplateIdType(SS.getScopeRep(), Template, TemplateIILoc, + TemplateArgs); if (T.isNull()) return true; @@ -10484,8 +11421,7 @@ TL.setElaboratedKeywordLoc(TypenameLoc); TL.setQualifierLoc(SS.getWithLocInContext(Context)); - TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T); - return CreateParsedType(T, TSI); + return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); } @@ -10691,9 +11627,9 @@ // We found a type. Build an ElaboratedType, since the // typename-specifier was just sugar. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); - return Context.getElaboratedType(Keyword, - QualifierLoc.getNestedNameSpecifier(), - Context.getTypeDeclType(Type)); + return Context.getElaboratedType( + Keyword, QualifierLoc.getNestedNameSpecifier(), + resugar(SS.getScopeRep(), Context.getTypeDeclType(Type))); } // C++ [dcl.type.simple]p2: diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp b/clang/lib/Sema/SemaTemplateDeduction.cpp --- a/clang/lib/Sema/SemaTemplateDeduction.cpp +++ b/clang/lib/Sema/SemaTemplateDeduction.cpp @@ -2567,13 +2567,10 @@ /// Convert the given deduced template argument and add it to the set of /// fully-converted template arguments. -static bool -ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, - DeducedTemplateArgument Arg, - NamedDecl *Template, - TemplateDeductionInfo &Info, - bool IsDeduced, - SmallVectorImpl &Output) { +static bool ConvertDeducedTemplateArgument( + Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template, + TemplateDeductionInfo &Info, bool IsDeduced, + SmallVectorImpl &Output, bool DontCanonicalize) { auto ConvertArg = [&](DeducedTemplateArgument Arg, unsigned ArgumentPackIndex) { // Convert the deduced template argument into a template @@ -2589,7 +2586,8 @@ IsDeduced ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound : Sema::CTAK_Deduced) - : Sema::CTAK_Specified); + : Sema::CTAK_Specified, + DontCanonicalize); }; if (Arg.getKind() == TemplateArgument::Pack) { @@ -2658,13 +2656,14 @@ // FIXME: This should not be a template, but // ClassTemplatePartialSpecializationDecl sadly does not derive from // TemplateDecl. -template +template static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments( Sema &S, TemplateDeclT *Template, bool IsDeduced, SmallVectorImpl &Deduced, TemplateDeductionInfo &Info, SmallVectorImpl &Builder, LocalInstantiationScope *CurrentInstantiationScope = nullptr, - unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) { + unsigned NumAlreadyConverted = 0, bool PartialOverloading = false, + bool DontCanonicalize = false) { TemplateParameterList *TemplateParams = Template->getTemplateParameters(); for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { @@ -2704,7 +2703,8 @@ // We may have deduced this argument, so it still needs to be // checked and converted. if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info, - IsDeduced, Builder)) { + IsDeduced, Builder, + DontCanonicalize)) { Info.Param = makeTemplateParameter(Param); // FIXME: These template arguments are temporary. Free them! Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder)); @@ -2756,7 +2756,7 @@ // Check whether we can actually use the default argument. if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(), 0, Builder, - Sema::CTAK_Specified)) { + Sema::CTAK_Specified, DontCanonicalize)) { Info.Param = makeTemplateParameter( const_cast(TemplateParams->getParam(I))); // FIXME: These template arguments are temporary. Free them! @@ -2813,7 +2813,7 @@ Sema &S, T *Partial, bool IsPartialOrdering, const TemplateArgumentList &TemplateArgs, SmallVectorImpl &Deduced, - TemplateDeductionInfo &Info) { + TemplateDeductionInfo &Info, bool DontCanonicalize) { // Unevaluated SFINAE context. EnterExpressionEvaluationContext Unevaluated( S, Sema::ExpressionEvaluationContext::Unevaluated); @@ -2826,7 +2826,10 @@ // explicitly specified, template argument deduction fails. SmallVector Builder; if (auto Result = ConvertDeducedTemplateArguments( - S, Partial, IsPartialOrdering, Deduced, Info, Builder)) + S, Partial, IsPartialOrdering, Deduced, Info, Builder, + /*CurrentInstantiationScope=*/nullptr, + /*NumAlreadyConverted=*/0U, + /*PartialOverloading=*/false, DontCanonicalize)) return Result; // Form the template argument list from the deduced template arguments. @@ -2835,6 +2838,9 @@ Info.reset(DeducedArgumentList); + if (DontCanonicalize) + return Sema::TDK_Success; + // Substitute the deduced template arguments into the template // arguments of the class template partial specialization, and // verify that the instantiated template arguments are both valid @@ -2898,7 +2904,7 @@ Sema &S, TemplateDecl *Template, bool PartialOrdering, const TemplateArgumentList &TemplateArgs, SmallVectorImpl &Deduced, - TemplateDeductionInfo &Info) { + TemplateDeductionInfo &Info, bool DontCanonicalize) { // Unevaluated SFINAE context. EnterExpressionEvaluationContext Unevaluated( S, Sema::ExpressionEvaluationContext::Unevaluated); @@ -2911,9 +2917,15 @@ // explicitly specified, template argument deduction fails. SmallVector Builder; if (auto Result = ConvertDeducedTemplateArguments( - S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder)) + S, Template, /*IsDeduced*/ PartialOrdering, Deduced, Info, Builder, + /*CurrentInstantiationScope=*/nullptr, + /*NumAlreadyConverted=*/0U, /*PartialOverloading=*/false, + DontCanonicalize)) return Result; + if (DontCanonicalize) + return Sema::TDK_Success; + // Check that we produced the correct argument list. TemplateParameterList *TemplateParams = Template->getTemplateParameters(); for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) { @@ -2943,7 +2955,8 @@ Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, - TemplateDeductionInfo &Info) { + TemplateDeductionInfo &Info, + bool DontCanonicalize) { if (Partial->isInvalidDecl()) return TDK_Invalid; @@ -2984,7 +2997,8 @@ runWithSufficientStackSpace(Info.getLocation(), [&] { Result = ::FinishTemplateArgumentDeduction(*this, Partial, /*IsPartialOrdering=*/false, - TemplateArgs, Deduced, Info); + TemplateArgs, Deduced, Info, + DontCanonicalize); }); return Result; } @@ -3032,9 +3046,10 @@ TemplateDeductionResult Result; runWithSufficientStackSpace(Info.getLocation(), [&] { - Result = ::FinishTemplateArgumentDeduction(*this, Partial, - /*IsPartialOrdering=*/false, - TemplateArgs, Deduced, Info); + Result = ::FinishTemplateArgumentDeduction( + *this, Partial, + /*IsPartialOrdering=*/false, TemplateArgs, Deduced, Info, + /*DontCanonicalize=*/false); // FIXME }); return Result; } @@ -5365,7 +5380,8 @@ S, P2, /*IsPartialOrdering=*/true, TemplateArgumentList(TemplateArgumentList::OnStack, TST1->template_arguments()), - Deduced, Info); + Deduced, Info, + /*DontCanonicalize=*/false); // FIXME }); return AtLeastAsSpecialized; } diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp b/clang/lib/Sema/SemaTemplateInstantiate.cpp --- a/clang/lib/Sema/SemaTemplateInstantiate.cpp +++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp @@ -1640,9 +1640,11 @@ // Type=decltype(2))) // The call to CheckTemplateArgument here produces the ImpCast. TemplateArgument Converted; - if (SemaRef.CheckTemplateArgument(E->getParameter(), SubstType, - SubstReplacement.get(), - Converted).isInvalid()) + if (SemaRef + .CheckTemplateArgument( + E->getParameter(), SubstType, SubstReplacement.get(), Converted, + Sema::CTAK_Specified, /*DontCanonicalize=*/false) + .isInvalid()) return true; return transformNonTypeTemplateParmRef(E->getParameter(), E->getExprLoc(), Converted); diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp --- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp +++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp @@ -6163,7 +6163,8 @@ Args.addArgument( getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc)); } - QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args); + QualType T = + CheckTemplateIdType(nullptr, TemplateName(TD), Loc, Args); if (T.isNull()) return nullptr; auto *SubstRecord = T->getAsCXXRecordDecl(); diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h --- a/clang/lib/Sema/TreeTransform.h +++ b/clang/lib/Sema/TreeTransform.h @@ -1009,7 +1009,8 @@ /// By default, performs semantic analysis when building the template /// specialization type. Subclasses may override this routine to provide /// different behavior. - QualType RebuildTemplateSpecializationType(TemplateName Template, + QualType RebuildTemplateSpecializationType(NestedNameSpecifier *NNS, + TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &Args); @@ -1068,8 +1069,8 @@ // Otherwise, make an elaborated type wrapping a non-dependent // specialization. - QualType T = - getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args); + QualType T = getDerived().RebuildTemplateSpecializationType( + SS.getScopeRep(), InstName, NameLoc, Args); if (T.isNull()) return QualType(); if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr) @@ -4895,7 +4896,7 @@ return TL; TypeSourceInfo *TSI = - TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS); + getDerived().TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS); if (TSI) return TSI->getTypeLoc(); return TypeLoc(); @@ -4910,8 +4911,8 @@ if (getDerived().AlreadyTransformed(TSInfo->getType())) return TSInfo; - return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType, - UnqualLookup, SS); + return getDerived().TransformTSIInObjectScope(TSInfo->getTypeLoc(), + ObjectType, UnqualLookup, SS); } template @@ -6694,10 +6695,8 @@ // FIXME: maybe don't rebuild if all the template arguments are the same. - QualType Result = - getDerived().RebuildTemplateSpecializationType(Template, - TL.getTemplateNameLoc(), - NewTemplateArgs); + QualType Result = getDerived().RebuildTemplateSpecializationType( + nullptr, Template, TL.getTemplateNameLoc(), NewTemplateArgs); if (!Result.isNull()) { // Specializations of template template parameters are represented as @@ -6770,10 +6769,8 @@ return Result; } - QualType Result - = getDerived().RebuildTemplateSpecializationType(Template, - TL.getTemplateNameLoc(), - NewTemplateArgs); + QualType Result = getDerived().RebuildTemplateSpecializationType( + SS.getScopeRep(), Template, TL.getTemplateNameLoc(), NewTemplateArgs); if (!Result.isNull()) { /// FIXME: Wrap this in an elaborated-type-specifier? @@ -14706,12 +14703,12 @@ return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc); } -template +template QualType TreeTransform::RebuildTemplateSpecializationType( - TemplateName Template, - SourceLocation TemplateNameLoc, - TemplateArgumentListInfo &TemplateArgs) { - return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs); + NestedNameSpecifier *NNS, TemplateName Template, + SourceLocation TemplateNameLoc, TemplateArgumentListInfo &TemplateArgs) { + return SemaRef.CheckTemplateIdType(NNS, Template, TemplateNameLoc, + TemplateArgs); } template diff --git a/clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/dcl.type.elab/p3.cpp b/clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/dcl.type.elab/p3.cpp --- a/clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/dcl.type.elab/p3.cpp +++ b/clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/dcl.type.elab/p3.cpp @@ -38,8 +38,8 @@ void b1(struct B); void b2(class B); -void b3(union B); // expected-error {{use of 'B' with tag type that does not match previous declaration}} -//void b4(enum B); // this just doesn't parse; you can't template an enum directly +void b3(union B); // expected-error {{use of 'union B' with tag type that does not match previous declaration}} +// void b4(enum B); // this just doesn't parse; you can't template an enum directly void c1(struct B::Member); void c2(class B::Member); diff --git a/clang/test/CXX/temp/temp.deduct.guide/p3.cpp b/clang/test/CXX/temp/temp.deduct.guide/p3.cpp --- a/clang/test/CXX/temp/temp.deduct.guide/p3.cpp +++ b/clang/test/CXX/temp/temp.deduct.guide/p3.cpp @@ -33,7 +33,7 @@ }; A(int) -> int; // expected-error {{deduced type 'int' of deduction guide is not a specialization of template 'A'}} -template A(T) -> B; // expected-error {{deduced type 'B' (aka 'A') of deduction guide is not written as a specialization of template 'A'}} +template A(T)->B; // expected-error {{deduced type 'B' (aka 'A') of deduction guide is not written as a specialization of template 'A'}} template A(T*) -> const A; // expected-error {{deduced type 'const A' of deduction guide is not a specialization of template 'A'}} // A deduction-guide shall be declared in the same scope as the corresponding diff --git a/clang/test/CodeGenCXX/mangle-ms-back-references-pr13207.cpp b/clang/test/CodeGenCXX/mangle-ms-back-references-pr13207.cpp --- a/clang/test/CodeGenCXX/mangle-ms-back-references-pr13207.cpp +++ b/clang/test/CodeGenCXX/mangle-ms-back-references-pr13207.cpp @@ -1,4 +1,4 @@ -// RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 | FileCheck %s +// RUN: %clang_cc1 -fno-resugar -emit-llvm %s -o - -triple=i386-pc-win32 | FileCheck %s template class A {}; @@ -220,6 +220,7 @@ class T20> struct Food {}; +// FIXME: Should implement resugaring cache for this. using B0 = Food; using B1 = Food; using B2 = Food; diff --git a/clang/test/CodeGenCXX/pr29160.cpp b/clang/test/CodeGenCXX/pr29160.cpp --- a/clang/test/CodeGenCXX/pr29160.cpp +++ b/clang/test/CodeGenCXX/pr29160.cpp @@ -1,8 +1,9 @@ -// RUN: %clang_cc1 -std=c++11 -triple i686-linux-gnu %s -o /dev/null -S -emit-llvm +// RUN: %clang_cc1 -std=c++11 -fno-resugar -triple i686-linux-gnu %s -o /dev/null -S -emit-llvm // // This test's failure mode is running ~forever. (For some value of "forever" // that's greater than 25 minutes on my machine) +// FIXME: Should implement resugaring cache for this. template struct Foo { template diff --git a/clang/test/Misc/diag-template-diffing.cpp b/clang/test/Misc/diag-template-diffing.cpp --- a/clang/test/Misc/diag-template-diffing.cpp +++ b/clang/test/Misc/diag-template-diffing.cpp @@ -257,24 +257,21 @@ int k9 = f9(V9()); // CHECK-ELIDE-NOTREE: no matching function for call to 'f9' -// CHECK-ELIDE-NOTREE: candidate function not viable: no known conversion from 'S9<[2 * ...], S9<[2 * ...], double>>' to 'S9<[2 * ...], S9<[2 * ...], const double>>' for 1st argument +// CHECK-ELIDE-NOTREE: candidate function not viable: no known conversion from 'S9<[2 * ...], U9>' to 'S9<[2 * ...], U9>' for 1st argument // CHECK-NOELIDE-NOTREE: no matching function for call to 'f9' -// CHECK-NOELIDE-NOTREE: candidate function not viable: no known conversion from 'S9>' to 'S9>' for 1st argument +// CHECK-NOELIDE-NOTREE: candidate function not viable: no known conversion from 'S9>' to 'S9>' for 1st argument // CHECK-ELIDE-TREE: no matching function for call to 'f9' // CHECK-ELIDE-TREE: candidate function not viable: no known conversion from argument type to parameter type for 1st argument // CHECK-ELIDE-TREE: S9< -// CHECK-ELIDE-TREE: [2 * ...], -// CHECK-ELIDE-TREE: S9< -// CHECK-ELIDE-TREE: [2 * ...], +// CHECK-ELIDE-TREE: [2 * ...], +// CHECK-ELIDE-TREE: U9< // CHECK-ELIDE-TREE: [double != const double]>> // CHECK-NOELIDE-TREE: no matching function for call to 'f9' // CHECK-NOELIDE-TREE: candidate function not viable: no known conversion from argument type to parameter type for 1st argument // CHECK-NOELIDE-TREE: S9< -// CHECK-NOELIDE-TREE: int, -// CHECK-NOELIDE-TREE: char, -// CHECK-NOELIDE-TREE: S9< -// CHECK-NOELIDE-TREE: int, -// CHECK-NOELIDE-TREE: char, +// CHECK-NOELIDE-TREE: int, +// CHECK-NOELIDE-TREE: char, +// CHECK-NOELIDE-TREE: U9< // CHECK-NOELIDE-TREE: [double != const double]>> template class class_types {}; diff --git a/clang/test/Sema/resugar.cpp b/clang/test/Sema/resugar.cpp new file mode 100644 --- /dev/null +++ b/clang/test/Sema/resugar.cpp @@ -0,0 +1,156 @@ +// RUN: %clang_cc1 -std=c++2b -verify %s +// expected-no-diagnostics + +static constexpr int alignment = 64; // Suitable large alignment. + +struct Baz {}; +using Bar [[gnu::aligned(alignment)]] = Baz; +using Int [[gnu::aligned(alignment)]] = int; + +#define TEST(X) static_assert(alignof(X) == alignment) +#define TEST_NOT(X) static_assert(alignof(X) != alignment) + +// Sanity checks. +TEST_NOT(Baz); +TEST(Bar); + +namespace t1 { +template struct foo { using type = T; }; +template struct foo { using type = U; }; + +TEST(typename foo::type); +TEST(typename foo::type); +} // namespace t1 + +namespace t2 { +template struct foo1 { using type = T; }; +template struct foo2 { using type = typename foo1<1, T>::type; }; +TEST(typename foo2::type); +} // namespace t2 + +namespace t3 { +template struct foo1 { + template struct foo2 { using type1 = T; }; + using type2 = typename foo2<1, int>::type1; +}; +TEST(typename foo1::type2); +} // namespace t3 + +namespace t4 { +template struct foo { + template using type1 = T; + using type2 = type1; +}; +TEST(typename foo::type2); +} // namespace t4 + +namespace t5 { +template struct foo { + template using type1 = U; + using type2 = type1<1, T>; +}; +TEST(typename foo::type2); +} // namespace t5 + +namespace t6 { +template struct foo1 { + template struct foo2 { using type = U; }; + using type2 = typename foo2<1, T>::type; +}; +TEST(typename foo1::type2); +}; // namespace t6 + +namespace t7 { +template struct foo { + template using type1 = U; +}; +using type2 = typename foo::template type1<1, Bar>; +TEST(type2); +} // namespace t7 + +namespace t8 { +template struct foo { + using type1 = T; +}; +template using type2 = T; +using type3 = typename type2, int>::type1; +TEST(type3); +} // namespace t8 + +namespace t9 { +template struct Y { + using type1 = A; + using type2 = B; +}; +template using Z = Y; +template struct foo { + template using apply = Z; +}; +using T1 = foo::apply; +TEST_NOT(T1::type1); +TEST(T1::type2); + +using T2 = foo::apply; +TEST(T2::type1); +TEST_NOT(T2::type2); +} // namespace t9 + +namespace t10 { +template struct Y { + using type1 = A1; + using type2 = A2; +}; +template using Z = Y; +template struct foo { + template using bind = Z; +}; +using T1 = foo::bind; +TEST_NOT(T1::type1); +TEST(T1::type2); + +using T2 = foo::bind; +TEST(T2::type1); +TEST_NOT(T2::type2); +} // namespace t10 + +namespace t11 { +template struct A { using type1 = A2; }; +TEST(A::type1); +} // namespace t11 + +namespace t12 { +template