Integrate LLVM to llvm/llvm-project@1bd41d70d179 (#25129) The upstream LLVM bazel build broke, hence I cherry-picked this fix commit: - https://github.com/llvm/llvm-project/commit/aa5c7b777908364447188c64fbf737141af496d1 Moreover, I had to make some changes to IREE itself: 1) Store a global `LibraryOptionsContext` - needed because `PassBuilder` now takes a `LLVMContext&` with those options - `PipelineTuningOptions` combines settings supplied by IREE with those provided by the context - see https://github.com/llvm/llvm-project/pull/233150 2) Remove workaround for AMDGPU loop unrolling - no longer needed as of https://github.com/llvm/llvm-project/pull/223291 - this used to be handled in `ROCMTarget.cpp` by overriding an option 3) Adapt to target-specific passes being split out of MLIRGpuTransforms - see https://github.com/llvm/llvm-project/pull/234903 - AMD-specific `populateGpu...Patterns` now live in MLIRGPUROCDLTransforms - header is `mlir/Dialect/GPU/Transforms/ROCDL/Passes.h` - still need to link `iree_compiler_API_SharedImpl` against the now-split target libs, because MLIRCAPIGPU references them 4) Update lit tests related to softmax, which now uses a finite reduction identity - see https://github.com/llvm/llvm-project/pull/232257 5) Adjust LLVMGPULegalizeNDVectors to work with new `tensor.extract` folding - see https://github.com/llvm/llvm-project/pull/228686 - added two lit cases in `legalize_nd_vectors.mlir` 6) Remove workaround for packed reductions - fixed in upstream by: https://github.com/llvm/llvm-project/pull/221430 - keeping it would remap index twice, which would be incorrect Assisted-by: Codex Signed-off-by: Maksymilian B. Knust <knust@roofline.ai>
diff --git a/build_tools/cmake/iree_renamed_link.cmake b/build_tools/cmake/iree_renamed_link.cmake index c993ad0..07ce918 100644 --- a/build_tools/cmake/iree_renamed_link.cmake +++ b/build_tools/cmake/iree_renamed_link.cmake
@@ -224,10 +224,16 @@ # The closure is renamed too, or the references above find nothing. It keeps # selective extraction, so the same objects land as in an unrenamed link. + # Include the implementations used by the embedded MLIRCAPIGPU objects: + # object-library dependencies omit these owning C API library dependencies. iree_collect_static_link_closure(_closure_static_libs _closure_other ${_object_libs} MLIRExportSMTLIB MLIRTargetLLVMIRImport + MLIRGPUNVVMTransforms + MLIRGPUROCDLTransforms + MLIRGPUSPIRVTransforms + MLIRGPUXeVMTransforms ) set(_closure_archives) foreach(_lib ${_closure_static_libs})
diff --git a/compiler/plugins/target/CUDA/CUDATarget.cpp b/compiler/plugins/target/CUDA/CUDATarget.cpp index 50bfa18..2dd3cec 100644 --- a/compiler/plugins/target/CUDA/CUDATarget.cpp +++ b/compiler/plugins/target/CUDA/CUDATarget.cpp
@@ -14,6 +14,7 @@ #include "iree/compiler/Dialect/HAL/Utils/LLVMLinkerUtils.h" #include "iree/compiler/PluginAPI/Client.h" #include "iree/compiler/Utils/FlatbufferUtils.h" +#include "iree/compiler/Utils/OptionUtils.h" #include "iree/compiler/Utils/StringUtils.h" #include "iree/compiler/Utils/ToolUtils.h" #include "iree/schemas/cuda_executable_def_builder.h" @@ -347,7 +348,7 @@ fam.registerPass([&] { return targetMachine.getTargetIRAnalysis(); }); - llvm::PipelineTuningOptions pto; + llvm::PipelineTuningOptions pto(&module.getContext().getLibraryOptions()); pto.SLPVectorization = false; llvm::PassInstrumentationCallbacks pic; @@ -355,7 +356,8 @@ llvm::StandardInstrumentations si(module.getContext(), false); si.registerCallbacks(pic, &mam); - llvm::PassBuilder pb(&targetMachine, pto, std::nullopt, &pic); + llvm::PassBuilder pb(module.getContext(), &targetMachine, pto, std::nullopt, + &pic); llvm::ModulePassManager mpm; StringRef nnvmReflectPassName = "nvvm-reflect"; if (pb.parsePassPipeline(mpm, nnvmReflectPassName)) { @@ -536,6 +538,7 @@ // Perform the translation in a separate context to avoid any // multi-threading issues. llvm::LLVMContext context; + context.getLibraryOptions().assign(*commandLineOptions); std::unique_ptr<llvm::Module> llvmModule = mlir::translateModuleToLLVMIR(innerModuleOp, context, libraryName); @@ -587,8 +590,10 @@ if (target == nullptr) { return variantOp.emitError() << "cannot initialize target triple"; } + llvm::TargetOptions llvmOptions; + llvmOptions.MCOptions.LibraryOptions = &context.getLibraryOptions(); targetMachine.reset(target->createTargetMachine( - triple, targetArch, targetFeatures, {}, {})); + triple, targetArch, targetFeatures, llvmOptions, {})); if (targetMachine == nullptr) { return variantOp.emitError() << "cannot initialize target machine"; }
diff --git a/compiler/plugins/target/LLVMCPU/LLVMCPUTarget.cpp b/compiler/plugins/target/LLVMCPU/LLVMCPUTarget.cpp index db7b4bd..11ec7df 100644 --- a/compiler/plugins/target/LLVMCPU/LLVMCPUTarget.cpp +++ b/compiler/plugins/target/LLVMCPU/LLVMCPUTarget.cpp
@@ -31,6 +31,7 @@ #include "iree/compiler/PluginAPI/Client.h" #include "iree/compiler/Utils/EmbeddedDataDirectory.h" #include "iree/compiler/Utils/ModuleUtils.h" +#include "iree/compiler/Utils/OptionUtils.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Bitcode/BitcodeReader.h" @@ -294,6 +295,7 @@ // Perform the translation in a separate context to avoid any // multi-threading issues. llvm::LLVMContext context; + context.getLibraryOptions().assign(*commandLineOptions); auto maybeTarget = getVariantTarget(variantOp); if (!maybeTarget) { return failure();
diff --git a/compiler/plugins/target/LLVMCPU/LLVMIRPasses.cpp b/compiler/plugins/target/LLVMCPU/LLVMIRPasses.cpp index 2b482ef..03f628b 100644 --- a/compiler/plugins/target/LLVMCPU/LLVMIRPasses.cpp +++ b/compiler/plugins/target/LLVMCPU/LLVMIRPasses.cpp
@@ -38,8 +38,17 @@ /*DebugLogging=*/false); standardInstrumentations.registerCallbacks(passInstrumentationCallbacks); - llvm::PassBuilder passBuilder(machine, target.pipelineTuningOptions, {}, - &passInstrumentationCallbacks); + llvm::PipelineTuningOptions tuningOptions( + &module->getContext().getLibraryOptions()); + tuningOptions.LoopInterleaving = + target.pipelineTuningOptions.LoopInterleaving; + tuningOptions.LoopVectorization = + target.pipelineTuningOptions.LoopVectorization; + tuningOptions.LoopUnrolling = target.pipelineTuningOptions.LoopUnrolling; + tuningOptions.SLPVectorization = + target.pipelineTuningOptions.SLPVectorization; + llvm::PassBuilder passBuilder(module->getContext(), machine, tuningOptions, + {}, &passInstrumentationCallbacks); llvm::AAManager aa = passBuilder.buildDefaultAAPipeline(); functionAnalysisManager.registerPass([&] { return std::move(aa); });
diff --git a/compiler/plugins/target/LLVMCPU/LLVMTargetOptions.cpp b/compiler/plugins/target/LLVMCPU/LLVMTargetOptions.cpp index 26f06f6..366edf0 100644 --- a/compiler/plugins/target/LLVMCPU/LLVMTargetOptions.cpp +++ b/compiler/plugins/target/LLVMCPU/LLVMTargetOptions.cpp
@@ -9,6 +9,7 @@ #include "compiler/plugins/target/LLVMCPU/ResolveCPUAndCPUFeatures.h" #include "iree/compiler/Codegen/LLVMCPU/Utils.h" #include "iree/compiler/Codegen/Utils/CPUUtils.h" +#include "iree/compiler/Utils/OptionUtils.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/StringRef.h" #include "llvm/Analysis/TargetTransformInfo.h" @@ -433,6 +434,7 @@ // If anyone comes across this: it'd be great if getTargetTransformInfo // could be called without requiring a function. llvm::LLVMContext llvmContext; + llvmContext.getLibraryOptions().assign(*commandLineOptions); auto llvmModule = std::make_unique<llvm::Module>("dummy_module", llvmContext); llvmModule->setDataLayout(dataLayout); @@ -468,11 +470,12 @@ return nullptr; } llvm::Triple triple(target.getTriple()); + auto llvmTargetOptions = target.llvmTargetOptions; + llvmTargetOptions.MCOptions.LibraryOptions = &*commandLineOptions; std::unique_ptr<llvm::TargetMachine> machine(llvmTarget->createTargetMachine( triple, target.getCpu() /* cpu e.g k8 */, - target.getCpuFeatures() /* cpu features e.g avx512f */, - target.llvmTargetOptions, llvm::Reloc::Model::PIC_, {}, - target.codeGenOptLevel, + target.getCpuFeatures() /* cpu features e.g avx512f */, llvmTargetOptions, + llvm::Reloc::Model::PIC_, {}, target.codeGenOptLevel, /*JIT=*/false)); return machine; }
diff --git a/compiler/plugins/target/ROCM/ROCMTarget.cpp b/compiler/plugins/target/ROCM/ROCMTarget.cpp index c8b1493..0f46d7e 100644 --- a/compiler/plugins/target/ROCM/ROCMTarget.cpp +++ b/compiler/plugins/target/ROCM/ROCMTarget.cpp
@@ -32,6 +32,7 @@ #include "iree/compiler/PluginAPI/Client.h" #include "iree/compiler/Utils/EmbeddedDataDirectory.h" #include "iree/compiler/Utils/FlatbufferUtils.h" +#include "iree/compiler/Utils/OptionUtils.h" #include "iree/compiler/Utils/ToolUtils.h" #include "iree/schemas/amdgpu_executable_def_builder.h" #include "iree/schemas/hip_executable_def_builder.h" @@ -612,25 +613,6 @@ llvm::TargetMachine &targetMachine, bool slpVectorization, std::string &outPassesString) { - // Workaround for upstream LLVM PR llvm/llvm-project#194924 (commit - // b09174b41e7e, "[AMDGPU] Enable runtime loop unrolling") which set - // UP.PartialThreshold = UP.Threshold / 4 (75 for AMDGPU) - // in AMDGPUTTIImpl::getUnrollingPreferences, regressing partial unrolling - // of small constant-trip-count reduction loops. Restore the prior - // un-overridden LLVM default (150) by bumping the cl::opt occurrence - // count, which makes LoopUnrollPass apply the override (see - // LoopUnrollPass.cpp gatherUnrollingPreferences). Skipped when the user - // already set --unroll-partial-threshold so an explicit override still - // wins. Safe to remove once the upstream regression is fixed. - auto ®isteredCLOpts = llvm::cl::getRegisteredOptions(); - auto unrollOptIt = registeredCLOpts.find("unroll-partial-threshold"); - if (unrollOptIt != registeredCLOpts.end() && - unrollOptIt->second->getNumOccurrences() == 0) { - unrollOptIt->second->addOccurrence(/*pos=*/0, - /*ArgName=*/"unroll-partial-threshold", - /*Value=*/"150"); - } - llvm::LoopAnalysisManager lam; llvm::FunctionAnalysisManager fam; llvm::CGSCCAnalysisManager cgam; @@ -638,7 +620,7 @@ fam.registerPass([&] { return targetMachine.getTargetIRAnalysis(); }); - llvm::PipelineTuningOptions pto; + llvm::PipelineTuningOptions pto(&module.getContext().getLibraryOptions()); pto.SLPVectorization = slpVectorization; llvm::PassInstrumentationCallbacks pic; @@ -646,7 +628,8 @@ llvm::StandardInstrumentations si(module.getContext(), false); si.registerCallbacks(pic, &mam); - llvm::PassBuilder pb(&targetMachine, pto, std::nullopt, &pic); + llvm::PassBuilder pb(module.getContext(), &targetMachine, pto, std::nullopt, + &pic); llvm::ModulePassManager mpm; pb.registerModuleAnalyses(mam); pb.registerCGSCCAnalyses(cgam); @@ -794,6 +777,7 @@ // Perform the translation in a separate context to avoid any // multi-threading issues. llvm::LLVMContext context; + context.getLibraryOptions().assign(*commandLineOptions); std::unique_ptr<llvm::Module> llvmModule = mlir::translateModuleToLLVMIR(innerModuleOp, context, libraryName); if (!llvmModule) { @@ -834,6 +818,7 @@ return variantOp.emitError() << "cannot initialize target triple"; } llvm::TargetOptions opt; + opt.MCOptions.LibraryOptions = &context.getLibraryOptions(); // Be extra cautious while this is less tested, and prevent unknown // fallbacks from global isel. // @@ -1029,11 +1014,13 @@ return variantOp.emitError() << "cannot find SPIR-V target: " << spirvError; } + llvm::TargetOptions spirvOptions; + spirvOptions.MCOptions.LibraryOptions = &context.getLibraryOptions(); auto spirvTM = std::unique_ptr<llvm::TargetMachine>( - spirvTarget->createTargetMachine( - spirvTriple, /*CPU=*/"", /*Features=*/"", llvm::TargetOptions{}, - llvm::Reloc::PIC_, std::nullopt, - llvm::CodeGenOptLevel::Default)); + spirvTarget->createTargetMachine(spirvTriple, /*CPU=*/"", + /*Features=*/"", spirvOptions, + llvm::Reloc::PIC_, std::nullopt, + llvm::CodeGenOptLevel::Default)); if (!spirvTM) { return variantOp.emitError() << "cannot create SPIR-V target machine";
diff --git a/compiler/src/iree/compiler/API/CMakeLists.txt b/compiler/src/iree/compiler/API/CMakeLists.txt index af3edc9..abe27cc 100644 --- a/compiler/src/iree/compiler/API/CMakeLists.txt +++ b/compiler/src/iree/compiler/API/CMakeLists.txt
@@ -232,6 +232,16 @@ ${_EXPORT_OBJECT_DEPS} ) + # The embedded MLIRCAPIGPU objects expose target-specific pass constructors. + # Collecting object-library dependencies would not bring in all dependencies + # of the owning C API library. + target_link_libraries(iree_compiler_API_SharedImpl PRIVATE + MLIRGPUNVVMTransforms + MLIRGPUROCDLTransforms + MLIRGPUSPIRVTransforms + MLIRGPUXeVMTransforms + ) + # Link MLIRTargetLLVMIRImport and MLIRExportSMTLIB directly since they are # not exported as object libraries. target_link_libraries(iree_compiler_API_SharedImpl PRIVATE
diff --git a/compiler/src/iree/compiler/API/Internal/BUILD.bazel b/compiler/src/iree/compiler/API/Internal/BUILD.bazel index 4de946e..248af39 100644 --- a/compiler/src/iree/compiler/API/Internal/BUILD.bazel +++ b/compiler/src/iree/compiler/API/Internal/BUILD.bazel
@@ -35,6 +35,7 @@ "//compiler/src/iree/compiler/Tools:init_passes_and_dialects", "//compiler/src/iree/compiler/Tools:version", "//compiler/src/iree/compiler/Utils", + "@llvm-project//llvm:Core", "@llvm-project//llvm:Passes", "@llvm-project//llvm:Remarks", "@llvm-project//llvm:Support", @@ -87,6 +88,7 @@ "//compiler/src/iree/compiler/PluginAPI:PluginManager", "//compiler/src/iree/compiler/Tools:init_llvmir_translations", "//compiler/src/iree/compiler/Tools:init_passes_and_dialects", + "//compiler/src/iree/compiler/Utils", "@llvm-project//llvm:Support", "@llvm-project//mlir:Debug", "@llvm-project//mlir:IR",
diff --git a/compiler/src/iree/compiler/API/Internal/CMakeLists.txt b/compiler/src/iree/compiler/API/Internal/CMakeLists.txt index 86315b4..7655971 100644 --- a/compiler/src/iree/compiler/API/Internal/CMakeLists.txt +++ b/compiler/src/iree/compiler/API/Internal/CMakeLists.txt
@@ -19,6 +19,7 @@ "CompilerDriver.cpp" "Diagnostics.cpp" DEPS + LLVMCore LLVMPasses LLVMRemarks LLVMSupport @@ -89,6 +90,7 @@ iree::compiler::PluginAPI::PluginManager iree::compiler::Tools::init_llvmir_translations iree::compiler::Tools::init_passes_and_dialects + iree::compiler::Utils iree::compiler::bindings::c::headers PUBLIC )
diff --git a/compiler/src/iree/compiler/API/Internal/CompilerDriver.cpp b/compiler/src/iree/compiler/API/Internal/CompilerDriver.cpp index e7c80cb..0dc4e36 100644 --- a/compiler/src/iree/compiler/API/Internal/CompilerDriver.cpp +++ b/compiler/src/iree/compiler/API/Internal/CompilerDriver.cpp
@@ -53,12 +53,14 @@ #include "iree/compiler/Tools/init_passes.h" #include "iree/compiler/Tools/version.h" #include "iree/compiler/Utils/ModuleUtils.h" +#include "iree/compiler/Utils/OptionUtils.h" #include "iree/compiler/Utils/TracingUtils.h" #include "iree/compiler/embedding_api.h" #include "iree/compiler/mlir_interop.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/ScopeExit.h" #include "llvm/ADT/StringExtras.h" +#include "llvm/IR/LLVMContext.h" #include "llvm/Passes/PassBuilder.h" #include "llvm/Remarks/RemarkFormat.h" #include "llvm/Support/Allocator.h" @@ -385,6 +387,7 @@ // Command line handling. bool usesCommandLine = false; + bool printPipelinePasses = false; // Populated and retained if we have to copy and handle our own permuted // argv (i.e. Windows). Otherwise, not used. llvm::SmallVector<const char *> retainedArgv; @@ -1149,12 +1152,6 @@ std::string(path.begin(), path.end())})); } -// Returns true if LLVM's -print-pipeline-passes flag was given. -static bool shouldPrintPipelinePasses() { - llvm::PassBuilder passBuilder; - return passBuilder.getPrintPipelinePasses().has_value(); -} - bool Invocation::runPipeline(enum iree_compiler_pipeline_t pipeline) { auto passManager = createPassManager(); @@ -1242,7 +1239,7 @@ return false; } - if (shouldPrintPipelinePasses()) { + if (session.globalInit.printPipelinePasses) { passManager->dump(); } if (failed(passManager->run(parsedModule))) { @@ -1260,7 +1257,7 @@ return false; } - if (shouldPrintPipelinePasses()) { + if (session.globalInit.printPipelinePasses) { passManager->dump(); } if (failed(passManager->run(parsedModule))) { @@ -1536,7 +1533,15 @@ llvm::install_out_of_memory_new_handler(); } - llvm::cl::ParseCommandLineOptions(argc, argv, banner); + llvm::cl::parseCommandLineOptions(*mlir::iree_compiler::commandLineOptions, + llvm::ArrayRef<const char *>(argv, argc), + banner); + llvm::LLVMContext llvmContext; + llvmContext.getLibraryOptions().assign( + *mlir::iree_compiler::commandLineOptions); + llvm::PassBuilder passBuilder(llvmContext); + globalInit->printPipelinePasses = + passBuilder.getPrintPipelinePasses().has_value(); // Reject load flags that were not handled before global initialization. if (!mlir::iree_compiler::verifyDynamicPluginFlags(llvm::errs())) { exit(EXIT_FAILURE);
diff --git a/compiler/src/iree/compiler/API/Internal/IREEOptToolEntryPoint.cpp b/compiler/src/iree/compiler/API/Internal/IREEOptToolEntryPoint.cpp index b1c50b2..3ca7085 100644 --- a/compiler/src/iree/compiler/API/Internal/IREEOptToolEntryPoint.cpp +++ b/compiler/src/iree/compiler/API/Internal/IREEOptToolEntryPoint.cpp
@@ -14,6 +14,7 @@ #include "iree/compiler/Tools/init_dialects.h" #include "iree/compiler/Tools/init_llvmir_translations.h" #include "iree/compiler/Tools/init_passes.h" +#include "iree/compiler/Utils/OptionUtils.h" #include "iree/compiler/tool_entry_points_api.h" #include "llvm/Support/InitLLVM.h" #include "llvm/Support/Process.h" @@ -92,7 +93,8 @@ } // Parse pass names in main to ensure static initialization completed. - cl::ParseCommandLineOptions(argc, argv, helpHeader); + cl::parseCommandLineOptions(*mlir::iree_compiler::commandLineOptions, + ArrayRef<const char *>(argv, argc), helpHeader); MlirOptMainConfig config = MlirOptMainConfig::createFromCLOptions(); // The local binder is meant for overriding session-level options, but for
diff --git a/compiler/src/iree/compiler/Codegen/Common/GPU/BUILD.bazel b/compiler/src/iree/compiler/Codegen/Common/GPU/BUILD.bazel index e657eb4..d67f771 100644 --- a/compiler/src/iree/compiler/Codegen/Common/GPU/BUILD.bazel +++ b/compiler/src/iree/compiler/Codegen/Common/GPU/BUILD.bazel
@@ -152,6 +152,7 @@ "@llvm-project//mlir:FuncDialect", "@llvm-project//mlir:FunctionInterfaces", "@llvm-project//mlir:GPUDialect", + "@llvm-project//mlir:GPUROCDLTransforms", "@llvm-project//mlir:GPUTransformOps", "@llvm-project//mlir:GPUTransforms", "@llvm-project//mlir:GPUUtils",
diff --git a/compiler/src/iree/compiler/Codegen/Common/GPU/CMakeLists.txt b/compiler/src/iree/compiler/Codegen/Common/GPU/CMakeLists.txt index 0145290..e348285 100644 --- a/compiler/src/iree/compiler/Codegen/Common/GPU/CMakeLists.txt +++ b/compiler/src/iree/compiler/Codegen/Common/GPU/CMakeLists.txt
@@ -116,6 +116,7 @@ MLIRFuncDialect MLIRFunctionInterfaces MLIRGPUDialect + MLIRGPUROCDLTransforms MLIRGPUTransformOps MLIRGPUTransforms MLIRGPUUtils
diff --git a/compiler/src/iree/compiler/Codegen/Common/GPU/ExpandGPUOps.cpp b/compiler/src/iree/compiler/Codegen/Common/GPU/ExpandGPUOps.cpp index 818b4cf..f3ddddb 100644 --- a/compiler/src/iree/compiler/Codegen/Common/GPU/ExpandGPUOps.cpp +++ b/compiler/src/iree/compiler/Codegen/Common/GPU/ExpandGPUOps.cpp
@@ -13,6 +13,7 @@ #include "mlir/Dialect/Arith/IR/Arith.h" #include "mlir/Dialect/GPU/IR/GPUDialect.h" #include "mlir/Dialect/GPU/Transforms/Passes.h" +#include "mlir/Dialect/GPU/Transforms/ROCDL/Passes.h" #include "mlir/Dialect/LLVMIR/ROCDLTargetInfo.h" #include "mlir/IR/IRMapping.h" #include "mlir/Interfaces/FunctionInterfaces.h"
diff --git a/compiler/src/iree/compiler/Codegen/Common/GPU/GPUPackPartialReductions.cpp b/compiler/src/iree/compiler/Codegen/Common/GPU/GPUPackPartialReductions.cpp index 390882f..9f27cbd 100644 --- a/compiler/src/iree/compiler/Codegen/Common/GPU/GPUPackPartialReductions.cpp +++ b/compiler/src/iree/compiler/Codegen/Common/GPU/GPUPackPartialReductions.cpp
@@ -8,7 +8,6 @@ #include "iree/compiler/Codegen/Dialect/GPU/IR/GPULoweringConfigUtils.h" #include "iree/compiler/Codegen/Dialect/GPU/IR/IREEGPUAttrs.h" #include "llvm/Support/DebugLog.h" -#include "mlir/Dialect/Affine/IR/AffineOps.h" #include "mlir/Dialect/Linalg/IR/Linalg.h" #include "mlir/Dialect/Linalg/Transforms/Transforms.h" #include "mlir/Dialect/Tensor/IR/Tensor.h" @@ -101,44 +100,9 @@ // To bypass this for now, this pass expects that padding should be done // properly before this pass. This pass is generally placed after // GPUApplyPaddingLevel, which is the only reason it works, otherwise it's - // wrong in general. The other problem with the transformation is it does - // not account for linalg.index in the body of the op. These commonly come - // up because general masking of reductions requires this. We fix up the index - // ops after the fact, but it would be better if linalg::pack just handled - // this correctly in the first place. The ideal solution is to implement a + // wrong in general. The ideal solution is to implement a // more general version of linalg::pack that works on IndexingOpInterface and // handles things correctly. - // - // Fix linalg.index ops in the body. After packing, dimension d is split into - // [outer=d, inner=numLoops+idx]. The original linalg.index d now refers to - // the outer dimension. Replace it with: outer * T + inner. - SmallVector<linalg::IndexOp> indexOps; - packedOp.getBlock()->walk( - [&](linalg::IndexOp op) { indexOps.push_back(op); }); - for (linalg::IndexOp indexOp : indexOps) { - uint64_t dim = indexOp.getDim(); - auto it = llvm::find(dimsToPackVec, dim); - if (it == dimsToPackVec.end()) { - continue; - } - unsigned idx = std::distance(dimsToPackVec.begin(), it); - unsigned innerDim = numLoops + idx; - int64_t tileSize = threadSizes[dim]; - - rewriter.setInsertionPointAfter(indexOp); - Location loc = indexOp.getLoc(); - Value inner = linalg::IndexOp::create(rewriter, loc, innerDim); - AffineExpr outerExpr, innerExpr; - bindDims(rewriter.getContext(), outerExpr, innerExpr); - OpFoldResult combined = affine::makeComposedFoldedAffineApply( - rewriter, loc, outerExpr * tileSize + innerExpr, - {getAsOpFoldResult(indexOp.getResult()), getAsOpFoldResult(inner)}); - Value combinedVal = - getValueOrCreateConstantIndexOp(rewriter, loc, combined); - rewriter.replaceUsesWithIf(indexOp, combinedVal, [&](OpOperand &use) { - return use.getOwner() != combinedVal.getDefiningOp(); - }); - } // Now build the updated lowering config for the packed op. // The packed op has numLoops + dimsToPackVec.size() dimensions.
diff --git a/compiler/src/iree/compiler/Codegen/Common/GPU/test/gpu_pack_partial_reductions.mlir b/compiler/src/iree/compiler/Codegen/Common/GPU/test/gpu_pack_partial_reductions.mlir index a71ebec..f8df165 100644 --- a/compiler/src/iree/compiler/Codegen/Common/GPU/test/gpu_pack_partial_reductions.mlir +++ b/compiler/src/iree/compiler/Codegen/Common/GPU/test/gpu_pack_partial_reductions.mlir
@@ -110,8 +110,10 @@ return %result : tensor<4xi32> } +// CHECK: #[[$INDEX_MAP:.+]] = affine_map<()[s0, s1] -> (s0 * 4 + s1)> // CHECK-LABEL: func.func @pack_with_linalg_index // CHECK: linalg.generic // CHECK: %[[OUTER:.+]] = linalg.index 1 : index // CHECK: %[[INNER:.+]] = linalg.index 2 : index -// CHECK: affine.apply #[[$INDEX_MAP:.+]]()[%[[OUTER]], %[[INNER]]] +// CHECK-NEXT: %[[INDEX:.+]] = affine.apply #[[$INDEX_MAP]]()[%[[OUTER]], %[[INNER]]] +// CHECK-NEXT: %{{.+}} = arith.index_cast %[[INDEX]] : index to i32
diff --git a/compiler/src/iree/compiler/Codegen/Common/test/decompose_softmax.mlir b/compiler/src/iree/compiler/Codegen/Common/test/decompose_softmax.mlir index 49f437f..5fda2ad 100644 --- a/compiler/src/iree/compiler/Codegen/Common/test/decompose_softmax.mlir +++ b/compiler/src/iree/compiler/Codegen/Common/test/decompose_softmax.mlir
@@ -13,7 +13,7 @@ // CHECK: func.func @softmax(%[[ARG0:[a-zA-Z0-9_]+]]: tensor<2x16x32xf32>) -> tensor<2x16x32xf32> { // CHECK-DAG: %[[D0:.+]] = tensor.empty() : tensor<2x16x32xf32> // CHECK-DAG: %[[D1:.+]] = tensor.empty() : tensor<2x16xf32> -// CHECK-DAG: %[[CST:.+]] = arith.constant 0xFFC00000 : f32 +// CHECK-DAG: %[[CST:.+]] = arith.constant -3.40282347E+38 : f32 // CHECK-DAG: %[[CST0:.+]] = arith.constant 0.0 // CHECK: %[[D2:.+]] = linalg.fill ins(%[[CST]] : f32) outs(%[[D1]] : tensor<2x16xf32>) -> tensor<2x16xf32> // CHECK: %[[D3:.+]] = linalg.generic {indexing_maps = [#[[MAP]], #[[MAP1]]], iterator_types = ["parallel", @@ -49,7 +49,7 @@ // CHECK-NO-FUSE: func.func @softmax(%[[ARG0:[a-zA-Z0-9_]+]]: tensor<2x16x32xf32>) -> tensor<2x16x32xf32> { // CHECK-NO-FUSE-DAG: %[[D0:.+]] = tensor.empty() : tensor<2x16x32xf32> // CHECK-NO-FUSE-DAG: %[[D1:.+]] = tensor.empty() : tensor<2x16xf32> -// CHECK-NO-FUSE-DAG: %[[CST:.+]] = arith.constant 0xFFC00000 : f32 +// CHECK-NO-FUSE-DAG: %[[CST:.+]] = arith.constant -3.40282347E+38 : f32 // CHECK-NO-FUSE-DAG: %[[CST0:.+]] = arith.constant 0.000000e+00 : f32 // CHECK-NO-FUSE: %[[D2:.+]] = linalg.fill ins(%[[CST]] : f32) outs(%[[D1]] : tensor<2x16xf32>) -> tensor<2x16xf32> // CHECK-NO-FUSE: %[[D3:.+]] = linalg.generic {indexing_maps = [#[[MAP]], #[[MAP1]]], iterator_types = ["parallel",
diff --git a/compiler/src/iree/compiler/Codegen/LLVMGPU/BUILD.bazel b/compiler/src/iree/compiler/Codegen/LLVMGPU/BUILD.bazel index 3845321..ecfcd94 100644 --- a/compiler/src/iree/compiler/Codegen/LLVMGPU/BUILD.bazel +++ b/compiler/src/iree/compiler/Codegen/LLVMGPU/BUILD.bazel
@@ -218,6 +218,7 @@ "@llvm-project//mlir:FuncTransforms", "@llvm-project//mlir:FunctionInterfaces", "@llvm-project//mlir:GPUDialect", + "@llvm-project//mlir:GPUROCDLTransforms", "@llvm-project//mlir:GPUToNVVMTransforms", "@llvm-project//mlir:GPUToROCDLTransforms", "@llvm-project//mlir:GPUTransformOps",
diff --git a/compiler/src/iree/compiler/Codegen/LLVMGPU/CMakeLists.txt b/compiler/src/iree/compiler/Codegen/LLVMGPU/CMakeLists.txt index 59d8522..be4c866 100644 --- a/compiler/src/iree/compiler/Codegen/LLVMGPU/CMakeLists.txt +++ b/compiler/src/iree/compiler/Codegen/LLVMGPU/CMakeLists.txt
@@ -153,6 +153,7 @@ MLIRFuncTransforms MLIRFunctionInterfaces MLIRGPUDialect + MLIRGPUROCDLTransforms MLIRGPUToNVVMTransforms MLIRGPUToROCDLTransforms MLIRGPUTransformOps
diff --git a/compiler/src/iree/compiler/Codegen/LLVMGPU/ConvertToROCDL.cpp b/compiler/src/iree/compiler/Codegen/LLVMGPU/ConvertToROCDL.cpp index 329305b..d60f967 100644 --- a/compiler/src/iree/compiler/Codegen/LLVMGPU/ConvertToROCDL.cpp +++ b/compiler/src/iree/compiler/Codegen/LLVMGPU/ConvertToROCDL.cpp
@@ -35,6 +35,7 @@ #include "mlir/Dialect/Arith/Transforms/Passes.h" #include "mlir/Dialect/GPU/IR/GPUDialect.h" #include "mlir/Dialect/GPU/Transforms/Passes.h" +#include "mlir/Dialect/GPU/Transforms/ROCDL/Passes.h" #include "mlir/Dialect/LLVMIR/ROCDLDialect.h" #include "mlir/Dialect/LLVMIR/ROCDLTargetInfo.h" #include "mlir/Dialect/MemRef/Transforms/Transforms.h"
diff --git a/compiler/src/iree/compiler/Codegen/LLVMGPU/LLVMGPULegalizeNDVectors.cpp b/compiler/src/iree/compiler/Codegen/LLVMGPU/LLVMGPULegalizeNDVectors.cpp index d7a87ac..c1f725e 100644 --- a/compiler/src/iree/compiler/Codegen/LLVMGPU/LLVMGPULegalizeNDVectors.cpp +++ b/compiler/src/iree/compiler/Codegen/LLVMGPU/LLVMGPULegalizeNDVectors.cpp
@@ -152,13 +152,16 @@ if (srcType.getRank() <= 1) { return failure(); } - if (op.hasDynamicPosition()) { - op.emitRemark() - << "dynamic positions on extract are intentionally disabled"; - return failure(); + ArrayRef<int64_t> staticPos = op.getStaticPosition(); + // Outer positions select a statically known 1-D slice. The innermost + // position may be dynamic: extract-chain folding can produce this form + // from a static slice extraction followed by a dynamic scalar extraction. + if (llvm::is_contained(staticPos.take_front(srcType.getRank() - 1), + ShapedType::kDynamic)) { + return rewriter.notifyMatchFailure(op, + "dynamic outer positions unsupported"); } - ArrayRef<int64_t> staticPos = op.getStaticPosition(); SmallVector<Value> srcValues(adaptor.getSource()); ArrayRef<int64_t> outerShape = srcType.getShape().drop_back(); SmallVector<int64_t> outerStrides = computeStrides(outerShape); @@ -176,9 +179,15 @@ if (hasInnerIndex) { // Scalar extraction: pick the 1-D vector, then extract the element. - rewriter.replaceOp(op, vector::ExtractOp::create(rewriter, op.getLoc(), - srcValues[offset], - staticPos.back())); + OpFoldResult innerPos; + if (op.hasDynamicPosition()) { + innerPos = adaptor.getDynamicPosition().front().front(); + } else { + innerPos = rewriter.getIndexAttr(staticPos.back()); + } + rewriter.replaceOp(op, vector::ExtractOp::create( + rewriter, op.getLoc(), srcValues[offset], + ArrayRef<OpFoldResult>{innerPos})); } else { // Sub-vector extraction: select a contiguous slice of converted values. SmallVector<Value> results(srcValues.begin() + offset,
diff --git a/compiler/src/iree/compiler/Codegen/LLVMGPU/test/ROCDL/pipeline_argcompare_tile_and_fuse.mlir b/compiler/src/iree/compiler/Codegen/LLVMGPU/test/ROCDL/pipeline_argcompare_tile_and_fuse.mlir index 6b7e725..052a250 100644 --- a/compiler/src/iree/compiler/Codegen/LLVMGPU/test/ROCDL/pipeline_argcompare_tile_and_fuse.mlir +++ b/compiler/src/iree/compiler/Codegen/LLVMGPU/test/ROCDL/pipeline_argcompare_tile_and_fuse.mlir
@@ -1,5 +1,7 @@ // RUN: iree-opt --split-input-file --iree-gpu-test-target=gfx942 \ // RUN: --iree-codegen-llvmgpu-rocdl-lowering-pipeline='include-llvm-lowering=false' %s | FileCheck %s +// RUN: iree-opt --split-input-file --iree-gpu-test-target=gfx942 \ +// RUN: --iree-codegen-llvmgpu-rocdl-lowering-pipeline='include-llvm-lowering=true' %s | FileCheck %s --check-prefix=LLVM // Small 3-D reduction over dim 0 (non-last-dim). Reduction size 2 is smaller // than subgroup size, so setReductionConfig rejects and falls through to @@ -37,10 +39,17 @@ } // Non-last-dim reduction over dim 0: the 3-D input is read as vector<2x1x1xf32> -// and shape_cast to vector<2xf32> before the scf.for reduction loop. +// and shape_cast to vector<1x1x2xf32> before the scf.for reduction loop. +// The dynamic innermost extraction must also survive full LLVM lowering. +// LLVM-LABEL: llvm.func @argcompare_small_3d_dim0 +// LLVM: llvm.extractelement {{.*}} : vector<2xf32> +// LLVM: llvm.fcmp "ogt" +// LLVM: llvm.select +// LLVM: llvm.return // CHECK-LABEL: func.func @argcompare_small_3d_dim0 -// CHECK: vector.shape_cast %{{.*}} : vector<2x1x1xf32> to vector<2xf32> -// CHECK: scf.for +// CHECK: %[[INPUT:.+]] = vector.shape_cast %{{.*}} : vector<2x1x1xf32> to vector<1x1x2xf32> +// CHECK: scf.for %[[I:[a-zA-Z0-9_]+]] = +// CHECK: vector.extract %[[INPUT]][0, 0, %[[I]]] : f32 from vector<1x1x2xf32> // CHECK: arith.cmpf ogt // CHECK: arith.select // CHECK: vector.transfer_write @@ -82,6 +91,8 @@ // Last-dim reduction: no transpose/shape_cast needed; input read directly as // vector<128xf32> and reduced via scf.for. +// LLVM-LABEL: llvm.func @argcompare_last_dim_reduction +// LLVM: llvm.return // CHECK-LABEL: func.func @argcompare_last_dim_reduction // CHECK-NOT: vector.transpose // CHECK: vector.transfer_read {{.*}} vector<128xf32> @@ -126,6 +137,8 @@ } // Unaligned reduction: input read as vector<100xf32>, reduced via scf.for. +// LLVM-LABEL: llvm.func @argcompare_unaligned_reduction +// LLVM: llvm.return // CHECK-LABEL: func.func @argcompare_unaligned_reduction // CHECK: vector.transfer_read {{.*}} vector<100xf32> // CHECK: scf.for @@ -168,6 +181,8 @@ } // f64 fallback: input read as vector<256xf64>, reduced via scf.for with f64 compare. +// LLVM-LABEL: llvm.func @argcompare_f64_fallback +// LLVM: llvm.return // CHECK-LABEL: func.func @argcompare_f64_fallback // CHECK: vector.transfer_read {{.*}} vector<256xf64> // CHECK: scf.for
diff --git a/compiler/src/iree/compiler/Codegen/LLVMGPU/test/legalize_nd_vectors.mlir b/compiler/src/iree/compiler/Codegen/LLVMGPU/test/legalize_nd_vectors.mlir index 05f6734..132b170 100644 --- a/compiler/src/iree/compiler/Codegen/LLVMGPU/test/legalize_nd_vectors.mlir +++ b/compiler/src/iree/compiler/Codegen/LLVMGPU/test/legalize_nd_vectors.mlir
@@ -120,6 +120,30 @@ // ----- +// A dynamic innermost index extracts from the statically selected 1-D slice. +func.func @extract_dynamic_inner(%v: vector<2x4xf32>, %i: index) -> f32 { + %0 = vector.extract %v[1, %i] : f32 from vector<2x4xf32> + return %0 : f32 +} +// CHECK-LABEL: func.func @extract_dynamic_inner( +// CHECK-SAME: %[[V0:.+]]: vector<4xf32>, %[[V1:.+]]: vector<4xf32>, %[[I:.+]]: index) +// CHECK: %[[S:.+]] = vector.extract %[[V1]][%[[I]]] : f32 from vector<4xf32> +// CHECK: return %[[S]] : f32 + +// ----- + +// Multiple static outer indices select the correct flattened slice. +func.func @extract_dynamic_inner_3d(%v: vector<2x3x4xf32>, %i: index) -> f32 { + %0 = vector.extract %v[1, 1, %i] : f32 from vector<2x3x4xf32> + return %0 : f32 +} +// CHECK-LABEL: func.func @extract_dynamic_inner_3d( +// CHECK-SAME: %[[V0:.+]]: vector<4xf32>, %[[V1:.+]]: vector<4xf32>, %[[V2:.+]]: vector<4xf32>, %[[V3:.+]]: vector<4xf32>, %[[V4:.+]]: vector<4xf32>, %[[V5:.+]]: vector<4xf32>, %[[I:.+]]: index) +// CHECK: %[[S:.+]] = vector.extract %[[V4]][%[[I]]] : f32 from vector<4xf32> +// CHECK: return %[[S]] : f32 + +// ----- + // Extracting a 2-D sub-vector from a 3-D vector selects the first group of flat vectors. func.func @extract_3d(%v: vector<2x3x4xf32>) -> vector<3x4xf32> { %0 = vector.extract %v[0] : vector<3x4xf32> from vector<2x3x4xf32>
diff --git a/compiler/src/iree/compiler/Codegen/LLVMGPU/test/reduction_pipeline_cuda.mlir b/compiler/src/iree/compiler/Codegen/LLVMGPU/test/reduction_pipeline_cuda.mlir index 839d280..c4b56cb 100644 --- a/compiler/src/iree/compiler/Codegen/LLVMGPU/test/reduction_pipeline_cuda.mlir +++ b/compiler/src/iree/compiler/Codegen/LLVMGPU/test/reduction_pipeline_cuda.mlir
@@ -155,13 +155,16 @@ } // CHECK-LABEL: func.func @softmax_singlesubgroup() +// CHECK: %[[MAX_INIT:.+]] = arith.constant dense<-3.40282347E+38> : vector<1x1x1x1x1x1xf32> // CHECK: scf.for {{.*}} -> (vector<1x1x1x1x1x1x1x1x1xf32>) { // CHECK: vector.transfer_read {{.*}} : memref<12x256x40960xf32, {{.*}}>, vector<1x1x4xf32> // CHECK: vector.multi_reduction <maxnumf>, {{.*}} {{.*}} : vector<1x1x1x1x1x1x1x1x1x1x1x4xf32> to vector<1x1x1x1x1x1x1x1x1xf32> // CHECK: arith.maxnumf {{.*}} : vector<1x1x1x1x1x1x1x1x1xf32> // CHECK: scf.yield -// CHECK: gpu.subgroup_reduce maxnumf -// CHECK: vector.broadcast %{{.*}} : f32 to vector<1x1x1x1x1x1x1x1x1x1x1x4xf32> +// CHECK: %[[SUBGROUP_MAX:.+]] = gpu.subgroup_reduce maxnumf +// CHECK: %[[MAX_BCAST:.+]] = vector.broadcast %[[SUBGROUP_MAX]] : f32 to vector<1x1x1x1x1x1xf32> +// CHECK: %[[MAX:.+]] = arith.maxnumf %[[MAX_BCAST]], %[[MAX_INIT]] : vector<1x1x1x1x1x1xf32> +// CHECK: vector.broadcast %[[MAX]] : vector<1x1x1x1x1x1xf32> to vector<1x1x1x1x1x1x1x1x1x1x1x4xf32> // CHECK: scf.for {{.*}} -> (vector<1x1x1x1x1x1x1x1x1xf32>) { // CHECK: vector.transfer_read // CHECK: arith.subf
diff --git a/compiler/src/iree/compiler/Codegen/SPIRV/test/lowering_reduction.mlir b/compiler/src/iree/compiler/Codegen/SPIRV/test/lowering_reduction.mlir index bd47786..7244a51 100644 --- a/compiler/src/iree/compiler/Codegen/SPIRV/test/lowering_reduction.mlir +++ b/compiler/src/iree/compiler/Codegen/SPIRV/test/lowering_reduction.mlir
@@ -278,6 +278,7 @@ // CHECK-LABEL: func.func @dynamic_softmax // CHECK-DAG: %[[ADD_PAD:.+]] = arith.constant dense<0.000000e+00> : vector<1xf16> // CHECK-DAG: %[[MIN_F16:.+]] = arith.constant dense<0xFE00> : vector<1xf16> +// CHECK-DAG: %[[MAX_INIT:.+]] = arith.constant -6.550400e+04 : f16 // CHECK-DAG: %[[C0:.+]] = arith.constant 0 : index // CHECK-DAG: %[[C64:.+]] = arith.constant 64 : index // CHECK-DAG: %[[PV:.+]] = ub.poison : f16 @@ -304,10 +305,11 @@ // CHECK: vector.transfer_read {{.*}} : memref<1x64xf16, #gpu.address_space<workgroup>>, vector<1xf16> // CHECK: %[[V11:.*]] = vector.extract {{.*}} : f16 from vector<1xf16> // CHECK: %[[MAXNUMF:.+]] = gpu.subgroup_reduce maxnumf %[[V11]] : (f16) -> f16 +// CHECK: %[[INITIALIZED_MAX:.+]] = arith.maxnumf %[[MAXNUMF]], %[[MAX_INIT]] : f16 // Do the elementwise scaling and second local reduction. // CHECK: vector.transfer_write %[[ADD_PAD]], %{{.*}} : vector<1xf16>, memref<1x64xf16, #gpu.address_space<workgroup>> -// CHECK: %[[MAXNUMF_BCAST:.+]] = vector.broadcast %[[MAXNUMF]] : f16 to vector<1xf16> +// CHECK: %[[MAXNUMF_BCAST:.+]] = vector.broadcast %[[INITIALIZED_MAX]] : f16 to vector<1xf16> // CHECK: scf.for {{.*}} %[[C0]] to %[[DYNAMIC_SIZE]] step %[[C64]] // CHECK: %[[MASK2:.+]] = vector.create_mask %{{.*}} : vector<1xi1> // CHECK: vector.transfer_read %{{.*}}, %[[MASK]] {{.*}} : memref<32x?xf16, #hal.descriptor_type<storage_buffer>>, vector<1xf16>
diff --git a/compiler/src/iree/compiler/Utils/OptionUtils.cpp b/compiler/src/iree/compiler/Utils/OptionUtils.cpp index dd65056..fb4377c 100644 --- a/compiler/src/iree/compiler/Utils/OptionUtils.cpp +++ b/compiler/src/iree/compiler/Utils/OptionUtils.cpp
@@ -12,6 +12,8 @@ namespace mlir::iree_compiler { +llvm::ManagedStatic<llvm::cl::LibraryOptionsContext> commandLineOptions; + llvm::ManagedStatic<llvm::DenseMap<llvm::StringRef, OptionsBinder::OptionInfo>> OptionsBinder::globalOptions;
diff --git a/compiler/src/iree/compiler/Utils/OptionUtils.h b/compiler/src/iree/compiler/Utils/OptionUtils.h index d1a503d..92b8f8a 100644 --- a/compiler/src/iree/compiler/Utils/OptionUtils.h +++ b/compiler/src/iree/compiler/Utils/OptionUtils.h
@@ -12,6 +12,7 @@ #include "llvm/Passes/OptimizationLevel.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" +#include "llvm/Support/LibraryOptionsContext.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/raw_ostream.h" #include "mlir/Support/LogicalResult.h" @@ -25,6 +26,12 @@ namespace mlir::iree_compiler { +// Process-wide LLVM library options, populated during command-line parsing and +// immutable during compilation. Empty (LLVM defaults) for embedding clients +// that do not initialize command-line options. The storage lives until +// llvm_shutdown(), outliving target machines. +extern llvm::ManagedStatic<llvm::cl::LibraryOptionsContext> commandLineOptions; + template <typename Ty> struct opt_initializer { llvm::StringRef parentName;
diff --git a/third_party/llvm-project b/third_party/llvm-project index d033127..1bd41d7 160000 --- a/third_party/llvm-project +++ b/third_party/llvm-project
@@ -1 +1 @@ -Subproject commit d033127d27ef0becca9d73edb667ac37442309a4 +Subproject commit 1bd41d70d179a1dd8daeab69b41ea55732df48bc