From 2981926d067e4393797b530165ec4f1a4f4ae79b Mon Sep 17 00:00:00 2001 From: AkshayK Date: Wed, 7 May 2025 11:15:04 -0400 Subject: [PATCH 1/2] add support for building with llvm20 --- CMakeLists.txt | 10 +- lib/AST/ASTBuilder.cpp | 26 +-- lib/AST/CXXToCDecl.cpp | 2 +- lib/AST/StructGenerator.cpp | 19 +- lib/AST/Util.cpp | 10 +- lib/BC/Util.cpp | 29 +-- tools/CMakeLists.txt | 18 +- tools/decomp/Decomp.cpp | 6 +- tools/xref/DeclPrinter.cpp | 132 +++++++++---- tools/xref/StmtPrinter.cpp | 361 +++++++++++++++++++++++++---------- tools/xref/TypePrinter.cpp | 303 +++++++++++++++++++++-------- unittests/AST/ASTBuilder.cpp | 12 +- 12 files changed, 652 insertions(+), 276 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index d484c43f..5322ec9b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -50,9 +50,15 @@ find_package(gflags CONFIG REQUIRED) find_package(glog CONFIG REQUIRED) find_package(Z3 4.8 CONFIG REQUIRED) find_package(doctest CONFIG REQUIRED) -find_package(LLVM CONFIG REQUIRED) +find_package(LLVM 20 CONFIG REQUIRED) +message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}") llvm_map_components_to_libnames(llvm_libs support core irreader bitreader bitwriter) -find_package(Clang CONFIG REQUIRED) + +find_package(MLIR 20 CONFIG REQUIRED) +message(STATUS "Using MLIRConfig.cmake in: ${MLIR_DIR}") + +find_package(Clang 20 CONFIG REQUIRED) +message(STATUS "Using ClangConfig.cmake in: ${Clang_DIR}") # diff --git a/lib/AST/ASTBuilder.cpp b/lib/AST/ASTBuilder.cpp index 9ea4517e..0a1edb86 100644 --- a/lib/AST/ASTBuilder.cpp +++ b/lib/AST/ASTBuilder.cpp @@ -147,7 +147,7 @@ clang::IntegerLiteral *ASTBuilder::CreateIntLit(llvm::APSInt val) { // Extend the literal value based on it's sign if we have a // mismatch between the bit width of the value and inferred type. auto type_size{ctx.getIntWidth(type)}; - if (val.getBitWidth() != type_size && val.getMinSignedBits() < type_size) { + if (val.getBitWidth() != type_size && val.getSignificantBits() < type_size) { val = val.extOrTrunc(type_size); } // Clang does this check in the `clang::IntegerLiteral::Create`, but @@ -159,21 +159,21 @@ clang::IntegerLiteral *ASTBuilder::CreateIntLit(llvm::APSInt val) { clang::CharacterLiteral *ASTBuilder::CreateCharLit(llvm::APInt val) { CHECK(val.getBitWidth() == 8U); - return new (ctx) clang::CharacterLiteral( - val.getLimitedValue(), clang::CharacterLiteral::CharacterKind::Ascii, - ctx.IntTy, clang::SourceLocation()); + return new (ctx) clang::CharacterLiteral(val.getLimitedValue(), + clang::CharacterLiteralKind::Ascii, + ctx.IntTy, clang::SourceLocation()); } clang::CharacterLiteral *ASTBuilder::CreateCharLit(unsigned val) { - return new (ctx) clang::CharacterLiteral( - val, clang::CharacterLiteral::CharacterKind::Ascii, ctx.IntTy, - clang::SourceLocation()); + return new (ctx) + clang::CharacterLiteral(val, clang::CharacterLiteralKind::Ascii, + ctx.IntTy, clang::SourceLocation()); } clang::StringLiteral *ASTBuilder::CreateStrLit(std::string val) { auto type{ctx.getStringLiteralArrayType(ctx.CharTy, val.size())}; return clang::StringLiteral::Create( - ctx, val, clang::StringLiteral::StringKind::Ordinary, + ctx, val, clang::StringLiteralKind::Ordinary, /*Pascal=*/false, type, clang::SourceLocation()); } @@ -199,13 +199,13 @@ clang::Expr *ASTBuilder::CreateFPLit(llvm::APFloat val) { clang::Expr *ASTBuilder::CreateNull() { auto type{ctx.UnsignedIntTy}; - auto val{llvm::APInt::getNullValue(ctx.getTypeSize(type))}; + auto val{llvm::APInt::getZero(ctx.getTypeSize(type))}; auto lit{CreateIntLit(val)}; return CreateCStyleCast(ctx.VoidPtrTy, lit); } clang::Expr *ASTBuilder::CreateUndefInteger(clang::QualType type) { - auto val{llvm::APInt::getNullValue(ctx.getTypeSize(type))}; + auto val{llvm::APInt::getZero(ctx.getTypeSize(type))}; auto lit{CreateIntLit(val)}; return lit; } @@ -253,15 +253,15 @@ clang::ParmVarDecl *ASTBuilder::CreateParamDecl(clang::DeclContext *decl_ctx, clang::RecordDecl *ASTBuilder::CreateStructDecl(clang::DeclContext *decl_ctx, clang::IdentifierInfo *id, clang::RecordDecl *prev_decl) { - return clang::RecordDecl::Create(ctx, clang::TagTypeKind::TTK_Struct, - decl_ctx, clang::SourceLocation(), + return clang::RecordDecl::Create(ctx, clang::TagTypeKind::Struct, decl_ctx, + clang::SourceLocation(), clang::SourceLocation(), id, prev_decl); } clang::RecordDecl *ASTBuilder::CreateUnionDecl(clang::DeclContext *decl_ctx, clang::IdentifierInfo *id, clang::RecordDecl *prev_decl) { - return clang::RecordDecl::Create(ctx, clang::TagTypeKind::TTK_Union, decl_ctx, + return clang::RecordDecl::Create(ctx, clang::TagTypeKind::Union, decl_ctx, clang::SourceLocation(), clang::SourceLocation(), id, prev_decl); } diff --git a/lib/AST/CXXToCDecl.cpp b/lib/AST/CXXToCDecl.cpp index f9d9ae60..642f7836 100644 --- a/lib/AST/CXXToCDecl.cpp +++ b/lib/AST/CXXToCDecl.cpp @@ -25,7 +25,7 @@ static std::string GetMangledName(clang::NamedDecl *decl) { llvm::raw_string_ostream os(buffer); if (auto type_decl = clang::dyn_cast(decl)) { auto type = clang::QualType(type_decl->getTypeForDecl(), 0); - mangler->mangleTypeName(type, os); + mangler->mangleCanonicalTypeName(type, os); } else if (auto cst = clang::dyn_cast(decl)) { mangler->mangleName(clang::GlobalDecl(cst), os); } else if (auto dst = clang::dyn_cast(decl)) { diff --git a/lib/AST/StructGenerator.cpp b/lib/AST/StructGenerator.cpp index 57a0d694..5645c524 100644 --- a/lib/AST/StructGenerator.cpp +++ b/lib/AST/StructGenerator.cpp @@ -119,7 +119,7 @@ static FieldInfo CreatePadding(clang::ASTContext& ast_ctx, auto padding_count{needed_padding / type_size}; auto padding_arr_type{ast_ctx.getConstantArrayType( padding_type, llvm::APInt(64, padding_count), nullptr, - clang::ArrayType::ArraySizeModifier::Normal, 0)}; + clang::ArraySizeModifier::Normal, 0)}; return {name, padding_arr_type, 0}; } } @@ -146,7 +146,8 @@ static unsigned GetStructSize(clang::ASTContext& ast_ctx, ASTBuilder& ast, auto tudecl{ast_ctx.getTranslationUnitDecl()}; auto decl{ast.CreateStructDecl(tudecl, "temp" + std::to_string(count++))}; - clang::AttributeCommonInfo info{clang::SourceLocation{}}; + clang::AttributeCommonInfo info{nullptr, clang::SourceLocation{}, + clang::AttributeCommonInfo::Form::GNU()}; decl->addAttr(clang::PackedAttr::Create(ast_ctx, info)); for (auto& field : fields) { decl->addDecl(FieldInfoToFieldDecl(ast_ctx, ast, decl, field)); @@ -217,7 +218,9 @@ void StructGenerator::VisitFields(clang::RecordDecl* decl, auto field_count{0U}; std::vector fields{}; if (!isUnion) { - clang::AttributeCommonInfo attrinfo{clang::SourceLocation{}}; + clang::AttributeCommonInfo attrinfo{ + nullptr, clang::SourceLocation{}, + clang::AttributeCommonInfo::Form::GNU()}; decl->addAttr(clang::PackedAttr::Create(ast_ctx, attrinfo)); } @@ -333,10 +336,10 @@ clang::QualType StructGenerator::BuildArray(llvm::DICompositeType* a) { VLOG(1) << "BuildArray: " << rellic::LLVMThingToString(a); auto base{BuildType(a->getBaseType())}; auto subrange{llvm::cast(a->getElements()[0])}; - auto* ci = subrange->getCount().get(); - return ast_ctx.getConstantArrayType( - base, llvm::APInt(64, ci->getZExtValue()), nullptr, - clang::ArrayType::ArraySizeModifier::Normal, 0); + auto* ci = llvm::dyn_cast(subrange->getCount()); + return ast_ctx.getConstantArrayType(base, llvm::APInt(64, ci->getZExtValue()), + nullptr, clang::ArraySizeModifier::Normal, + 0); } clang::QualType StructGenerator::BuildDerived(llvm::DIDerivedType* d, @@ -608,7 +611,7 @@ std::vector StructGenerator::GetAccessor(clang::Expr* base, auto idx{field->getFieldIndex()}; auto type{field->getType().getDesugaredType(ast_ctx)}; auto field_offset{layout.getFieldOffset(idx)}; - auto field_size{field->isBitField() ? field->getBitWidthValue(ast_ctx) + auto field_size{field->isBitField() ? field->getBitWidthValue() : ast_ctx.getTypeSize(type)}; if (offset >= field_offset && offset + length <= field_offset + field_size) { diff --git a/lib/AST/Util.cpp b/lib/AST/Util.cpp index 3796d62a..e3f28cf6 100644 --- a/lib/AST/Util.cpp +++ b/lib/AST/Util.cpp @@ -462,11 +462,11 @@ clang::QualType DecompilationContext::GetQualType(llvm::Type *type) { case llvm::Type::PointerTyID: { auto ptr_type{llvm::cast(type)}; - if (ptr_type->isOpaque()) { + auto pointee_type = ptr_type->getContainedType(0); + if (!pointee_type || pointee_type->isVoidTy()) { result = ast_ctx.VoidPtrTy; } else { - result = ast_ctx.getPointerType( - GetQualType(ptr_type->getNonOpaquePointerElementType())); + result = ast_ctx.getPointerType(GetQualType(pointee_type)); } } break; @@ -475,7 +475,7 @@ clang::QualType DecompilationContext::GetQualType(llvm::Type *type) { auto elm{GetQualType(arr->getElementType())}; result = ast_ctx.getConstantArrayType( elm, llvm::APInt(64, arr->getNumElements()), nullptr, - clang::ArrayType::ArraySizeModifier::Normal, 0); + clang::ArraySizeModifier::Normal, 0); } break; case llvm::Type::StructTyID: { @@ -521,7 +521,7 @@ clang::QualType DecompilationContext::GetQualType(llvm::Type *type) { auto vtype{llvm::cast(type)}; auto etype{GetQualType(vtype->getElementType())}; auto ecnt{vtype->getNumElements()}; - auto vkind{clang::VectorType::GenericVector}; + auto vkind{clang::VectorKind::Generic}; result = ast_ctx.getVectorType(etype, ecnt, vkind); } else { THROW() << "Unknown LLVM Type: " << LLVMThingToString(type); diff --git a/lib/BC/Util.cpp b/lib/BC/Util.cpp index 07de89e2..4b2b99d6 100644 --- a/lib/BC/Util.cpp +++ b/lib/BC/Util.cpp @@ -258,13 +258,14 @@ static llvm::LoadInst *ConvertInsertValue(llvm::InsertValueInst *I) { auto F{I->getParent()->getParent()}; auto alloca{new llvm::AllocaInst(I->getType(), DL.getAllocaAddrSpace(), - nullptr, I->getName() + ".iv2mem", I)}; + nullptr, I->getName() + ".iv2mem", + I->getIterator())}; auto aggr_opnd{I->getAggregateOperand()}; auto aggr_ty{aggr_opnd->getType()}; auto ins_opnd{I->getInsertedValueOperand()}; if (!llvm::isa(aggr_opnd)) { - new llvm::StoreInst(aggr_opnd, alloca, I); + new llvm::StoreInst(aggr_opnd, alloca, I->getIterator()); } std::vector indices; indices.push_back(llvm::ConstantInt::get(ctx, llvm::APInt(64, 0, false))); @@ -273,10 +274,10 @@ static llvm::LoadInst *ConvertInsertValue(llvm::InsertValueInst *I) { llvm::ConstantInt::get(ctx, llvm::APInt(sizeof(i) * 8, i))); } auto ptr{llvm::GetElementPtrInst::Create(aggr_opnd->getType(), alloca, - indices, "", I)}; - new llvm::StoreInst(ins_opnd, ptr, I); - auto load{ - new llvm::LoadInst(I->getType(), alloca, I->getName() + ".reload", I)}; + indices, "", I->getIterator())}; + new llvm::StoreInst(ins_opnd, ptr, I->getIterator()); + auto load{new llvm::LoadInst(I->getType(), alloca, I->getName() + ".reload", + I->getIterator())}; I->replaceAllUsesWith(load); I->eraseFromParent(); @@ -359,9 +360,9 @@ void ConvertArrayArguments(llvm::Module &m) { if (orig_func->getReturnType()->isArrayTy()) { auto undef{llvm::UndefValue::get(return_ty)}; for (auto ret : Returns) { - auto wrap{llvm::InsertValueInst::Create(undef, ret->getReturnValue(), - indices, "", ret)}; - auto new_ret{llvm::ReturnInst::Create(ctx, wrap, ret)}; + auto wrap{llvm::InsertValueInst::Create( + undef, ret->getReturnValue(), indices, "", ret->getIterator())}; + auto new_ret{llvm::ReturnInst::Create(ctx, wrap, ret->getIterator())}; ret->eraseFromParent(); } } @@ -397,8 +398,8 @@ void ConvertArrayArguments(llvm::Module &m) { for (auto &old_arg : call->args()) { if (old_arg->getType()->isArrayTy()) { auto undef{llvm::UndefValue::get(conv_types[old_arg->getType()])}; - auto new_arg{llvm::InsertValueInst::Create(undef, old_arg, indices, - "", call)}; + auto new_arg{llvm::InsertValueInst::Create( + undef, old_arg, indices, "", call->getIterator())}; args.push_back(new_arg); } else { args.push_back(old_arg); @@ -407,12 +408,12 @@ void ConvertArrayArguments(llvm::Module &m) { llvm::SmallVector, 16u> mds; auto new_call{llvm::CallInst::Create(new_func->getFunctionType(), new_func, args, call->getName(), - call)}; + call->getIterator())}; call->getAllMetadata(mds); CloneMetadataInto(new_call, mds); if (callee->getReturnType()->isArrayTy()) { - auto unwrap{ - llvm::ExtractValueInst::Create(new_call, indices, "", call)}; + auto unwrap{llvm::ExtractValueInst::Create(new_call, indices, "", + call->getIterator())}; call->replaceAllUsesWith(unwrap); } else { call->replaceAllUsesWith(new_call); diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index 3adea9d6..ec3fced7 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -20,7 +20,7 @@ target_link_libraries(${RELLIC_DECOMP} PRIVATE "${PROJECT_NAME}_cxx_settings" "${PROJECT_NAME}" - gflags::gflags + gflags ) set(RELLIC_DECOMP "${RELLIC_DECOMP}" PARENT_SCOPE) @@ -39,7 +39,7 @@ target_link_libraries(${RELLIC_HEADERGEN} PRIVATE "${PROJECT_NAME}_cxx_settings" "${PROJECT_NAME}" - gflags::gflags + gflags ) set(RELLIC_HEADERGEN "${RELLIC_HEADERGEN}" PARENT_SCOPE) @@ -57,6 +57,14 @@ add_executable(${RELLIC_XREF} "xref/Xref.cpp" ) +include(FetchContent) +FetchContent_Declare(cpp-httplib + GIT_REPOSITORY https://github.com/yhirose/cpp-httplib.git + GIT_TAG v0.20.0 +) +FetchContent_MakeAvailable(cpp-httplib) +set(CPP_HTTPLIB_INCLUDE_DIRS "${cpp-httplib_SOURCE_DIR}") + find_path(CPP_HTTPLIB_INCLUDE_DIRS "httplib.h") target_include_directories(${RELLIC_XREF} PRIVATE ${CPP_HTTPLIB_INCLUDE_DIRS}) @@ -64,7 +72,7 @@ target_link_libraries(${RELLIC_XREF} PRIVATE "${PROJECT_NAME}_cxx_settings" "${PROJECT_NAME}" - gflags::gflags + gflags ) set(RELLIC_XREF "${RELLIC_XREF}" PARENT_SCOPE) @@ -98,7 +106,7 @@ target_link_libraries(${RELLIC_REPL} PRIVATE "${PROJECT_NAME}_cxx_settings" "${PROJECT_NAME}" - gflags::gflags + gflags linenoise ) @@ -117,7 +125,7 @@ target_link_libraries(${RELLIC_DEC2HEX} PRIVATE "${PROJECT_NAME}_cxx_settings" "${PROJECT_NAME}" - gflags::gflags + gflags ) set(RELLIC_DEC2HEX "${RELLIC_DEC2HEX}" PARENT_SCOPE) diff --git a/tools/decomp/Decomp.cpp b/tools/decomp/Decomp.cpp index 9f60622b..327f52eb 100644 --- a/tools/decomp/Decomp.cpp +++ b/tools/decomp/Decomp.cpp @@ -34,15 +34,15 @@ DEFINE_bool(lower_switch, false, DECLARE_bool(version); namespace { -static llvm::Optional GetPCMetadata(llvm::Value* value) { +static std::optional GetPCMetadata(llvm::Value* value) { auto inst{llvm::dyn_cast(value)}; if (!inst) { - return llvm::Optional(); + return std::nullopt; } auto pc{inst->getMetadata("pc")}; if (!pc) { - return llvm::Optional(); + return std::nullopt; } auto& cop{pc->getOperand(0U)}; diff --git a/tools/xref/DeclPrinter.cpp b/tools/xref/DeclPrinter.cpp index 35aedd0f..ff28a6dd 100644 --- a/tools/xref/DeclPrinter.cpp +++ b/tools/xref/DeclPrinter.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include @@ -116,9 +117,13 @@ class DeclPrinter : public DeclVisitor { void printTemplateParameters(const TemplateParameterList *Params, bool OmitTemplateKW = false); - void printTemplateArguments(llvm::ArrayRef Args); - void printTemplateArguments(llvm::ArrayRef Args); - void prettyPrintAttributes(Decl *D); + void printTemplateArguments(llvm::ArrayRef Args, + const TemplateParameterList *Params); + void printTemplateArguments(llvm::ArrayRef Args, + const TemplateParameterList *Params); + enum class AttrPosAsWritten { Default = 0, Left, Right }; + bool prettyPrintAttributes(const Decl *D, + AttrPosAsWritten Pos = AttrPosAsWritten::Default); void prettyPrintPragmas(Decl *D); void printDeclType(QualType T, StringRef DeclName, bool Pack = false); @@ -209,24 +214,51 @@ raw_ostream &DeclPrinter::Indent(unsigned Indentation) { return Out; } -void DeclPrinter::prettyPrintAttributes(Decl *D) { - if (Policy.PolishForDeclaration) return; +static DeclPrinter::AttrPosAsWritten getPosAsWritten(const Attr *A, + const Decl *D) { + SourceLocation ALoc = A->getLoc(); + SourceLocation DLoc = D->getLocation(); + const ASTContext &C = D->getASTContext(); + if (ALoc.isInvalid() || DLoc.isInvalid()) + return DeclPrinter::AttrPosAsWritten::Left; + + if (C.getSourceManager().isBeforeInTranslationUnit(ALoc, DLoc)) + return DeclPrinter::AttrPosAsWritten::Left; + + return DeclPrinter::AttrPosAsWritten::Right; +} + +// returns true if an attribute was printed. +bool DeclPrinter::prettyPrintAttributes(const Decl *D, + AttrPosAsWritten Pos /*=Default*/) { + bool hasPrinted = false; if (D->hasAttrs()) { - AttrVec &Attrs = D->getAttrs(); + const AttrVec &Attrs = D->getAttrs(); for (auto *A : Attrs) { if (A->isInherited() || A->isImplicit()) continue; + // Print out the keyword attributes, they aren't regular attributes. + if (Policy.PolishForDeclaration && !A->isKeywordAttribute()) continue; switch (A->getKind()) { #define ATTR(X) #define PRAGMA_SPELLING_ATTR(X) case attr::X: -#include +#include "clang/Basic/AttrList.inc" break; default: - A->printPretty(Out, Policy); + AttrPosAsWritten APos = getPosAsWritten(A, D); + assert(APos != AttrPosAsWritten::Default && + "Default not a valid for an attribute location"); + if (Pos == AttrPosAsWritten::Default || Pos == APos) { + if (Pos != AttrPosAsWritten::Left) Out << ' '; + A->printPretty(Out, Policy); + hasPrinted = true; + if (Pos == AttrPosAsWritten::Left) Out << ' '; + } break; } } } + return hasPrinted; } void DeclPrinter::prettyPrintPragmas(Decl *D) { @@ -553,8 +585,10 @@ static void printExplicitSpecifier(ExplicitSpecifier ES, llvm::raw_ostream &Out, void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) { if (!D->getDescribedFunctionTemplate() && - !D->isFunctionTemplateSpecialization()) + !D->isFunctionTemplateSpecialization()) { prettyPrintPragmas(D); + prettyPrintAttributes(D, AttrPosAsWritten::Left); + } if (D->isFunctionTemplateSpecialization()) Out << "template<> "; @@ -623,10 +657,10 @@ void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) { DeclPrinter TArgPrinter(POut, SubPolicy, Context, Indentation); const auto *TArgAsWritten = D->getTemplateSpecializationArgsAsWritten(); if (TArgAsWritten && !Policy.PrintCanonicalTypes) - TArgPrinter.printTemplateArguments(TArgAsWritten->arguments()); + TArgPrinter.printTemplateArguments(TArgAsWritten->arguments(), nullptr); else if (const TemplateArgumentList *TArgs = D->getTemplateSpecializationArgs()) - TArgPrinter.printTemplateArguments(TArgs->asArray()); + TArgPrinter.printTemplateArguments(TArgs->asArray(), nullptr); } QualType Ty = D->getType(); @@ -730,7 +764,7 @@ void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) { prettyPrintAttributes(D); - if (D->isPure()) + if (D->isPureVirtual()) Out << " = 0"; else if (D->isDeletedAsWritten()) Out << " = delete"; @@ -893,9 +927,9 @@ void DeclPrinter::VisitImportDecl(ImportDecl *D) { void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) { Out << "static_assert("; PrintStmt(D->getAssertExpr(), Out, Policy, Indentation); - if (StringLiteral *SL = D->getMessage()) { + if (Expr *E = D->getMessage()) { Out << ", "; - PrintStmt(SL, Out, Policy, Indentation); + PrintStmt(E, Out, Policy, Indentation); } Out << ")"; } @@ -936,19 +970,21 @@ void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { Out << "__module_private__ "; Out << "" << D->getKindName() << ""; - prettyPrintAttributes(D); + if (prettyPrintAttributes(D, AttrPosAsWritten::Left)) Out << ' '; if (D->getIdentifier()) { + if (auto *NNS = D->getQualifier()) NNS->print(Out, Policy); Out << ' ' << *D; if (auto S = dyn_cast(D)) { - ArrayRef Args = S->getTemplateArgs().asArray(); - if (!Policy.PrintCanonicalTypes) - if (const auto *TSI = S->getTypeAsWritten()) - if (const auto *TST = - dyn_cast(TSI->getType())) - Args = TST->template_arguments(); - printTemplateArguments(Args); + const TemplateParameterList *TParams = + S->getSpecializedTemplate()->getTemplateParameters(); + const ASTTemplateArgumentListInfo *TArgAsWritten = + S->getTemplateArgsAsWritten(); + if (TArgAsWritten && !Policy.PrintCanonicalTypes) + printTemplateArguments(TArgAsWritten->arguments(), TParams); + else + printTemplateArguments(S->getTemplateArgs().asArray(), TParams); } } @@ -995,10 +1031,10 @@ void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) { const char *l; - if (D->getLanguage() == LinkageSpecDecl::lang_c) + if (D->getLanguage() == LinkageSpecLanguageIDs::C) l = "C"; else { - assert(D->getLanguage() == LinkageSpecDecl::lang_cxx && + assert(D->getLanguage() == LinkageSpecLanguageIDs::CXX && "unknown language in linkage specification"); l = "C++"; } @@ -1042,20 +1078,33 @@ void DeclPrinter::printTemplateParameters(const TemplateParameterList *Params, if (!OmitTemplateKW) Out << ' '; } -void DeclPrinter::printTemplateArguments(ArrayRef Args) { +void DeclPrinter::printTemplateArguments(ArrayRef Args, + const TemplateParameterList *Params) { Out << "<"; for (size_t I = 0, E = Args.size(); I < E; ++I) { if (I) Out << ", "; - Args[I].print(Policy, Out, true); + if (!Params) + Args[I].print(Policy, Out, /*IncludeType*/ true); + else + Args[I].print(Policy, Out, + TemplateParameterList::shouldIncludeTypeForArgument( + Policy, Params, I)); } Out << ">"; } -void DeclPrinter::printTemplateArguments(ArrayRef Args) { +void DeclPrinter::printTemplateArguments(ArrayRef Args, + const TemplateParameterList *Params) { Out << "<"; for (size_t I = 0, E = Args.size(); I < E; ++I) { if (I) Out << ", "; - Args[I].getArgument().print(Policy, Out, true); + if (!Params) + Args[I].getArgument().print(Policy, Out, /*IncludeType*/ true); + else + Args[I].getArgument().print( + Policy, Out, + TemplateParameterList::shouldIncludeTypeForArgument(Policy, Params, + I)); } Out << ">"; } @@ -1524,7 +1573,7 @@ void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) { std::string TypeStr = GetQualTypeAsString( PDecl->getASTContext().getUnqualifiedObjCPointerType(T), Policy); Out << ' ' << TypeStr; - if (!StringRef(TypeStr).endswith("*")) Out << ' '; + if (!StringRef(TypeStr).ends_with("*")) Out << ' '; Out << *PDecl; if (Policy.PolishForDeclaration) Out << ';'; } @@ -1639,17 +1688,17 @@ void DeclPrinter::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) { if (auto *Init = D->getInitializer()) { Out << " initializer("; switch (D->getInitializerKind()) { - case OMPDeclareReductionDecl::DirectInit: + case OMPDeclareReductionInitKind::Direct: Out << "omp_priv("; break; - case OMPDeclareReductionDecl::CopyInit: + case OMPDeclareReductionInitKind::Copy: Out << "omp_priv = "; break; - case OMPDeclareReductionDecl::CallInit: + case OMPDeclareReductionInitKind::Call: break; } PrintStmt(Init, Out, Policy, 0); - if (D->getInitializerKind() == OMPDeclareReductionDecl::DirectInit) + if (D->getInitializerKind() == OMPDeclareReductionInitKind::Direct) Out << ")"; Out << ")"; } @@ -1693,22 +1742,31 @@ void DeclPrinter::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *TTP) { else if (TTP->getDeclName()) Out << ' '; - if (TTP->getDeclName()) Out << TTP->getDeclName(); + if (TTP->getDeclName()) { + if (Policy.CleanUglifiedParameters && TTP->getIdentifier()) + Out << TTP->getIdentifier()->deuglifiedName(); + else + Out << TTP->getDeclName(); + } if (TTP->hasDefaultArgument()) { Out << " = "; - Out << GetQualTypeAsString(TTP->getDefaultArgument(), Policy); + TTP->getDefaultArgument().getArgument().print(Policy, Out, + /*IncludeType=*/false); } } void DeclPrinter::VisitNonTypeTemplateParmDecl( const NonTypeTemplateParmDecl *NTTP) { StringRef Name; - if (IdentifierInfo *II = NTTP->getIdentifier()) Name = II->getName(); + if (IdentifierInfo *II = NTTP->getIdentifier()) + Name = + Policy.CleanUglifiedParameters ? II->deuglifiedName() : II->getName(); printDeclType(NTTP->getType(), Name, NTTP->isParameterPack()); if (NTTP->hasDefaultArgument()) { Out << " = "; - PrintStmt(NTTP->getDefaultArgument(), Out, Policy, Indentation); + NTTP->getDefaultArgument().getArgument().print(Policy, Out, + /*IncludeType=*/false); } } diff --git a/tools/xref/StmtPrinter.cpp b/tools/xref/StmtPrinter.cpp index 232147b7..97db75a5 100644 --- a/tools/xref/StmtPrinter.cpp +++ b/tools/xref/StmtPrinter.cpp @@ -47,6 +47,7 @@ #include #include #include +#include #include #include #include @@ -137,6 +138,8 @@ class StmtPrinter : public StmtVisitor { void PrintOMPExecutableDirective(OMPExecutableDirective *S, bool ForceNoStmt = false); void PrintFPPragmas(CompoundStmt *S); + void PrintOpenACCClauseList(OpenACCConstructStmt *S); + void PrintOpenACCConstruct(OpenACCConstructStmt *S); void PrintExpr(Expr *E) { if (E) @@ -194,60 +197,62 @@ void StmtPrinter::PrintRawCompoundStmt(CompoundStmt *Node) { } void StmtPrinter::PrintFPPragmas(CompoundStmt *S) { - if (!S->hasStoredFPFeatures()) - return; + if (!S->hasStoredFPFeatures()) return; FPOptionsOverride FPO = S->getStoredFPFeatures(); bool FEnvAccess = false; if (FPO.hasAllowFEnvAccessOverride()) { FEnvAccess = FPO.getAllowFEnvAccessOverride(); - Indent() << "#pragma STDC FENV_ACCESS " << (FEnvAccess ? "ON" : "OFF") - << NL; + Indent() + << "#pragma STDC FENV_ACCESS " + << (FEnvAccess ? "ON" : "OFF") << NL; } if (FPO.hasSpecifiedExceptionModeOverride()) { LangOptions::FPExceptionModeKind EM = FPO.getSpecifiedExceptionModeOverride(); if (!FEnvAccess || EM != LangOptions::FPE_Strict) { - Indent() << "#pragma clang fp exceptions("; + Indent() << "#pragma clang fp " + "exceptions("; switch (FPO.getSpecifiedExceptionModeOverride()) { - default: - break; - case LangOptions::FPE_Ignore: - OS << "ignore"; - break; - case LangOptions::FPE_MayTrap: - OS << "maytrap"; - break; - case LangOptions::FPE_Strict: - OS << "strict"; - break; + default: + break; + case LangOptions::FPE_Ignore: + OS << "ignore"; + break; + case LangOptions::FPE_MayTrap: + OS << "maytrap"; + break; + case LangOptions::FPE_Strict: + OS << "strict"; + break; } OS << ")\n"; } } if (FPO.hasConstRoundingModeOverride()) { LangOptions::RoundingMode RM = FPO.getConstRoundingModeOverride(); - Indent() << "#pragma STDC FENV_ROUND "; + Indent() + << "#pragma STDC FENV_ROUND "; switch (RM) { - case llvm::RoundingMode::TowardZero: - OS << "FE_TOWARDZERO"; - break; - case llvm::RoundingMode::NearestTiesToEven: - OS << "FE_TONEAREST"; - break; - case llvm::RoundingMode::TowardPositive: - OS << "FE_UPWARD"; - break; - case llvm::RoundingMode::TowardNegative: - OS << "FE_DOWNWARD"; - break; - case llvm::RoundingMode::NearestTiesToAway: - OS << "FE_TONEARESTFROMZERO"; - break; - case llvm::RoundingMode::Dynamic: - OS << "FE_DYNAMIC"; - break; - default: - llvm_unreachable("Invalid rounding mode"); + case llvm::RoundingMode::TowardZero: + OS << "FE_TOWARDZERO"; + break; + case llvm::RoundingMode::NearestTiesToEven: + OS << "FE_TONEAREST"; + break; + case llvm::RoundingMode::TowardPositive: + OS << "FE_UPWARD"; + break; + case llvm::RoundingMode::TowardNegative: + OS << "FE_DOWNWARD"; + break; + case llvm::RoundingMode::NearestTiesToAway: + OS << "FE_TONEARESTFROMZERO"; + break; + case llvm::RoundingMode::Dynamic: + OS << "FE_DYNAMIC"; + break; + default: + llvm_unreachable("Invalid rounding mode"); } OS << NL; } @@ -572,6 +577,10 @@ void StmtPrinter::VisitCapturedStmt(CapturedStmt *Node) { PrintStmt(Node->getCapturedDecl()->getBody()); } +void StmtPrinter::VisitSYCLKernelCallStmt(SYCLKernelCallStmt *Node) { + PrintStmt(Node->getOutlinedFunctionDecl()->getBody()); +} + void StmtPrinter::VisitObjCAtTryStmt(ObjCAtTryStmt *Node) { Indent() << "@try"; if (auto *TS = dyn_cast(Node->getTryBody())) { @@ -754,6 +763,17 @@ void StmtPrinter::VisitOMPUnrollDirective(OMPUnrollDirective *Node) { PrintOMPExecutableDirective(Node); } +void StmtPrinter::VisitOMPReverseDirective(OMPReverseDirective *Node) { + Indent() << "#pragma omp reverse"; + PrintOMPExecutableDirective(Node); +} + +void StmtPrinter::VisitOMPInterchangeDirective(OMPInterchangeDirective *Node) { + Indent() + << "#pragma omp interchange"; + PrintOMPExecutableDirective(Node); +} + void StmtPrinter::VisitOMPForDirective(OMPForDirective *Node) { Indent() << "#pragma omp for"; PrintOMPExecutableDirective(Node); @@ -774,6 +794,11 @@ void StmtPrinter::VisitOMPSectionDirective(OMPSectionDirective *Node) { PrintOMPExecutableDirective(Node); } +void StmtPrinter::VisitOMPScopeDirective(OMPScopeDirective *Node) { + Indent() << "#pragma omp scope"; + PrintOMPExecutableDirective(Node); +} + void StmtPrinter::VisitOMPSingleDirective(OMPSingleDirective *Node) { Indent() << "#pragma omp single"; PrintOMPExecutableDirective(Node); @@ -816,7 +841,8 @@ void StmtPrinter::VisitOMPParallelMasterDirective( void StmtPrinter::VisitOMPParallelMaskedDirective( OMPParallelMaskedDirective *Node) { - Indent() << "#pragma omp parallel masked"; + Indent() << "#pragma omp parallel " + "masked"; PrintOMPExecutableDirective(Node); } @@ -829,7 +855,8 @@ void StmtPrinter::VisitOMPParallelSectionsDirective( void StmtPrinter::VisitOMPMaskedTaskLoopDirective( OMPMaskedTaskLoopDirective *Node) { - Indent() << "#pragma omp masked taskloop"; + Indent() << "#pragma omp masked " + "taskloop"; PrintOMPExecutableDirective(Node); } @@ -853,6 +880,11 @@ void StmtPrinter::VisitOMPTaskwaitDirective(OMPTaskwaitDirective *Node) { PrintOMPExecutableDirective(Node); } +void StmtPrinter::VisitOMPAssumeDirective(OMPAssumeDirective *Node) { + Indent() << "#pragma omp assume"; + PrintOMPExecutableDirective(Node); +} + void StmtPrinter::VisitOMPErrorDirective(OMPErrorDirective *Node) { Indent() << "#pragma omp error"; PrintOMPExecutableDirective(Node); @@ -988,43 +1020,50 @@ void StmtPrinter::VisitOMPParallelMasterTaskLoopSimdDirective( void StmtPrinter::VisitOMPMaskedTaskLoopSimdDirective( OMPMaskedTaskLoopSimdDirective *Node) { - Indent() << "#pragma omp masked taskloop simd"; + Indent() << "#pragma omp masked " + "taskloop simd"; PrintOMPExecutableDirective(Node); } void StmtPrinter::VisitOMPParallelMaskedTaskLoopDirective( OMPParallelMaskedTaskLoopDirective *Node) { - Indent() << "#pragma omp parallel masked taskloop"; + Indent() << "#pragma omp parallel " + "masked taskloop"; PrintOMPExecutableDirective(Node); } void StmtPrinter::VisitOMPParallelMaskedTaskLoopSimdDirective( OMPParallelMaskedTaskLoopSimdDirective *Node) { - Indent() << "#pragma omp parallel masked taskloop simd"; + Indent() << "#pragma omp parallel " + "masked taskloop simd"; PrintOMPExecutableDirective(Node); } void StmtPrinter::VisitOMPTeamsGenericLoopDirective( OMPTeamsGenericLoopDirective *Node) { - Indent() << "#pragma omp teams loop"; + Indent() + << "#pragma omp teams loop"; PrintOMPExecutableDirective(Node); } void StmtPrinter::VisitOMPTargetTeamsGenericLoopDirective( OMPTargetTeamsGenericLoopDirective *Node) { - Indent() << "#pragma omp target teams loop"; + Indent() << "#pragma omp target " + "teams loop"; PrintOMPExecutableDirective(Node); } void StmtPrinter::VisitOMPParallelGenericLoopDirective( OMPParallelGenericLoopDirective *Node) { - Indent() << "#pragma omp parallel loop"; + Indent() + << "#pragma omp parallel loop"; PrintOMPExecutableDirective(Node); } void StmtPrinter::VisitOMPTargetParallelGenericLoopDirective( OMPTargetParallelGenericLoopDirective *Node) { - Indent() << "#pragma omp target parallel loop"; + Indent() << "#pragma omp target " + "parallel loop"; PrintOMPExecutableDirective(Node); } @@ -1157,6 +1196,87 @@ void StmtPrinter::VisitOMPGenericLoopDirective(OMPGenericLoopDirective *Node) { PrintOMPExecutableDirective(Node); } +//===----------------------------------------------------------------------===// +// OpenACC construct printing methods +//===----------------------------------------------------------------------===// +void StmtPrinter::PrintOpenACCClauseList(OpenACCConstructStmt *S) { + if (!S->clauses().empty()) { + OS << ' '; + OpenACCClausePrinter Printer(OS, Policy); + Printer.VisitClauseList(S->clauses()); + } +} +void StmtPrinter::PrintOpenACCConstruct(OpenACCConstructStmt *S) { + Indent() << "#pragma acc " + << S->getDirectiveKind(); + PrintOpenACCClauseList(S); + OS << '\n'; +} +void StmtPrinter::VisitOpenACCComputeConstruct(OpenACCComputeConstruct *S) { + PrintOpenACCConstruct(S); + PrintStmt(S->getStructuredBlock()); +} +void StmtPrinter::VisitOpenACCLoopConstruct(OpenACCLoopConstruct *S) { + PrintOpenACCConstruct(S); + PrintStmt(S->getLoop()); +} + +void StmtPrinter::VisitOpenACCCombinedConstruct(OpenACCCombinedConstruct *S) { + PrintOpenACCConstruct(S); + PrintStmt(S->getLoop()); +} + +void StmtPrinter::VisitOpenACCDataConstruct(OpenACCDataConstruct *S) { + PrintOpenACCConstruct(S); + PrintStmt(S->getStructuredBlock()); +} +void StmtPrinter::VisitOpenACCHostDataConstruct(OpenACCHostDataConstruct *S) { + PrintOpenACCConstruct(S); + PrintStmt(S->getStructuredBlock()); +} +void StmtPrinter::VisitOpenACCEnterDataConstruct(OpenACCEnterDataConstruct *S) { + PrintOpenACCConstruct(S); +} +void StmtPrinter::VisitOpenACCExitDataConstruct(OpenACCExitDataConstruct *S) { + PrintOpenACCConstruct(S); +} +void StmtPrinter::VisitOpenACCInitConstruct(OpenACCInitConstruct *S) { + PrintOpenACCConstruct(S); +} +void StmtPrinter::VisitOpenACCShutdownConstruct(OpenACCShutdownConstruct *S) { + PrintOpenACCConstruct(S); +} + +void StmtPrinter::VisitOpenACCSetConstruct(OpenACCSetConstruct *S) { + PrintOpenACCConstruct(S); +} +void StmtPrinter::VisitOpenACCUpdateConstruct(OpenACCUpdateConstruct *S) { + PrintOpenACCConstruct(S); +} + +void StmtPrinter::VisitOpenACCWaitConstruct(OpenACCWaitConstruct *S) { + Indent() << "#pragma acc wait"; + if (!S->getLParenLoc().isInvalid()) { + OS << "("; + if (S->hasDevNumExpr()) { + OS << "devnum: "; + S->getDevNumExpr()->printPretty(OS, nullptr, Policy); + OS << " : "; + } + + if (S->hasQueuesTag()) OS << "queues: "; + + llvm::interleaveComma(S->getQueueIdExprs(), OS, [&](const Expr *E) { + E->printPretty(OS, nullptr, Policy); + }); + + OS << ")"; + } + + PrintOpenACCClauseList(S); + OS << '\n'; +} + //===----------------------------------------------------------------------===// // Expr printing methods. //===----------------------------------------------------------------------===// @@ -1165,6 +1285,10 @@ void StmtPrinter::VisitSourceLocExpr(SourceLocExpr *Node) { OS << Node->getBuiltinStr() << "()"; } +void StmtPrinter::VisitEmbedExpr(EmbedExpr *Node) { + llvm::report_fatal_error("Not implemented"); +} + void StmtPrinter::VisitConstantExpr(ConstantExpr *Node) { PrintExpr(Node->getSubExpr()); } @@ -1216,7 +1340,7 @@ void StmtPrinter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *Node) { static bool isImplicitSelf(const Expr *E) { if (const auto *DRE = dyn_cast(E)) { if (const auto *PD = dyn_cast(DRE->getDecl())) { - if (PD->getParameterKind() == ImplicitParamDecl::ObjCSelf && + if (PD->getParameterKind() == ImplicitParamKind::ObjCSelf && DRE->getBeginLoc().isInvalid()) return true; } @@ -1273,23 +1397,27 @@ void StmtPrinter::VisitPredefinedExpr(PredefinedExpr *Node) { OS << PredefinedExpr::getIdentKindName(Node->getIdentKind()); } +void StmtPrinter::VisitOpenACCAsteriskSizeExpr(OpenACCAsteriskSizeExpr *Node) { + OS << '*'; +} + void StmtPrinter::VisitCharacterLiteral(CharacterLiteral *Node) { OS << ""; unsigned value = Node->getValue(); switch (Node->getKind()) { - case CharacterLiteral::Ascii: + case CharacterLiteralKind::Ascii: break; // no prefix. - case CharacterLiteral::Wide: + case CharacterLiteralKind::Wide: OS << 'L'; break; - case CharacterLiteral::UTF8: + case CharacterLiteralKind::UTF8: OS << "u8"; break; - case CharacterLiteral::UTF16: + case CharacterLiteralKind::UTF16: OS << 'u'; break; - case CharacterLiteral::UTF32: + case CharacterLiteralKind::UTF32: OS << 'U'; break; } @@ -1342,7 +1470,7 @@ void StmtPrinter::VisitCharacterLiteral(CharacterLiteral *Node) { // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF' // are not correctly handled. if ((value & ~0xFFu) == ~0xFFu && - Node->getKind() == CharacterLiteral::Ascii) + Node->getKind() == CharacterLiteralKind::Ascii) value &= 0xFFu; if (value < 256 && isPrintable((unsigned char)value)) OS << "'" << (char)value << "'"; @@ -1377,10 +1505,11 @@ void StmtPrinter::VisitIntegerLiteral(IntegerLiteral *Node) { return; OS << ""; bool isSigned = Node->getType()->isSignedIntegerType(); - if (Node->getValue().getZExtValue() < 16) { - OS << toString(Node->getValue(), 10, isSigned); - } else { - OS << toString(Node->getValue(), 16, isSigned, /*formatAsCLiteral=*/true); + OS << toString(Node->getValue(), 10, isSigned); + + if (isa(Node->getType())) { + OS << (isSigned ? "wb" : "uwb"); + return; } if (isa(Node->getType())) { @@ -1393,24 +1522,45 @@ void StmtPrinter::VisitIntegerLiteral(IntegerLiteral *Node) { default: llvm_unreachable("Unexpected type for integer literal!"); case BuiltinType::Char_S: - case BuiltinType::Char_U: OS << "i8"; break; - case BuiltinType::UChar: OS << "Ui8"; break; - case BuiltinType::SChar: OS << "i8"; break; - case BuiltinType::Short: OS << "i16"; break; - case BuiltinType::UShort: OS << "Ui16"; break; - case BuiltinType::Int: break; // no suffix. - case BuiltinType::UInt: OS << 'U'; break; - case BuiltinType::Long: OS << 'L'; break; - case BuiltinType::ULong: OS << "UL"; break; - case BuiltinType::LongLong: OS << "LL"; break; - case BuiltinType::ULongLong: OS << "ULL"; break; + case BuiltinType::Char_U: + OS << "i8"; + break; + case BuiltinType::UChar: + OS << "Ui8"; + break; + case BuiltinType::SChar: + OS << "i8"; + break; + case BuiltinType::Short: + OS << "i16"; + break; + case BuiltinType::UShort: + OS << "Ui16"; + break; + case BuiltinType::Int: + break; // no suffix. + case BuiltinType::UInt: + OS << 'U'; + break; + case BuiltinType::Long: + OS << 'L'; + break; + case BuiltinType::ULong: + OS << "UL"; + break; + case BuiltinType::LongLong: + OS << "LL"; + break; + case BuiltinType::ULongLong: + OS << "ULL"; + break; case BuiltinType::Int128: - break; // no suffix. + break; // no suffix. case BuiltinType::UInt128: - break; // no suffix. + break; // no suffix. case BuiltinType::WChar_S: case BuiltinType::WChar_U: - break; // no suffix + break; // no suffix } OS << ""; } @@ -1514,18 +1664,19 @@ void StmtPrinter::VisitImaginaryLiteral(ImaginaryLiteral *Node) { static void outputString(const StringLiteral *Str, raw_ostream &OS) { switch (Str->getKind()) { - case StringLiteral::Ordinary: + case StringLiteralKind::Unevaluated: + case StringLiteralKind::Ordinary: break; // no prefix. - case StringLiteral::Wide: + case StringLiteralKind::Wide: OS << 'L'; break; - case StringLiteral::UTF8: + case StringLiteralKind::UTF8: OS << "u8"; break; - case StringLiteral::UTF16: + case StringLiteralKind::UTF16: OS << 'u'; break; - case StringLiteral::UTF32: + case StringLiteralKind::UTF32: OS << 'U'; break; } @@ -1538,7 +1689,7 @@ static void outputString(const StringLiteral *Str, raw_ostream &OS) { // FIXME: Convert UTF-8 back to codepoints before rendering. // Convert UTF-16 surrogate pairs back to codepoints before rendering. // Leave invalid surrogates alone; we'll use \x for those. - if (Str->getKind() == StringLiteral::UTF16 && I != N - 1 && + if (Str->getKind() == StringLiteralKind::UTF16 && I != N - 1 && Char >= 0xd800 && Char <= 0xdbff) { uint32_t Trail = Str->getCodeUnit(I + 1); if (Trail >= 0xdc00 && Trail <= 0xdfff) { @@ -1550,7 +1701,7 @@ static void outputString(const StringLiteral *Str, raw_ostream &OS) { // If this is a wide string, output characters over 0xff using \x // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is // a codepoint: use \x escapes for invalid codepoints. - if (Str->getKind() == StringLiteral::Wide || + if (Str->getKind() == StringLiteralKind::Wide || (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) { // FIXME: Is this the best way to print wchar_t? OS << "\\x"; @@ -1774,7 +1925,7 @@ void StmtPrinter::VisitMatrixSubscriptExpr(MatrixSubscriptExpr *Node) { OS << "]"; } -void StmtPrinter::VisitOMPArraySectionExpr(OMPArraySectionExpr *Node) { +void StmtPrinter::VisitArraySectionExpr(ArraySectionExpr *Node) { PrintExpr(Node->getBase()); OS << "["; if (Node->getLowerBound()) PrintExpr(Node->getLowerBound()); @@ -1782,7 +1933,7 @@ void StmtPrinter::VisitOMPArraySectionExpr(OMPArraySectionExpr *Node) { OS << ":"; if (Node->getLength()) PrintExpr(Node->getLength()); } - if (Node->getColonLocSecond().isValid()) { + if (Node->isOMPArraySection() && Node->getColonLocSecond().isValid()) { OS << ":"; if (Node->getStride()) PrintExpr(Node->getStride()); } @@ -2009,7 +2160,7 @@ void StmtPrinter::VisitDesignatedInitExpr(DesignatedInitExpr *Node) { for (const DesignatedInitExpr::Designator &D : Node->designators()) { if (D.isFieldDesignator()) { if (D.getDotLoc().isInvalid()) { - if (IdentifierInfo *II = D.getFieldName()) { + if (const IdentifierInfo *II = D.getFieldName()) { OS << II->getName() << ":"; NeedsEquals = false; } @@ -2086,7 +2237,7 @@ void StmtPrinter::VisitAtomicExpr(AtomicExpr *Node) { case AtomicExpr::AO##ID: \ Name = #ID "("; \ break; -#include +#include } OS << Name; @@ -2268,7 +2419,8 @@ void StmtPrinter::VisitUserDefinedLiteral(UserDefinedLiteral *Node) { cast(DRE->getDecl())->getTemplateSpecializationArgs(); assert(Args); - if (Args->size() != 1 || Args->get(0).getKind() != TemplateArgument::Pack) { + if (Args->size() != 1 || + Args->get(0).getKind() != TemplateArgument::Pack) { OS << "operator\"\"" << Node->getUDSuffix()->getName(); printTemplateArgumentList(OS, Args->asArray(), Policy); @@ -2339,18 +2491,14 @@ void StmtPrinter::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) { bool Bare = Auto && Auto->isDeduced(); // Parenthesize deduced casts. - if (Bare) - OS << '('; + if (Bare) OS << '('; TargetType.print(OS, Policy); - if (Bare) - OS << ')'; + if (Bare) OS << ')'; // No extra braces surrounding the inner construct. - if (!Node->isListInitialization()) - OS << '('; + if (!Node->isListInitialization()) OS << '('; PrintExpr(Node->getSubExpr()); - if (!Node->isListInitialization()) - OS << ')'; + if (!Node->isListInitialization()) OS << ')'; } void StmtPrinter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *Node) { @@ -2536,15 +2684,13 @@ void StmtPrinter::VisitCXXNewExpr(CXXNewExpr *E) { PrintType(E->getAllocatedType(), OS, Policy, TypeS); if (E->isParenTypeId()) OS << ")"; - CXXNewExpr::InitializationStyle InitStyle = E->getInitializationStyle(); - if (InitStyle != CXXNewExpr::NoInit) { - bool Bare = InitStyle == CXXNewExpr::CallInit && + CXXNewInitializationStyle InitStyle = E->getInitializationStyle(); + if (InitStyle != CXXNewInitializationStyle::None) { + bool Bare = InitStyle == CXXNewInitializationStyle::Parens && !isa(E->getInitializer()); - if (Bare) - OS << "("; + if (Bare) OS << "("; PrintExpr(E->getInitializer()); - if (Bare) - OS << ")"; + if (Bare) OS << ")"; } } @@ -2564,7 +2710,7 @@ void StmtPrinter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) { if (E->getQualifier()) E->getQualifier()->print(OS, Policy); OS << "~"; - if (IdentifierInfo *II = E->getDestroyedTypeIdentifier()) + if (const IdentifierInfo *II = E->getDestroyedTypeIdentifier()) OS << II->getName(); else PrintType(E->getDestroyedType(), OS, Policy); @@ -2603,15 +2749,13 @@ void StmtPrinter::VisitExprWithCleanups(ExprWithCleanups *E) { void StmtPrinter::VisitCXXUnresolvedConstructExpr( CXXUnresolvedConstructExpr *Node) { PrintType(Node->getTypeAsWritten(), OS, Policy); - if (!Node->isListInitialization()) - OS << '('; + if (!Node->isListInitialization()) OS << '('; for (auto Arg = Node->arg_begin(), ArgEnd = Node->arg_end(); Arg != ArgEnd; ++Arg) { if (Arg != Node->arg_begin()) OS << ", "; PrintExpr(*Arg); } - if (!Node->isListInitialization()) - OS << ')'; + if (!Node->isListInitialization()) OS << ')'; } void StmtPrinter::VisitCXXDependentScopeMemberExpr( @@ -2680,6 +2824,13 @@ void StmtPrinter::VisitSizeOfPackExpr(SizeOfPackExpr *E) { << ")"; } +void StmtPrinter::VisitPackIndexingExpr(PackIndexingExpr *E) { + PrintExpr(E->getPackIdExpression()); + OS << "...["; + PrintExpr(E->getIndexExpr()); + OS << "]"; +} + void StmtPrinter::VisitSubstNonTypeTemplateParmPackExpr( SubstNonTypeTemplateParmPackExpr *Node) { OS << *Node->getParameterPack(); @@ -2975,6 +3126,10 @@ void StmtPrinter::VisitAsTypeExpr(AsTypeExpr *Node) { OS << ")"; } +void StmtPrinter::VisitHLSLOutArgExpr(HLSLOutArgExpr *Node) { + PrintExpr(Node->getArgLValue()); +} + //===----------------------------------------------------------------------===// // Stmt method implementations //===----------------------------------------------------------------------===// diff --git a/tools/xref/TypePrinter.cpp b/tools/xref/TypePrinter.cpp index 80bb4f57..9f501a33 100644 --- a/tools/xref/TypePrinter.cpp +++ b/tools/xref/TypePrinter.cpp @@ -248,6 +248,7 @@ bool TypePrinter::canPrefixQualifiers(const Type *T, case Type::BitInt: case Type::DependentBitInt: case Type::BTFTagAttributed: + case Type::HLSLAttributedResource: CanPrefixQualifiers = true; break; @@ -270,6 +271,7 @@ bool TypePrinter::canPrefixQualifiers(const Type *T, case Type::Adjusted: case Type::Decayed: + case Type::ArrayParameter: case Type::Pointer: case Type::BlockPointer: case Type::LValueReference: @@ -288,6 +290,7 @@ bool TypePrinter::canPrefixQualifiers(const Type *T, case Type::PackExpansion: case Type::SubstTemplateTypeParm: case Type::MacroQualified: + case Type::CountAttributed: CanPrefixQualifiers = false; break; @@ -298,6 +301,11 @@ bool TypePrinter::canPrefixQualifiers(const Type *T, CanPrefixQualifiers = AttrTy->getAttrKind() == attr::AddressSpace; break; } + case Type::PackIndexing: { + return canPrefixQualifiers( + cast(UnderlyingType)->getPattern().getTypePtr(), + NeedARCStrongQualifier); + } } return CanPrefixQualifiers; @@ -525,7 +533,7 @@ void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T, OS << ' '; } - if (T->getSizeModifier() == ArrayType::Static) + if (T->getSizeModifier() == ArraySizeModifier::Static) OS << "static "; OS << "" @@ -559,9 +567,9 @@ void TypePrinter::printVariableArrayAfter(const VariableArrayType *T, OS << ' '; } - if (T->getSizeModifier() == VariableArrayType::Static) + if (T->getSizeModifier() == ArraySizeModifier::Static) OS << "static "; - else if (T->getSizeModifier() == VariableArrayType::Star) + else if (T->getSizeModifier() == ArraySizeModifier::Star) OS << '*'; if (T->getSizeExpr()) T->getSizeExpr()->printPretty(OS, nullptr, Policy); @@ -585,6 +593,16 @@ void TypePrinter::printDecayedBefore(const DecayedType *T, raw_ostream &OS) { printAdjustedBefore(T, OS); } +void TypePrinter::printArrayParameterAfter(const ArrayParameterType *T, + raw_ostream &OS) { + printConstantArrayAfter(T, OS); +} + +void TypePrinter::printArrayParameterBefore(const ArrayParameterType *T, + raw_ostream &OS) { + printConstantArrayBefore(T, OS); +} + void TypePrinter::printDecayedAfter(const DecayedType *T, raw_ostream &OS) { printAdjustedAfter(T, OS); } @@ -632,27 +650,27 @@ void TypePrinter::printDependentSizedExtVectorAfter( void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) { switch (T->getVectorKind()) { - case VectorType::AltiVecPixel: + case VectorKind::AltiVecPixel: OS << "__vector __pixel "; break; - case VectorType::AltiVecBool: + case VectorKind::AltiVecBool: OS << "__vector __bool "; printBefore(T->getElementType(), OS); break; - case VectorType::AltiVecVector: + case VectorKind::AltiVecVector: OS << "__vector "; printBefore(T->getElementType(), OS); break; - case VectorType::NeonVector: + case VectorKind::Neon: OS << "__attribute__((neon_vector_type(" << T->getNumElements() << "))) "; printBefore(T->getElementType(), OS); break; - case VectorType::NeonPolyVector: + case VectorKind::NeonPoly: OS << "__attribute__((neon_polyvector_type(" << T->getNumElements() << "))) "; printBefore(T->getElementType(), OS); break; - case VectorType::GenericVector: { + case VectorKind::Generic: { // FIXME: We prefer to print the size directly here, but have no way // to get the size of the type. OS << "__attribute__((__vector_size__(" << T->getNumElements() @@ -662,13 +680,13 @@ void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) { printBefore(T->getElementType(), OS); break; } - case VectorType::SveFixedLengthDataVector: - case VectorType::SveFixedLengthPredicateVector: + case VectorKind::SveFixedLengthData: + case VectorKind::SveFixedLengthPredicate: // FIXME: We prefer to print the size directly here, but have no way // to get the size of the type. OS << "__attribute__((__arm_sve_vector_bits__("; - if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) + if (T->getVectorKind() == VectorKind::SveFixedLengthPredicate) // Predicates take a bit per byte of the vector size, multiply by 8 to // get the number of bits passed to the attribute. OS << T->getNumElements() * 8; @@ -680,6 +698,24 @@ void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) { // Multiply by 8 for the number of bits. OS << ") * 8))) "; printBefore(T->getElementType(), OS); + break; + case VectorKind::RVVFixedLengthData: + case VectorKind::RVVFixedLengthMask: + case VectorKind::RVVFixedLengthMask_1: + case VectorKind::RVVFixedLengthMask_2: + case VectorKind::RVVFixedLengthMask_4: + // FIXME: We prefer to print the size directly here, but have no way + // to get the size of the type. + OS << "__attribute__((__riscv_rvv_vector_bits__("; + + OS << T->getNumElements(); + + OS << " * sizeof("; + print(T->getElementType(), OS, StringRef()); + // Multiply by 8 for the number of bits. + OS << ") * 8))) "; + printBefore(T->getElementType(), OS); + break; } } @@ -690,30 +726,30 @@ void TypePrinter::printVectorAfter(const VectorType *T, raw_ostream &OS) { void TypePrinter::printDependentVectorBefore(const DependentVectorType *T, raw_ostream &OS) { switch (T->getVectorKind()) { - case VectorType::AltiVecPixel: + case VectorKind::AltiVecPixel: OS << "__vector __pixel "; break; - case VectorType::AltiVecBool: + case VectorKind::AltiVecBool: OS << "__vector __bool "; printBefore(T->getElementType(), OS); break; - case VectorType::AltiVecVector: + case VectorKind::AltiVecVector: OS << "__vector "; printBefore(T->getElementType(), OS); break; - case VectorType::NeonVector: + case VectorKind::Neon: OS << "__attribute__((neon_vector_type("; if (T->getSizeExpr()) T->getSizeExpr()->printPretty(OS, nullptr, Policy); OS << "))) "; printBefore(T->getElementType(), OS); break; - case VectorType::NeonPolyVector: + case VectorKind::NeonPoly: OS << "__attribute__((neon_polyvector_type("; if (T->getSizeExpr()) T->getSizeExpr()->printPretty(OS, nullptr, Policy); OS << "))) "; printBefore(T->getElementType(), OS); break; - case VectorType::GenericVector: { + case VectorKind::Generic: { // FIXME: We prefer to print the size directly here, but have no way // to get the size of the type. OS << "__attribute__((__vector_size__("; @@ -724,14 +760,14 @@ void TypePrinter::printDependentVectorBefore(const DependentVectorType *T, printBefore(T->getElementType(), OS); break; } - case VectorType::SveFixedLengthDataVector: - case VectorType::SveFixedLengthPredicateVector: + case VectorKind::SveFixedLengthData: + case VectorKind::SveFixedLengthPredicate: // FIXME: We prefer to print the size directly here, but have no way // to get the size of the type. OS << "__attribute__((__arm_sve_vector_bits__("; if (T->getSizeExpr()) { T->getSizeExpr()->printPretty(OS, nullptr, Policy); - if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) + if (T->getVectorKind() == VectorKind::SveFixedLengthPredicate) // Predicates take a bit per byte of the vector size, multiply by 8 to // get the number of bits passed to the attribute. OS << " * 8"; @@ -742,6 +778,25 @@ void TypePrinter::printDependentVectorBefore(const DependentVectorType *T, } OS << "))) "; printBefore(T->getElementType(), OS); + break; + case VectorKind::RVVFixedLengthData: + case VectorKind::RVVFixedLengthMask: + case VectorKind::RVVFixedLengthMask_1: + case VectorKind::RVVFixedLengthMask_2: + case VectorKind::RVVFixedLengthMask_4: + // FIXME: We prefer to print the size directly here, but have no way + // to get the size of the type. + OS << "__attribute__((__riscv_rvv_vector_bits__("; + if (T->getSizeExpr()) { + T->getSizeExpr()->printPretty(OS, nullptr, Policy); + OS << " * sizeof("; + print(T->getElementType(), OS, StringRef()); + // Multiply by 8 for the number of bits. + OS << ") * 8"; + } + OS << "))) "; + printBefore(T->getElementType(), OS); + break; } } @@ -969,6 +1024,15 @@ void TypePrinter::printFunctionAfter(const FunctionType::ExtInfo &Info, case CC_PreserveAll: OS << " __attribute__((preserve_all))"; break; + case CC_M68kRTD: + OS << " __attribute__((m68k_rtd))"; + break; + case CC_PreserveNone: + OS << " __attribute__((preserve_none))"; + break; + case CC_RISCVVectorCall: + OS << "__attribute__((riscv_vector_cc))"; + break; } } @@ -1074,8 +1138,7 @@ void TypePrinter::printTypeOfExprAfter(const TypeOfExprType *T, void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) { OS << "" - << (T->getKind() == TypeOfKind::Unqualified ? "typeof_unqual" - : "typeof") + << (T->getKind() == TypeOfKind::Unqualified ? "typeof_unqual" : "typeof") << '('; print(T->getUnmodifiedType(), OS, StringRef()); OS << ')'; @@ -1092,6 +1155,21 @@ void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) { spaceBeforePlaceHolder(OS); } +void TypePrinter::printPackIndexingBefore(const PackIndexingType *T, + raw_ostream &OS) { + if (T->hasSelectedType()) { + OS << T->getSelectedType(); + } else { + OS << T->getPattern() << "...["; + T->getIndexExpr()->printPretty(OS, nullptr, Policy); + OS << "]"; + } + spaceBeforePlaceHolder(OS); +} + +void TypePrinter::printPackIndexingAfter(const PackIndexingType *T, + raw_ostream &OS) {} + void TypePrinter::printDecltypeAfter(const DecltypeType *T, raw_ostream &OS) {} void TypePrinter::printUnaryTransformBefore(const UnaryTransformType *T, @@ -1099,7 +1177,7 @@ void TypePrinter::printUnaryTransformBefore(const UnaryTransformType *T, IncludeStrongLifetimeRAII Strong(Policy); static llvm::DenseMap Transformation = {{ -#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \ +#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \ {UnaryTransformType::Enum, "__" #Trait}, #include "clang/Basic/TransformTypeTraits.def" }}; @@ -1300,8 +1378,11 @@ void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) { if (isa(D) && cast(D)->isLambda()) { OS << "lambda"; HasKindDecoration = true; - } else { + } else if ((isa(D) && + cast(D)->isAnonymousStructOrUnion())) { OS << "anonymous"; + } else { + OS << "unnamed"; } if (Policy.AnonymousTagLocations) { @@ -1317,11 +1398,20 @@ void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) { if (PLoc.isValid()) { OS << " at "; StringRef File = PLoc.getFilename(); + llvm::SmallString<1024> WrittenFile(File); if (auto *Callbacks = Policy.Callbacks) - OS << Callbacks->remapPath(File); - else - OS << File; - OS << ':' << PLoc.getLine() << ':' << PLoc.getColumn(); + WrittenFile = Callbacks->remapPath(File); + // Fix inconsistent path separator created by + // clang::DirectoryLookup::LookupFile when the file path is relative + // path. + llvm::sys::path::Style Style = + llvm::sys::path::is_absolute(WrittenFile) + ? llvm::sys::path::Style::native + : (Policy.MSVCFormatting + ? llvm::sys::path::Style::windows_backslash + : llvm::sys::path::Style::posix); + llvm::sys::path::native(WrittenFile, Style); + OS << WrittenFile << ':' << PLoc.getLine() << ':' << PLoc.getColumn(); } } @@ -1330,21 +1420,18 @@ void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) { // If this is a class template specialization, print the template // arguments. - if (const auto *Spec = dyn_cast(D)) { - ArrayRef Args; - TypeSourceInfo *TAW = Spec->getTypeAsWritten(); - if (!Policy.PrintCanonicalTypes && TAW) { - const TemplateSpecializationType *TST = - cast(TAW->getType()); - Args = TST->template_arguments(); - } else { - const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); - Args = TemplateArgs.asArray(); - } + if (auto *S = dyn_cast(D)) { + const TemplateParameterList *TParams = + S->getSpecializedTemplate()->getTemplateParameters(); + const ASTTemplateArgumentListInfo *TArgAsWritten = + S->getTemplateArgsAsWritten(); IncludeStrongLifetimeRAII Strong(Policy); - printTemplateArgumentList( - OS, Args, Policy, - Spec->getSpecializedTemplate()->getTemplateParameters()); + if (TArgAsWritten && !Policy.PrintCanonicalTypes) + printTemplateArgumentList(OS, TArgAsWritten->arguments(), Policy, + TParams); + else + printTemplateArgumentList(OS, S->getTemplateArgs().asArray(), Policy, + TParams); } OS << ""; @@ -1499,7 +1586,7 @@ void TypePrinter::printElaboratedBefore(const ElaboratedType *T, // The tag definition will take care of these. if (!Policy.IncludeTagDefinition) { OS << TypeWithKeyword::getKeywordName(T->getKeyword()); - if (T->getKeyword() != ETK_None) OS << " "; + if (T->getKeyword() != ElaboratedTypeKeyword::None) OS << " "; NestedNameSpecifier *Qualifier = T->getQualifier(); if (Qualifier) Qualifier->print(OS, Policy); } @@ -1533,9 +1620,10 @@ void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) { void TypePrinter::printDependentNameBefore(const DependentNameType *T, raw_ostream &OS) { - if (T->getKeyword() != ETK_None) { - OS << "" - << TypeWithKeyword::getKeywordName(T->getKeyword()) << " "; + OS << "" + << TypeWithKeyword::getKeywordName(T->getKeyword()) << " "; + if (T->getKeyword() != ElaboratedTypeKeyword::None) { + OS << " "; } T->getQualifier()->print(OS, Policy); @@ -1551,9 +1639,10 @@ void TypePrinter::printDependentTemplateSpecializationBefore( const DependentTemplateSpecializationType *T, raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); - if (T->getKeyword() != ETK_None) { - OS << "" - << TypeWithKeyword::getKeywordName(T->getKeyword()) << " "; + OS << "" + << TypeWithKeyword::getKeywordName(T->getKeyword()) << " "; + if (T->getKeyword() != ElaboratedTypeKeyword::None) { + OS << " "; } if (T->getQualifier()) T->getQualifier()->print(OS, Policy); @@ -1577,6 +1666,34 @@ void TypePrinter::printPackExpansionAfter(const PackExpansionType *T, OS << "..."; } +static void printCountAttributedImpl(const CountAttributedType *T, + raw_ostream &OS, + const PrintingPolicy &Policy) { + OS << ' '; + if (T->isCountInBytes() && T->isOrNull()) + OS << "__sized_by_or_null("; + else if (T->isCountInBytes()) + OS << "__sized_by("; + else if (T->isOrNull()) + OS << "__counted_by_or_null("; + else + OS << "__counted_by("; + if (T->getCountExpr()) T->getCountExpr()->printPretty(OS, nullptr, Policy); + OS << ')'; +} + +void TypePrinter::printCountAttributedBefore(const CountAttributedType *T, + raw_ostream &OS) { + printBefore(T->desugar(), OS); + if (!T->isArrayType()) printCountAttributedImpl(T, OS, Policy); +} + +void TypePrinter::printCountAttributedAfter(const CountAttributedType *T, + raw_ostream &OS) { + printAfter(T->desugar(), OS); + if (T->isArrayType()) printCountAttributedImpl(T, OS, Policy); +} + void TypePrinter::printAttributedBefore(const AttributedType *T, raw_ostream &OS) { // FIXME: Generate this with TableGen. @@ -1691,6 +1808,12 @@ void TypePrinter::printAttributedAfter(const AttributedType *T, case attr::BTFTypeTag: llvm_unreachable("BTFTypeTag attribute handled separately"); + case attr::HLSLResourceClass: + case attr::HLSLROV: + case attr::HLSLRawBuffer: + case attr::HLSLContainedType: + llvm_unreachable("HLSL resource type attributes handled separately"); + case attr::OpenCLPrivateAddressSpace: case attr::OpenCLGlobalAddressSpace: case attr::OpenCLGlobalDeviceAddressSpace: @@ -1703,7 +1826,12 @@ void TypePrinter::printAttributedAfter(const AttributedType *T, // AttributedType nodes for them. break; + case attr::CountedBy: + case attr::CountedByOrNull: + case attr::SizedBy: + case attr::SizedByOrNull: case attr::LifetimeBound: + case attr::LifetimeCaptureBy: case attr::TypeNonNull: case attr::TypeNullable: case attr::TypeNullableResult: @@ -1719,6 +1847,19 @@ void TypePrinter::printAttributedAfter(const AttributedType *T, case attr::AddressSpace: case attr::CmseNSCall: case attr::AnnotateType: + case attr::WebAssemblyFuncref: + case attr::ArmAgnostic: + case attr::ArmStreaming: + case attr::ArmStreamingCompatible: + case attr::ArmIn: + case attr::ArmOut: + case attr::ArmInOut: + case attr::ArmPreserves: + case attr::NonBlocking: + case attr::NonAllocating: + case attr::Blocking: + case attr::Allocating: + case attr::SwiftAttr: llvm_unreachable("This attribute should have been handled already"); case attr::NSReturnsRetained: @@ -1792,6 +1933,15 @@ void TypePrinter::printAttributedAfter(const AttributedType *T, case attr::PreserveAll: OS << "preserve_all"; break; + case attr::M68kRTD: + OS << "m68k_rtd"; + break; + case attr::PreserveNone: + OS << "preserve_none"; + break; + case attr::RISCVVectorCC: + OS << "riscv_vector_cc"; + break; case attr::NoDeref: OS << "noderef"; break; @@ -1816,6 +1966,30 @@ void TypePrinter::printBTFTagAttributedAfter(const BTFTagAttributedType *T, printAfter(T->getWrappedType(), OS); } +void TypePrinter::printHLSLAttributedResourceBefore( + const HLSLAttributedResourceType *T, raw_ostream &OS) { + printBefore(T->getWrappedType(), OS); +} + +void TypePrinter::printHLSLAttributedResourceAfter( + const HLSLAttributedResourceType *T, raw_ostream &OS) { + printAfter(T->getWrappedType(), OS); + const HLSLAttributedResourceType::Attributes &Attrs = T->getAttrs(); + OS << " [[hlsl::resource_class(" + << HLSLResourceClassAttr::ConvertResourceClassToStr(Attrs.ResourceClass) + << ")]]"; + if (Attrs.IsROV) OS << " [[hlsl::is_rov]]"; + if (Attrs.RawBuffer) OS << " [[hlsl::raw_buffer]]"; + + QualType ContainedTy = T->getContainedType(); + if (!ContainedTy.isNull()) { + OS << " [[hlsl::contained_type("; + printBefore(ContainedTy, OS); + printAfter(ContainedTy, OS); + OS << ")]]"; + } +} + void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T, raw_ostream &OS) { OS << "" << T->getDecl()->getName() @@ -2027,8 +2201,7 @@ static bool isSubstitutedTemplateArgument(ASTContext &Ctx, TemplateArgument Arg, } } - if (Arg.getKind() != Pattern.getKind()) - return false; + if (Arg.getKind() != Pattern.getKind()) return false; if (Arg.getKind() == TemplateArgument::Type) return isSubstitutedType(Ctx, Arg.getAsType(), Pattern.getAsType(), Args, @@ -2046,32 +2219,6 @@ static bool isSubstitutedTemplateArgument(ASTContext &Ctx, TemplateArgument Arg, return false; } -/// Make a best-effort determination of whether the type T can be produced by -/// substituting Args into the default argument of Param. -static bool isSubstitutedDefaultArgument(ASTContext &Ctx, TemplateArgument Arg, - const NamedDecl *Param, - ArrayRef Args, - unsigned Depth) { - // An empty pack is equivalent to not providing a pack argument. - if (Arg.getKind() == TemplateArgument::Pack && Arg.pack_size() == 0) - return true; - - if (auto *TTPD = dyn_cast(Param)) { - return TTPD->hasDefaultArgument() && - isSubstitutedTemplateArgument(Ctx, Arg, TTPD->getDefaultArgument(), - Args, Depth); - } else if (auto *TTPD = dyn_cast(Param)) { - return TTPD->hasDefaultArgument() && - isSubstitutedTemplateArgument( - Ctx, Arg, TTPD->getDefaultArgument().getArgument(), Args, Depth); - } else if (auto *NTTPD = dyn_cast(Param)) { - return NTTPD->hasDefaultArgument() && - isSubstitutedTemplateArgument(Ctx, Arg, NTTPD->getDefaultArgument(), - Args, Depth); - } - return false; -} - template static void printTo(raw_ostream &OS, ArrayRef Args, const PrintingPolicy &Policy, diff --git a/unittests/AST/ASTBuilder.cpp b/unittests/AST/ASTBuilder.cpp index e48cd43d..ad41f6c2 100644 --- a/unittests/AST/ASTBuilder.cpp +++ b/unittests/AST/ASTBuilder.cpp @@ -534,8 +534,7 @@ TEST_SUITE("ASTBuilder::CreateStructDecl") { auto record_decl{ast.CreateStructDecl(tudecl, "s")}; REQUIRE(record_decl != nullptr); CHECK(record_decl->getName() == "s"); - CHECK(record_decl->getTagKind() == - clang::RecordDecl::TagKind::TTK_Struct); + CHECK(record_decl->getTagKind() == clang::RecordDecl::TagKind::Struct); } } } @@ -552,8 +551,7 @@ TEST_SUITE("ASTBuilder::CreateUnionDecl") { auto record_decl{ast.CreateUnionDecl(tudecl, "u")}; REQUIRE(record_decl != nullptr); CHECK(record_decl->getName() == "u"); - CHECK(record_decl->getTagKind() == - clang::RecordDecl::TagKind::TTK_Union); + CHECK(record_decl->getTagKind() == clang::RecordDecl::TagKind::Union); } } } @@ -592,7 +590,7 @@ TEST_SUITE("ASTBuilder::CreateFieldDecl") { REQUIRE(field_decl != nullptr); CHECK(field_decl->getType() == type); CHECK(field_decl->getName() == "f"); - CHECK(field_decl->getBitWidthValue(ctx) == 3); + CHECK(field_decl->getBitWidthValue() == 3); } } } @@ -1130,8 +1128,8 @@ TEST_SUITE("ASTBuilder::CreateCompoundLit") { std::vector exprs; auto init_list{ast.CreateInitList(exprs)}; GIVEN("int[] type") { - auto type{ctx.getIncompleteArrayType( - ctx.IntTy, clang::ArrayType::ArraySizeModifier(), 0)}; + auto type{ctx.getIncompleteArrayType(ctx.IntTy, + clang::ArraySizeModifier(), 0)}; THEN("return (int[]){}") { auto comp_lit{ast.CreateCompoundLit(type, init_list)}; REQUIRE(comp_lit != nullptr); From 05d69ef40a826739eae26c876b0d03e423a805f7 Mon Sep 17 00:00:00 2001 From: AkshayK Date: Mon, 12 May 2025 17:32:51 -0400 Subject: [PATCH 2/2] Create opaque ptr --- lib/AST/Util.cpp | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/lib/AST/Util.cpp b/lib/AST/Util.cpp index e3f28cf6..1180c7ab 100644 --- a/lib/AST/Util.cpp +++ b/lib/AST/Util.cpp @@ -462,12 +462,9 @@ clang::QualType DecompilationContext::GetQualType(llvm::Type *type) { case llvm::Type::PointerTyID: { auto ptr_type{llvm::cast(type)}; - auto pointee_type = ptr_type->getContainedType(0); - if (!pointee_type || pointee_type->isVoidTy()) { - result = ast_ctx.VoidPtrTy; - } else { - result = ast_ctx.getPointerType(GetQualType(pointee_type)); - } + // With opaque pointers, we can't get element type directly from the + // pointer; Use the context's void pointer type as the default + result = ast_ctx.VoidPtrTy; } break; case llvm::Type::ArrayTyID: {