You are viewing a plain text version of this content. The canonical link for it is here.
Posted to discuss-archive@tvm.apache.org by "swjng (via GitHub)" <gi...@apache.org> on 2026/04/11 12:42:18 UTC

[PR] [BugFix][LLVM] Fix `insertDeclare` API mismatch for ROCm-bundled LLVM 20 [tvm]

swjng opened a new pull request, #19390:
URL: https://github.com/apache/tvm/pull/19390

   ## Problem
   
   Closes #18709.
   
   ROCm ships its own LLVM 20 build that still uses the pre-LLVM-20 `Instruction*` overload of `DIBuilder::insertDeclare`, while upstream LLVM 20 switched to `BasicBlock::iterator`. The previous guard `#if TVM_LLVM_VERSION >= 200` in `codegen_llvm.cc` broke ROCm users because their LLVM reports version 20 but lacks the new overload, causing a compile error like:
   
   ```
   error: no matching function for call to
     'llvm::DIBuilder::insertDeclare(..., llvm::BasicBlock::iterator)'
   note: candidate: insertDeclare(..., llvm::Instruction*)
   ```
   
   ## Fix
   
   Replace the version-number guard with a CMake `check_cxx_source_compiles` feature probe in `cmake/utils/FindLLVM.cmake`. The probe compiles a small test program that calls `insertDeclare` with `BasicBlock::iterator`. The result is exposed as the preprocessor macro `TVM_LLVM_INSERTDECLARE_USES_ITERATOR`.
   
   Three call sites in `src/target/llvm/codegen_llvm.cc` are updated to use `#if TVM_LLVM_INSERTDECLARE_USES_ITERATOR` instead of `#if TVM_LLVM_VERSION >= 200`.
   
   **Behavior by configuration:**
   | LLVM build | Probe result | Macro set | Code path |
   |---|---|---|---|
   | Upstream LLVM >= 20 with new overload | Compiles | Yes | `BasicBlock::iterator` |
   | ROCm LLVM 20 (old overload) | Fails | No | `Instruction*` |
   | Any LLVM < 20 | Probe skipped | No | `Instruction*` |
   
   ## Testing
   
   Tested locally with LLVM 20.1.8 (Ubuntu package, reports version 201). The probe correctly detects `Failed` (uses `Instruction*` path), `libtvm.so` builds cleanly, and all 39 LLVM codegen tests pass:
   
   ```
   tests/python/codegen/test_target_codegen_llvm.py::* 39 passed
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [BugFix][LLVM] Fix `insertDeclare` API mismatch for ROCm-bundled LLVM 20 [tvm]

Posted by "swjng (via GitHub)" <gi...@apache.org>.
swjng commented on PR #19390:
URL: https://github.com/apache/tvm/pull/19390#issuecomment-4285741582

   @tlopex Both points addressed in the latest commit. Could you take a look?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [BugFix][LLVM] Fix `insertDeclare` API mismatch for ROCm-bundled LLVM 20 [tvm]

Posted by "tlopex (via GitHub)" <gi...@apache.org>.
tlopex merged PR #19390:
URL: https://github.com/apache/tvm/pull/19390


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [BugFix][LLVM] Fix `insertDeclare` API mismatch for ROCm-bundled LLVM 20 [tvm]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #19390:
URL: https://github.com/apache/tvm/pull/19390#discussion_r3068009492


##########
cmake/utils/FindLLVM.cmake:
##########
@@ -237,4 +237,30 @@ macro(find_llvm use_llvm)
     message(FATAL_ERROR "TVM requires LLVM 15.0 or higher.")
   endif()
   message(STATUS "Found TVM_LLVM_HAS_AARCH64_TARGET=" ${TVM_LLVM_HAS_AARCH64_TARGET})
+
+  # Detect whether DIBuilder::insertDeclare accepts BasicBlock::iterator
+  # as the insertion point (upstream LLVM 20+) vs Instruction* (pre-LLVM 20
+  # and ROCm-bundled LLVM 20, which reports version 200 but lacks this overload).
+  if (${TVM_LLVM_VERSION} GREATER_EQUAL 200)
+    include(CheckCXXSourceCompiles)
+    set(CMAKE_REQUIRED_INCLUDES ${LLVM_INCLUDE_DIRS})
+    set(CMAKE_REQUIRED_FLAGS "-std=c++17 -fno-rtti")
+    check_cxx_source_compiles("
+      #include <llvm/IR/DIBuilder.h>
+      #include <llvm/IR/Instructions.h>
+      void f(llvm::DIBuilder* b, llvm::Value* v, llvm::DILocalVariable* var,
+             llvm::DIExpression* e, const llvm::DILocation* dl,
+             llvm::Instruction* i) {
+        b->insertDeclare(v, var, e, dl, llvm::BasicBlock::iterator(i));
+      }
+    " TVM_LLVM_INSERTDECLARE_USES_ITERATOR)
+    unset(CMAKE_REQUIRED_INCLUDES)
+    unset(CMAKE_REQUIRED_FLAGS)

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   Setting and then unsetting `CMAKE_REQUIRED_INCLUDES` and `CMAKE_REQUIRED_FLAGS` can lead to side effects if these variables had values before the `find_llvm` macro was called. It is safer to save the original values and restore them afterwards to avoid affecting other parts of the build system.
   
   ```
       set(OLD_CMAKE_REQUIRED_INCLUDES ${CMAKE_REQUIRED_INCLUDES})
       set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
       set(CMAKE_REQUIRED_INCLUDES ${LLVM_INCLUDE_DIRS})
       set(CMAKE_REQUIRED_FLAGS "-std=c++17 -fno-rtti")
       check_cxx_source_compiles("
         #include <llvm/IR/DIBuilder.h>
         #include <llvm/IR/Instructions.h>
         void f(llvm::DIBuilder* b, llvm::Value* v, llvm::DILocalVariable* var,
                llvm::DIExpression* e, const llvm::DILocation* dl,
                llvm::Instruction* i) {
           b->insertDeclare(v, var, e, dl, llvm::BasicBlock::iterator(i));
         }
       " TVM_LLVM_INSERTDECLARE_USES_ITERATOR)
       set(CMAKE_REQUIRED_INCLUDES ${OLD_CMAKE_REQUIRED_INCLUDES})
       set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
   ```



##########
python/tvm/s_tir/meta_schedule/relax_integration.py:
##########
@@ -407,16 +407,75 @@ def compile_relax(
         The built runtime module or vm VMExecutable for the given relax workload.
     """
     # pylint: disable=import-outside-toplevel
+    import tvm
+    from tvm import relax
     from tvm.relax import build as relax_build
     from tvm.relax.transform import BindParams, MetaScheduleApplyDatabase
+    from tvm.s_tir import dlight as dl
 
     # pylint: enable=import-outside-toplevel
     if not isinstance(target, Target):
         target = Target(target)
     if params:
         mod = BindParams("main", params)(mod)
 
+    # Build a pipeline with the correct ordering:
+    #   1. library_dispatch + LegalizeOps + FuseOps + FuseTIR
+    #      (same preparation as extract_tasks, so database keys match)
+    #   2. MetaScheduleApplyDatabase — replaces tuned fused-TIR functions
+    #   3. DLight fallback — schedules remaining untuned functions
+    #   4. VM lowering passes
+    # Applying MetaScheduleApplyDatabase BEFORE FuseOps (the original bug)
+    # caused DLight.Matmul to fail on cache-write stages embedded in fused TIR.
+    try:
+        from tvm.relax.backend.cuda.pipeline import (  # pylint: disable=import-outside-toplevel
+            library_dispatch_passes,
+            dataflow_lower_passes,
+            finalize_passes,
+        )
+        backend_specific = True
+    except ImportError:
+        backend_specific = False

Review Comment:
   ![high](https://www.gstatic.com/codereviewagent/high-priority.svg)
   
   The logic for detecting `backend_specific` passes is currently tied to the ability to import CUDA-specific pipeline modules. This will fail to detect backend-specific passes for other targets like ROCm, which is the primary focus of this PR. Instead of manual imports and `try-except` blocks, you should leverage the target-aware helper functions already available in `tvm.relax.pipeline` (e.g., `library_dispatch_passes`, `dataflow_lower_passes`, and `finalize_passes`). These helpers internally handle the dispatching to CUDA, ROCm, and other backends based on the provided `target`.



##########
python/tvm/s_tir/meta_schedule/relax_integration.py:
##########
@@ -407,16 +407,75 @@ def compile_relax(
         The built runtime module or vm VMExecutable for the given relax workload.
     """
     # pylint: disable=import-outside-toplevel
+    import tvm
+    from tvm import relax
     from tvm.relax import build as relax_build
     from tvm.relax.transform import BindParams, MetaScheduleApplyDatabase
+    from tvm.s_tir import dlight as dl
 
     # pylint: enable=import-outside-toplevel
     if not isinstance(target, Target):
         target = Target(target)
     if params:
         mod = BindParams("main", params)(mod)
 
+    # Build a pipeline with the correct ordering:
+    #   1. library_dispatch + LegalizeOps + FuseOps + FuseTIR
+    #      (same preparation as extract_tasks, so database keys match)
+    #   2. MetaScheduleApplyDatabase — replaces tuned fused-TIR functions
+    #   3. DLight fallback — schedules remaining untuned functions
+    #   4. VM lowering passes
+    # Applying MetaScheduleApplyDatabase BEFORE FuseOps (the original bug)
+    # caused DLight.Matmul to fail on cache-write stages embedded in fused TIR.
+    try:
+        from tvm.relax.backend.cuda.pipeline import (  # pylint: disable=import-outside-toplevel
+            library_dispatch_passes,
+            dataflow_lower_passes,
+            finalize_passes,
+        )
+        backend_specific = True
+    except ImportError:
+        backend_specific = False
+
+    @tvm.transform.module_pass(opt_level=3)
+    def _ms_pipeline(mod: tvm.ir.IRModule, _ctx: tvm.transform.PassContext) -> tvm.ir.IRModule:
+        fuse_passes = [
+            relax.transform.LegalizeOps(enable_warning=enable_warning),
+            relax.transform.AnnotateTIROpPattern(),
+            relax.transform.FoldConstant(),
+            relax.transform.FuseOps(),
+            relax.transform.FuseTIR(),
+        ]
+        if backend_specific:
+            fuse_passes = library_dispatch_passes(target) + fuse_passes
+        mod = tvm.transform.Sequential(fuse_passes)(mod)
+        mod = MetaScheduleApplyDatabase(enable_warning=enable_warning)(mod)
+        # DLight handles functions not covered by the database
+        mod = dl.ApplyDefaultSchedule(
+            dl.gpu.Matmul(),
+            dl.gpu.GEMV(),
+            dl.gpu.Reduction(),
+            dl.gpu.GeneralReduction(),
+            dl.gpu.Fallback(),
+        )(mod)
+        lower = (dataflow_lower_passes(target) if backend_specific else [
+            relax.transform.RewriteDataflowReshape(),
+            relax.transform.ToNonDataflow(),
+            relax.transform.RemovePurityChecking(),
+            relax.transform.CallTIRRewrite(),
+        ])
+        finalize = (finalize_passes(target) if backend_specific else [
+            relax.transform.StaticPlanBlockMemory(),
+            relax.transform.LowerAllocTensor(),
+            relax.transform.KillAfterLastUse(),
+            relax.transform.LowerRuntimeBuiltin(),
+            relax.transform.ComputePrimValue(),
+            relax.transform.VMShapeLower(),
+            relax.transform.AttachGlobalSymbol(),
+        ])

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   The fallback pass lists for `lower` and `finalize` are manually duplicated here. It would be cleaner to retrieve these from a central location (like `tvm.relax.pipeline.default_build_pipeline`) or define them as shared constants to ensure consistency across the codebase and reduce maintenance overhead.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org