A CUDA code migration method based on LLVM IR semantic recognition
By adopting a CUDA code migration method based on LLVM IR, the problems of incomplete semantic recognition and weak cross-platform adaptability in CUDA code migration are solved, and automated migration and performance preservation are achieved on multiple processor platforms.
Patent Information
- Application Number
- CN202611711342.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-11-02
- Publication Date
- 2026-11-27
AI Technical Summary
Existing CUDA code migration solutions suffer from incomplete semantic recognition, weak cross-platform adaptability, low automation, and poor robustness, making it impossible to effectively achieve cross-platform migration without human intervention.
A method based on LLVM IR semantic recognition is adopted to compile CUDA C++ source code into LLVM IR, extract parallel semantics through a custom LLVM Pass, and map them to the parallel programming model of the target platform to generate C++ source code that conforms to the syntax of the target platform.
It achieves end-to-end automated migration from CUDA source code to multiple processor platforms, retains the original parallel logic and performance, improves the robustness of translation and cross-platform adaptability, and reduces the cost of manual intervention.
Smart Images

Figure CN123177828A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of compiler technology, and in particular to a CUDA code migration method based on LLVM IR semantic recognition. Background Technology
[0002] CUDA, as a parallel programming model within the NVIDIA ecosystem, is widely used in high-performance computing and GPU acceleration. However, CUDA code suffers from strong platform dependency: CUDA source code can only be compiled and run on NVIDIA hardware and cannot be directly reused on multiple backend platforms such as CPUs, domestic GPUs, and AMD GPUs. When migrating a CUDA project to other hardware platforms, the code must be reimplemented or transformed.
[0003] To address the platform-binding issue of CUDA code, existing solutions can be broadly categorized into three types.
[0004] The first approach is manual rewriting. Developers directly rewrite the CUDA code into OpenMP, OpenCL, or a platform-specific API. While this approach enables cross-platform migration, it is labor-intensive, error-prone, and difficult to maintain. For large-scale CUDA projects, the amount of manual rewriting is enormous, and it is difficult to guarantee correctness.
[0005] The second type of solution is source-to-source translation tools. These tools are based on a C / C++ front-end and directly perform text matching and replacement on the CUDA source code, converting CUDA syntax elements into corresponding syntax elements for the target platform. However, this type of solution cannot handle complex templates, macro definitions, and implicit parallel semantics. It also has limited ability to recognize CUDA built-in functions, synchronization primitives, and memory models, resulting in poor translation robustness and a tendency to produce compilation or semantic errors.
[0006] The third type of solution is a translation scheme based on PTX or assembly. This type of solution compiles CUDA into PTX intermediate instruction sets or low-level assembly instructions, and then translates and converts these low-level instructions. This type of solution relies on a specific version of the PTX instruction set, has a low level of abstraction, is difficult to reconstruct high-level semantics across platforms, and requires re-adaptation of the instruction set when the hardware architecture is upgraded or changed, resulting in high adaptation costs.
[0007] The aforementioned existing solutions have the following defects and shortcomings: First, semantic recognition is incomplete. Existing solutions struggle to systematically recognize core parallel semantics in CUDA, such as metadata, built-in synchronization functions, thread indexing instructions, and shared memory allocation, resulting in translated code failing to retain the original parallel logic.
[0008] Second, cross-platform adaptability is weak. Existing solutions cannot automatically map CUDA's grid and thread block hierarchy, shared memory model, and memory management model to the abstract interfaces of multiple backend platforms, and cannot achieve one-time translation and multi-platform operation.
[0009] Third, the level of automation is low. Most existing solutions require manual intervention and cannot achieve end-to-end, manual-free migration from CUDA source code to cross-platform code.
[0010] Fourth, poor robustness. Existing solutions lack sufficient support for complex CUDA code, and are prone to translation errors or compilation failures.
[0011] The aforementioned shortcomings arise because existing technologies mostly remain at the CUDA source code text level or low-level assembly and PTX instruction level, lacking the ability to understand and abstractly reconstruct the semantics of the CUDA parallel computing model. On the one hand, existing solutions cannot extract the core semantics of parallel computing from the CUDA source code, only performing surface-level replacements, failing to identify key parallel semantic elements such as kernel function entry points, thread index calculations, synchronization primitives, and shared memory allocation. On the other hand, existing solutions do not utilize the structured information of the compiler's intermediate representation for cross-platform semantic mapping and reconstruction, failing to accurately map the CUDA parallel model to the target platform's parallel model. Therefore, a CUDA code migration method that can identify CUDA parallel semantics at the compiler's intermediate representation level and perform cross-platform model mapping is urgently needed. Summary of the Invention
[0012] The purpose of this invention is to provide a CUDA code migration method based on LLVM IR semantic recognition, which overcomes the technical defects of existing CUDA code migration schemes, such as incomplete semantic recognition, weak cross-platform adaptability, low degree of automation, and poor robustness.
[0013] To achieve the above objectives, this invention provides a CUDA code migration method based on LLVM IR semantic recognition, comprising the following steps: S1. Compile the CUDA C++ source code into LLVM IR. LLVM IR contains CUDA-specific metadata and built-in functions, and preserves the parallel semantics of kernel functions, thread hierarchy, synchronization primitives and memory allocation. S2. Run a custom LLVM Pass on LLVM IR and extract CUDA parallel semantics through pattern recognition. CUDA parallel semantics include kernel function entry points, synchronous built-in functions, thread index read instructions, and shared memory allocation modes. S3. Based on CUDA parallel semantics, control flow analysis, data flow analysis, and type inference are used to map CUDA parallel semantics to the target platform's parallel programming model. S4. Generate C++ source code that conforms to the target platform syntax based on the target platform's parallel programming model. The C++ source code includes the header files, execution space type aliases, and compiler macro definitions required by the target platform, and can be compiled and run directly on multiple processor platforms.
[0014] Preferably, the pattern recognition in S2 includes: Identify the kernel function entry points for nvvm.annotations metadata annotations; Identify the built-in synchronization function llvm.nvvm.barrier0; Recognize thread index read commands for llvm.nvvm.read.ptx.sreg.ctaid.x, llvm.nvvm.read.ptx.sreg.ctaid.y, llvm.nvvm.read.ptx.sreg.ctaid.z, llvm.nvvm.read.ptx.sreg.tid.x, llvm.nvvm.read.ptx.sreg.tid.y, and llvm.nvvm.read.ptx.sreg.tid.z. Recognize thread block dimension read commands for llvm.nvvm.read.ptx.sreg.ntid.x, llvm.nvvm.read.ptx.sreg.ntid.y, and llvm.nvvm.read.ptx.sreg.ntid.z; Identify the address space attributes as shared memory allocation mode.
[0015] Preferably, in S3, mapping CUDA parallel semantics to the target platform's parallel programming model includes: Map the CUDA mesh and thread block hierarchy to target platform team strategy parameters; Map CUDA thread indices to target platform team thread-range iterations; Map CUDA shared memory to a target platform team temporary view or view; Map CUDA synchronization primitives to target platform team barriers; Map CUDA global memory management functions to target platform view construction, deep copy, and destruction operations.
[0016] Preferably, mapping the CUDA grid to the thread block hierarchy to the target platform team strategy parameters and team thread range iteration includes: mapping the grid dimension to the league size of the team strategy; Mapping CUDA thread indexes to target platform team thread range iterations includes: mapping CUDA thread block dimensions to the logical iteration range of team thread range iterations; mapping one-dimensional thread indexes within CUDA thread blocks to logical iteration indices within the logical iteration range; when using two-dimensional or three-dimensional thread indexes within CUDA thread blocks, flattening the multi-dimensional thread indexes into one-dimensional logical iteration indices in row-major order, and then using modulo and integer division operations to inversely solve for the thread coordinates of each dimension. The logical iteration index is decoupled from the physical team ranking, and the thread index includes thread coordinates within the thread block and grid block coordinates. For a two-dimensional thread block, the thread linear index is threadIdx.x + blockDim.x × threadIdx.y, and the inverse solution is threadIdx.x = thread linear index mod blockDim.x, threadIdx.y = floor(thread linear index / blockDim.x); for a three-dimensional thread block, the thread linear index is threadIdx.x + blockDim.x × (threadIdx.y + blockDim.y × threadIdx.z), and the thread coordinates of each dimension are recovered by taking the modulus and dividing by integers. For a 2D mesh, the block linear index is blockIdx.x + gridDim.x × blockIdx.y, and the inverse solution is blockIdx.x = block linear index mod gridDim.x, blockIdx.y = floor(block linear index / gridDim.x); for a 3D mesh, the block linear index is blockIdx.x + gridDim.x × (blockIdx.y + gridDim.y × blockIdx.z), and the block coordinates of each dimension are recovered by taking the modulus and dividing by integers.
[0017] Preferably, mapping CUDA shared memory to a target platform team staging view or view includes: when mapping to a team staging view, converting the CUDA __shared__ memory declaration to the target platform's team staging view, and setting the staging memory size for each team through team policies, wherein the staging memory size is calculated based on the element type and number of elements in the shared memory array.
[0018] Preferably, mapping CUDA synchronization primitives to team barriers on the target platform includes mapping CUDA's __syncthreads() to the target platform's team_barrier(), and ensuring through control flow analysis that the team barrier is located on the dominant path where all team threads execute.
[0019] Preferably, mapping CUDA global memory management functions to target platform view construction, deep copy, and destruction operations includes: Map cudaMalloc to the constructor of the target platform view; Map cudaMemcpy to a deep copy function for the target platform; Map cudaFree to the destructor or reference count zeroing operation when the target platform view scope ends.
[0020] Preferably, in S4, generating C++ source code that conforms to the target platform syntax includes: Automatically add target platform initialization and termination calls; Automatically add the target platform header files; Define execution space type aliases based on the target backend; Automatically add compiler macro definitions to support multi-backend compilation.
[0021] Preferably, the target platform's parallel programming model is Kokkos or RAJA.
[0022] Preferably, the multiple processor platforms include at least one of CPU, NVIDIA GPU, AMD GPU, and domestically produced GPU.
[0023] Therefore, the present invention employs the above-mentioned CUDA code migration method based on LLVM IR semantic recognition, and compared with the prior art, the present invention has the following advantages: (1) Semantic-level recognition with strong robustness. This invention performs semantic recognition based on the structured information of LLVM IR, rather than surface text matching. It can accurately identify CUDA metadata, built-in functions, index instructions and memory allocation patterns, thereby improving the completeness of recognition and translation robustness of complex CUDA code.
[0024] (2) Fully automated cross-platform migration. This invention realizes end-to-end automated migration from CUDA source code to target platform code without the need for manual code modification or configuration, reducing the cost and time consumption of migrating CUDA projects to multiple platforms.
[0025] (3) Supports multiple backend platforms. This invention can automatically map to an abstract interface of a cross-platform programming model. The generated C++ source code can be directly compiled and run on multiple processor platforms such as CPU, NVIDIA GPU, AMD GPU, and domestic GPU, realizing the platform independence of CUDA code.
[0026] (4) Preserve the original parallel logic and performance. This invention fully preserves the parallel logic and memory access mode of the original CUDA code by accurately mapping the CUDA thread hierarchy, thread index, shared memory, synchronization primitives and memory management model, avoiding performance degradation or logical errors caused by manual rewriting or superficial translation.
[0027] (5) High scalability. Based on the modular design of LLVM Pass, this invention can be extended to support more CUDA features and more target platforms by adding new identification rules and mapping logic, and adapt to new hardware architectures and parallel programming models in the future.
[0028] The technical solution of the present invention will be further described in detail below with reference to the accompanying drawings and embodiments. Attached Figure Description
[0029] Figure 1 This is a flowchart illustrating a CUDA code migration method based on LLVM IR semantic recognition according to the present invention. Detailed Implementation
[0030] The technical solution of the present invention will be further described below with reference to the accompanying drawings and embodiments.
[0031] To make the objectives, technical solutions, and advantages of the embodiments of the present invention clearer, the technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0032] Example 1 like Figure 1 As shown, this embodiment provides a CUDA code migration method based on LLVM IR semantic recognition, including the following steps: S1. Compile the CUDA C++ source code into LLVM IR. LLVM IR contains CUDA-specific metadata and built-in functions, and preserves parallel semantic information for kernel functions, thread hierarchy, synchronization primitives, and memory allocation.
[0033] Specifically, the input CUDA C++ source code is compiled into LLVM IR using a Clang frontend (which supports CUDA). During this compilation process, the Clang frontend converts information from the CUDA source code, such as the __global__ kernel function, __device__ function, thread hierarchy (grid and thread blocks), synchronization primitives (__syncthreads()), and memory allocation (global memory, shared memory, constant memory, registers), into structured metadata, built-in function calls, and address space identifiers in LLVM IR. This LLVM IR fully preserves the parallel semantics of the CUDA source code, including kernel function entry points, thread index calculation methods, shared memory allocation modes, and synchronization point locations.
[0034] S2. Run a custom LLVM Pass on LLVM IR and extract CUDA parallel semantics through pattern recognition. CUDA parallel semantics include kernel function entry points, synchronous built-in functions, thread index read instructions, and shared memory allocation modes.
[0035] Specifically, a set of custom pattern recognition and translation passes (compiler optimization and transformation passes) runs at the LLVM IR level. These passes traverse and match the LLVM IR, systematically extracting CUDA parallel semantics. Pattern recognition includes: Identify kernel function entry points annotated with `nvvm.annotations` metadata. In LLVM IR, CUDA's `__global__` kernel functions are marked with a named metadata object called `nvvm.annotations`, which contains a reference to the kernel function itself and the "kernel" identifier string. The custom pass iterates through this metadata object, extracts functions annotated with "kernel," and identifies them as kernel function entry points.
[0036] Identify the `llvm.nvvm.barrier0` built-in synchronization function. The CUDA `__syncthreads()` synchronization primitive is represented in LLVM IR as a call to the `llvm.nvvm.barrier0` built-in function, which corresponds to the `bar.sync` instruction in PTX, used to synchronize all threads within a thread block. Custom Passes identify synchronization points by matching these built-in function calls.
[0037] Recognize the thread index read instructions llvm.nvvm.read.ptx.sreg.ctaid.x, llvm.nvvm.read.ptx.sreg.ctaid.y, and llvm.nvvm.read.ptx.sreg.ctaid.z, which correspond to blockIdx.x, blockIdx.y, and blockIdx.z in CUDA, respectively, to read the x, y, and z coordinates of the current thread block in the grid; recognize llvm.nvvm.read.ptx.sreg.tid.x, llvm.nvvm.read.ptx.sreg.tid.y, and llvm.nvvm.read.ptx.sr For example, the `tid.z` instruction is a thread index read instruction. These instructions correspond to `threadIdx.x`, `threadIdx.y`, and `threadIdx.z` in CUDA, respectively reading the x, y, and z coordinates of the current thread within the thread block. Similarly, the `llvm.nvvm.read.ptx.sreg.ntid.x`, `llvm.nvvm.read.ptx.sreg.ntid.y`, and `llvm.nvvm.read.ptx.sreg.ntid.z` instructions are used to identify thread block dimension read operations. These instructions correspond to `blockDim.x`, `blockDim.y`, and `blockDim.z` in CUDA, respectively reading the size of the thread block in the x, y, and z dimensions. A custom pass identifies thread index and thread block dimension read operations by matching these built-in function calls.
[0038] The address space attribute is identified as a shared memory allocation mode. In LLVM IR, different memory types of CUDA are distinguished by different address spaces. Among them, addrspace(3) represents shared memory, corresponding to the __shared__ memory declaration in CUDA; addrspace(1) represents global memory, corresponding to the __device__ memory declaration in CUDA; addrspace(2) represents constant memory, corresponding to the __constant__ memory declaration in CUDA. The custom pass identifies the shared memory allocation mode and usage mode by checking the address space attributes of memory allocation instructions (such as alloca instructions) and memory access instructions (such as load and store instructions). In this embodiment, the __shared__ memory declaration of CUDA is converted into a global variable with the address space attribute addrspace(3) in LLVM IR.
[0039] A custom LLVM Pass iterates through the LLVM IR, matching metadata, built-in function calls, and address space attributes in the IR according to predefined pattern rules. Upon successful matching, the corresponding semantic elements are extracted and an intermediate semantic model is constructed. The intermediate semantic model includes at least kernel function entry identifiers, synchronization point locations, thread index calculation methods, shared memory allocation information, and usage details for each dimension. The code generation step selects a one-dimensional direct mapping formula or a two-dimensional or three-dimensional flattening and inverse kinematic formula based on the dimensional information in the intermediate semantic model, and ensures that synchronization primitives are not placed in divergent branches based on control flow analysis results, ultimately generating the target platform code.
[0040] After loading the CUDA device-side LLVM IR module using a custom LLVM Pass, the following steps are executed sequentially: kernel function entry point identification, parallel built-in function identification, shared memory identification, control flow and data flow analysis, and intermediate semantic model construction. Kernel function entry point identification involves traversing the nvvm.annotations named metadata, reading function references and "kernel" identifiers, and identifying the corresponding functions as CUDA kernel functions. Parallel built-in function identification involves traversing the call instructions in the basic block function by function, and identifying the following functions based on their names: llvm.nvvm.read.ptx.sreg.tid.x, llvm.nvvm.read.ptx.sreg.tid.y, llvm.nvvm.read.ptx.sreg.tid.z, llvm.nvvm.read.ptx.sreg.ctaid.x, llvm.nvvm.read.ptx.sreg.ctaid.y, llvm.nvvm.read.ptx.sreg.ctaid.z, and llvm.nvvm.read.ptx.sreg.ctaid.z. x.sreg.ntid.x, llvm.nvvm.read.ptx.sreg.ntid.y, llvm.nvvm.read.ptx.sreg.ntid.z, llvm.nvvm.read.ptx.sreg.nctaid.x, llvm.nvvm.read.ptx.sreg.nctaid.y, and llvm.nvvm.read.ptx.sreg.nctaid.z respectively obtain the thread coordinates, grid block coordinates, thread block dimension, and grid dimension within the thread block, and determine the thread block synchronization point based on the call location of llvm.nvvm.barrier0.
[0041] Shared memory identification involves traversing the global variable numbered 3 in the address space and its pointer propagation relationship, determining the capacity and usage scope of static shared memory based on the variable's element type, number of elements, alignment, and reference relationship; for dynamic shared memory whose number of elements cannot be determined during the compilation stage, its capacity expression is recorded, and diagnostic information indicating that automatic migration is not supported is output when the capacity cannot be determined.
[0042] A custom LLVM Pass is used to build intermediate semantic models for each kernel function. These intermediate semantic models record at least the kernel function symbols, the usage of thread and grid indices for each dimension, thread block and grid dimensions, the basic block containing the synchronization point, the element type and capacity of shared memory objects, and the definition and usage relationships of related memory access instructions. For synchronization points, consistency analysis based on control flow graphs, dominance relationships, post-dominance relationships, and branch conditions is used to determine whether the synchronization point is executed by all threads within the same team. Only when this condition is met is it marked as a mappable team barrier; otherwise, a manual processing mark is output, and automatic code generation for that kernel function is stopped.
[0043] The code generation step reads the intermediate semantic model, converts the dimensional information corresponding to nctaid and ntid into the league scale and thread iteration range of the target platform, generates index expressions for the coordinate information corresponding to ctaid and tid according to one-dimensional direct mapping or two-dimensional and three-dimensional row-first flattening and inverse solving rules, converts the shared memory object with address space number 3 into a temporary view allocated by team, calculates the temporary space size according to element type, number of elements and alignment requirements, and converts llvm.nvvm.barrier0, which has been confirmed by consistency analysis, into a team barrier.
[0044] For CUDA built-in functions not covered by predefined rules, shared memory with undetermined capacity, synchronization points that cannot be proven to be executed consistently, or instructions whose type and index relationships cannot be recovered, the code generation step outputs diagnostic information containing the original instruction location and the reason for failure, instead of generating target code that is claimed to be semantically equivalent.
[0045] S3. Based on CUDA parallel semantics, control flow analysis, data flow analysis, and type inference are used to map CUDA parallel semantics to the target platform's parallel programming model.
[0046] Specifically, based on the CUDA parallel semantics identified in S2, control flow analysis (determining the execution order and branch paths of instructions in the program), data flow analysis (tracing the definition and usage relationships of variables in the program), and type inference (inferring the data type of expressions) are used to map the CUDA parallel computing model to the corresponding concepts of the target platform's parallel programming model. Mapping CUDA parallel semantics to the target platform's parallel programming model includes: The CUDA grid and thread block hierarchy are mapped to the target platform team policy and nested iteration range. Specifically, the product of the CUDA grid dimensions (gridDim.x, gridDim.y, gridDim.z) is mapped to the league size (league_size) of the target platform team policy (TeamPolicy); the product of the CUDA thread block dimensions (blockDim.x, blockDim.y, blockDim.z) is recorded as the logical thread count (logical_threads) and used as the logical iteration range of TeamThreadRange. The physical team size of TeamPolicy is selected by Kokkos::AUTO according to the target backend capabilities and is not required to be equal to logical_threads.
[0047] This mapping maps CUDA thread indices to target platform team thread range iterations. Specifically, it maps one-dimensional thread indices within a CUDA thread block to logical iteration indices (local) generated by TeamThreadRange. When two-dimensional or three-dimensional thread indices are used within a CUDA thread block, the multi-dimensional thread indices are flattened into local in row-major order, and then the thread coordinates for each dimension are deduced through modulo and integer division operations. This mapping is independent of the physical team_rank, allowing different backends to use different physical team sizes.
[0048] For a two-dimensional thread block, the thread linear index is threadIdx.x + blockDim.x × threadIdx.y, and the inverse solution is threadIdx.x = thread linear index mod blockDim.x, threadIdx.y = floor(thread linear index / blockDim.x); for a three-dimensional thread block, the thread linear index is threadIdx.x + blockDim.x × (threadIdx.y + blockDim.y × threadIdx.z), and the thread coordinates of each dimension are recovered by taking the modulus and dividing by integers. For a 2D mesh, the block linear index is blockIdx.x + gridDim.x × blockIdx.y, and the inverse solution is blockIdx.x = block linear index mod gridDim.x, blockIdx.y = floor(block linear index / gridDim.x); for a 3D mesh, the block linear index is blockIdx.x + gridDim.x × (blockIdx.y + gridDim.y × blockIdx.z), and the block coordinates of each dimension are recovered by taking the modulus and dividing by integers.
[0049] Map CUDA shared memory to a target platform team staging view or view. Specifically, convert CUDA __shared__ memory declarations to a target platform team staging view (ScratchView) or view, and set the staging memory size for each team through team policies. The staging memory size is calculated based on the element type and number of elements in the shared memory array.
[0050] Map CUDA synchronization primitives to team barriers on the target platform. Specifically, map CUDA's __syncthreads() to the target platform's team_barrier(), and use control flow analysis to ensure that the team barrier is located on the dominant path where all team threads execute (i.e., ensure that the barrier does not appear in conditional branches where only some threads execute, otherwise it will lead to deadlock).
[0051] The CUDA global memory management functions are mapped to target platform view construction, deep copy, and destruction operations. Specifically, cudaMalloc is mapped to the target platform view constructor; cudaMemcpy is mapped to the target platform deep copy function; and cudaFree is mapped to the target platform view destructor or reference count zeroing operation when the target platform view scope ends.
[0052] In this embodiment, the target platform's parallel programming model is either Kokkos or RAJA. The following explanation uses Kokkos as an example; the mapping logic of RAJA is similar to that of Kokkos.
[0053] When the target platform's parallel programming model is the Kokkos parallel programming model, the mappings in S3 include: mapping the CUDA mesh hierarchy to the Kokkos TeamPolicy league size, with the physical team size selected by Kokkos::AUTO; mapping the logical thread range of the CUDA thread block to the Kokkos TeamThreadRange iteration; mapping CUDA shared memory declarations to Kokkos ScratchView or View; mapping CUDA thread synchronization functions to Kokkos team_barrier; and mapping CUDA memory management functions to Kokkos View construction, deep_copy, and View lifecycle management.
[0054] In S3, mapping CUDA shared memory declarations to Kokkos ScratchViews or Views includes: when mapping to a team staging view, by matching the shared memory allocation instruction with address space attribute addrspace(3) in LLVM IR, obtaining the element type and capacity of shared memory, generating a ScratchView for each Team in Kokkos, and allocating shared memory of the corresponding capacity for each Team through set_scratch_size.
[0055] In S3, mapping CUDA thread synchronization functions to Kokkos' team_barrier involves ensuring, through control flow analysis, that the team_barrier is executed in all team threads and is not located within divergent control flow branches.
[0056] In S3, mapping CUDA memory management functions to Kokkos's View constructor, deep_copy, and View lifecycle management includes: mapping cudaMalloc to the View constructor in Kokkos; mapping cudaMemcpy to the deep_copy function in Kokkos; and mapping cudaFree to the View's scope destructor or reference count zeroing operation.
[0057] In S3, mapping the CUDA thread index calculation to Kokkos's TeamThreadRange iteration includes: when the CUDA thread index is one-dimensional, mapping the intra-block linear index of the CUDA thread to the local of TeamThreadRange, and mapping the CUDA block linear index to league_rank; when the CUDA thread index is two-dimensional, flattening the two-dimensional block coordinates to league_rank using L = blockIdx.x + gridDim.x × blockIdx.y, and then using T = threadIdx.x + blockDim.x × threadIdx.y. The `.y` parameter flattens the 2D thread coordinates to `local`, and then recovers the 2D coordinates through modulo and integer division operations. When the CUDA thread index is 3D, the 3D block coordinates are flattened to `league_rank` using `L=blockIdx.x+gridDim.x×(blockIdx.y+gridDim.y×blockIdx.z)`, and then flattened to `local` using `T=threadIdx.x+blockDim.x×(threadIdx.y+blockDim.y×threadIdx.z)`, and then recovered through modulo and integer division operations. `local` is a logical iterative index and is not required to equal the physical `team_rank`.
[0058] The following example of CUDA vector addition illustrates the implementation process of the above method in detail. This example is a two-dimensional vector addition kernel function that incorporates core CUDA parallel semantics such as two-dimensional thread indexing, shared memory, thread synchronization, and global memory read / write.
[0059] The CUDA C++ code before conversion is as follows: #define BLOCK_X 16 #define BLOCK_Y 16 __global__ void vec_add_2d(const float* a, const float* b, float* c, int width, int height) { / / [1] Each thread block shares a block of on-chip storage.
[0060] __shared__ float tile[BLOCK_X * BLOCK_Y]; / / [2][3] Thread coordinates within a two-dimensional block.
[0061] const int tx = threadIdx.x; const int ty = threadIdx.y; const int local = ty * blockDim.x + tx; / / [4] Two-dimensional global coordinates and global memory linear addresses.
[0062] const int x = blockIdx.x * blockDim.x + tx; const int y = blockIdx.y * blockDim.y + ty; const int idx = y * width + x; / / [5] Read global memory and write to shared memory.
[0063] if (x <width&&y<height) { tile[local] = a[idx] + b[idx]; } else { tile[local] = 0.0f; } / / [6] All threads can continue only after all threads have reached the synchronization point.
[0064] __syncthreads(); / / [7] Read from shared memory and write back to global memory.
[0065] if (x <width&&y<height) { c[idx] = tile[local]; } } / / Example startup configuration: 2D grid, 2D block.
[0066] dim3 block(BLOCK_X, BLOCK_Y); dim3 grid((width + BLOCK_X - 1) / BLOCK_X, (height + BLOCK_Y - 1) / BLOCK_Y); vec_add_2d<<<grid, block> >>(a, b, c, width, height); Step S1 is performed on the CUDA source code to compile it into LLVM IR via the Clang frontend (which supports CUDA). In this LLVM IR, the kernel function vec_add_2d is marked as the kernel function entry point by the nvvm.annotations metadata; __syncthreads() is converted into a call to the llvm.nvvm.barrier0 built-in function; threadIdx.x, threadIdx.y, blockIdx.x, blockIdx.y, blockDim.x, and blockDim.y are respectively converted into calls to the corresponding llvm.nvvm.read.ptx.sreg.* built-in functions; __shared__ float tile[BLOCK_X * BLOCK_Y] is converted into a shared memory allocation instruction with the address space attribute addrspace(3).
[0067] Execute step S2 to run the custom LLVM Pass on LLVM IR and extract the above CUDA parallel semantics through pattern recognition, including kernel function entry points, synchronous built-in functions, thread index read instructions, and shared memory allocation modes.
[0068] Step S3 is performed to map the identified CUDA parallel semantics to the Kokkos parallel programming model using control flow analysis, data flow analysis, and type inference.
[0069] The S4 step generates C++ source code that conforms to the target platform's syntax based on the target platform's parallel programming model. The C++ source code includes the header files, execution space type aliases, and compiler macro definitions required by the target platform, and can be directly compiled and run on multiple processor platforms.
[0070] The complete Kokkos C++ code after conversion is as follows: #include<Kokkos_Core.hpp> #include <cstddef> #include <iostream> int main(int argc, char* argv[]) { Kokkos::initialize(argc, argv); { constexpr int width = 4096; constexpr int height = 4096; constexpr int block_x = 16; constexpr int block_y = 16; constexpr int logical_threads = block_x * block_y; const int grid_x = (width + block_x - 1) / block_x; const int grid_y = (height + block_y - 1) / block_y; const int league_size = grid_x * grid_y; / / [8] const std::size_t n = static_cast<std::size_t>(width) * height; using ExecSpace = Kokkos::DefaultExecutionSpace; using View = Kokkos::View<float*, ExecSpace>; using Policy = Kokkos::TeamPolicy <execspace>; using Member = Policy::member_type; using ScratchSpace = Member::scratch_memory_space; using ScratchView = Kokkos::View< float*, ScratchSpace, Kokkos::MemoryTraits <kokkos::unmanaged>>; View a("a", n), b("b", n), c("c", n); auto h_a = Kokkos::create_mirror_view(a); auto h_b = Kokkos::create_mirror_view(b); for (std::size_t i = 0; i<n; ++i) { h_a(i) = 1.0f; h_b(i) = 2.0f; } Kokkos::deep_copy(a, h_a); Kokkos::deep_copy(b, h_b); Policy policy(league_size, Kokkos::AUTO); policy.set_scratch_size( 0, Kokkos::PerTeam(ScratchView::shmem_size(logical_threads))); Kokkos::parallel_for( "vec_add_2d", policy, KOKKOS_LAMBDA(const Member&team) { / / [8] The 2D block coordinates are derived from the 1D league_rank.
[0071] const int block_linear = team.league_rank(); const int bx = block_linear % grid_x; const int by = block_linear / grid_x; ScratchView tile(team.team_scratch(0), logical_threads); / / [1] Kokkos::parallel_for( Kokkos::TeamThreadRange(team, logical_threads), [=](const int local) { / / [2][3] 2D threadIdx is inversely solved from the logical iteration index local.
[0072] const int tx = local % block_x; const int ty = local / block_x; const int x = bx * block_x + tx; / / [4] const int y = by * block_y + ty; const std::size_t idx = static_cast<std::size_t>(y) * width + x; tile(local) = (x<width&&y<height) ? a(idx) + b(idx) / / [5] : 0.0f; }); team.team_barrier(); / / [6] Kokkos::parallel_for( Kokkos::TeamThreadRange(team, logical_threads), [=](const int local) { const int tx = local % block_x; const int ty = local / block_x; const int x = bx * block_x + tx; const int y = by * block_y + ty; if (x<width&&y<height) { c(static_cast<std::size_t>(y) * width +x) = tile(local); / / [7] } }); }); Kokkos::fence(); auto h_c = Kokkos::create_mirror_view(c); Kokkos::deep_copy(h_c, c); std::cout<<"c[0]="< <h_c(0)<<'\n'; } Kokkos::finalize(); return 0; } In the transformed code above, the two-dimensional CUDA grid is flattened into a TeamPolicy league; the logical thread range of each CUDA block is executed by TeamThreadRange, and the physical team size is selected by Kokkos::AUTO by backend; shared memory uses each team's scratch memory.
[0073] In S4, generating C++ source code that conforms to the target platform's syntax includes: automatically adding target platform initialization and termination calls (i.e., Kokkos::initialize and Kokkos::finalize); and automatically adding target platform header files (i.e., #include <Kokkos::initialize>).<Kokkos_Core.hpp> The code snippet describes how to automatically add compiler macros to support multi-backend compilation, based on the target backend's execution space type alias (i.e., `using ExecSpace= Kokkos::DefaultExecutionSpace`). When generating C++ source code in S4, the corresponding Kokkos execution space is automatically selected based on the macros defined for the target compilation platform. The header file must include at least `Kokkos_Core.hpp`, the execution space type alias includes renaming the type of `Kokkos::DefaultExecutionSpace`, and the compiler macros include enabling or disabling specific backend compilation options based on the target platform.
[0074] Multiple processor platforms are supported, including at least one of CPUs, NVIDIA GPUs, AMD GPUs, and domestically produced GPUs. The generated C++ source code, through an abstraction layer of Kokkos or Raja, can be compiled and run on these multiple processor platforms without requiring manual code modification.
[0075] The following table presents the item-by-item mapping rules between the original CUDA code / semantics and the transformed Kokkos code / semantics in this embodiment: Table 1 Item-by-item mapping rules
[0076] Through the above mapping rules, the CUDA 2D thread index and 2D grid index are completely preserved and mapped into the Kokkos league and logical TeamThreadRange structures. The mapping logic for 3D generalization is consistent with that for 2D: L = blockIdx.x + Gx × (blockIdx.y + Gy × blockIdx.z), T = threadIdx.x + Bx × (threadIdx.y + By × threadIdx.z); the coordinates of each dimension can be recovered by taking the modulus and dividing by integers in sequence. The code generation steps select the corresponding formula according to the actual x / y / z dimensions, and maintain boundary judgment, synchronization point dominance relationship and memory read / write order; the physical team size is selected by the target backend and is not used as the semantic source of CUDA thread coordinates.
[0077] Therefore, this invention employs the aforementioned CUDA code migration method based on LLVM IR semantic recognition. By performing semantic-level recognition at the LLVM IR level rather than surface-level text matching, it can accurately identify core parallel semantics of CUDA, such as kernel function entry points, synchronous built-in functions, thread index read instructions, and shared memory allocation patterns, thus solving the problem of incomplete semantic recognition in existing solutions. By automatically mapping CUDA parallel semantics to the target platform's parallel programming model, the generated C++ source code can be directly compiled and run on various processor platforms such as CPUs, NVIDIA GPUs, AMD GPUs, and domestic GPUs. This achieves end-to-end, unmanned, cross-platform automated migration, fully preserving the original CUDA code's parallel logic and memory access patterns, avoiding performance degradation or logical errors caused by manual rewriting or surface translation.
[0078] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention and not to limit them. Although the present invention has been described in detail with reference to preferred embodiments, those skilled in the art should understand that modifications or equivalent substitutions can still be made to the technical solutions of the present invention, and these modifications or equivalent substitutions cannot cause the modified technical solutions to deviate from the spirit and scope of the technical solutions of the present invention.< / kokkos::unmanaged> < / execspace> < / iostream> < / cstddef>
Claims
1. A CUDA code migration method based on LLVM IR semantic recognition, characterized in that, Includes the following steps: S1. Compile the CUDA C++ source code into LLVM IR. LLVM IR contains CUDA-specific metadata and built-in functions, and preserves the parallel semantics of kernel functions, thread hierarchy, synchronization primitives and memory allocation. S2. Run a custom LLVM Pass on LLVM IR and extract CUDA parallel semantics through pattern recognition. CUDA parallel semantics include kernel function entry points, synchronous built-in functions, thread index read instructions, and shared memory allocation modes. S3. Based on CUDA parallel semantics, control flow analysis, data flow analysis, and type inference are used to map CUDA parallel semantics to the target platform's parallel programming model. S4. Generate C++ source code that conforms to the target platform syntax based on the target platform's parallel programming model. The C++ source code includes the header files, execution space type aliases, and compiler macro definitions required by the target platform, and can be compiled and run directly on multiple processor platforms.
2. The method according to claim 1, characterized in that, The pattern recognition described in S2 includes: Identify the kernel function entry points for nvvm.annotations metadata annotations; Identify the built-in synchronization function llvm.nvvm.barrier0; Recognize thread index read commands for llvm.nvvm.read.ptx.sreg.ctaid.x, llvm.nvvm.read.ptx.sreg.ctaid.y, llvm.nvvm.read.ptx.sreg.ctaid.z, llvm.nvvm.read.ptx.sreg.tid.x, llvm.nvvm.read.ptx.sreg.tid.y, and llvm.nvvm.read.ptx.sreg.tid.z. Recognize thread block dimension read commands for llvm.nvvm.read.ptx.sreg.ntid.x, llvm.nvvm.read.ptx.sreg.ntid.y, and llvm.nvvm.read.ptx.sreg.ntid.z; Identify the address space attributes as shared memory allocation mode.
3. The method according to claim 1, characterized in that, In S3, mapping CUDA parallel semantics to the target platform's parallel programming model includes: Map the CUDA mesh and thread block hierarchy to target platform team strategy parameters; Map CUDA thread indices to target platform team thread-range iterations; Map CUDA shared memory to a target platform team staging view or view; Map CUDA synchronization primitives to target platform team barriers; Map CUDA global memory management functions to target platform view construction, deep copy, and destruction operations.
4. The method according to claim 3, characterized in that, Mapping the CUDA grid and thread block hierarchy to target platform team strategy parameters and team thread scope iterations includes: mapping grid dimensions to league size for team strategy; Mapping CUDA thread indexes to target platform team thread range iterations includes: mapping CUDA thread block dimensions to the logical iteration range of team thread range iterations; mapping one-dimensional thread indexes within CUDA thread blocks to logical iteration indices within the logical iteration range; when using two-dimensional or three-dimensional thread indexes within CUDA thread blocks, flattening the multi-dimensional thread indexes into one-dimensional logical iteration indices in row-major order, and then using modulo and integer division operations to inversely solve for the thread coordinates of each dimension. The logical iteration index is decoupled from the physical team ranking, and the thread index includes thread coordinates within the thread block and grid block coordinates. For a two-dimensional thread block, the thread linear index is threadIdx.x + blockDim.x × threadIdx.y, and the inverse solution is threadIdx.x = thread linear index mod blockDim.x, threadIdx.y = floor(thread linear index / blockDim.x); for a three-dimensional thread block, the thread linear index is threadIdx.x + blockDim.x × (threadIdx.y + blockDim.y × threadIdx.z), and the thread coordinates of each dimension are recovered by taking the modulus and dividing by integers. For a 2D mesh, the block linear index is blockIdx.x + gridDim.x × blockIdx.y, and the inverse solution is blockIdx.x = block linear index mod gridDim.x, blockIdx.y = floor(block linear index / gridDim.x); for a 3D mesh, the block linear index is blockIdx.x + gridDim.x × (blockIdx.y + gridDim.y × blockIdx.z), and the block coordinates of each dimension are recovered by taking the modulus and dividing by integers.
5. The method according to claim 3, characterized in that, Mapping CUDA shared memory to a team staging view or view on the target platform includes: when mapping to a team staging view, converting the CUDA __shared__ memory declaration to the team staging view of the target platform, and setting the staging memory size for each team through team policies. The staging memory size is calculated based on the element type and number of elements in the shared memory array.
6. The method according to claim 3, characterized in that, Mapping CUDA synchronization primitives to target platform team barriers involves mapping CUDA's __syncthreads() to the target platform's team_barrier() and using control flow analysis to ensure that the team barrier is located on the dominant path where all team threads execute.
7. The method according to claim 3, characterized in that, Mapping CUDA global memory management functions to target platform view construction, deep copy, and destruction operations includes: Map cudaMalloc to the constructor of the target platform view; Map cudaMemcpy to a deep copy function for the target platform; Map cudaFree to the destructor or reference count zeroing operation when the target platform view scope ends.
8. The method according to claim 1, characterized in that, In S4, generating C++ source code that conforms to the target platform's syntax includes: Automatically add target platform initialization and termination calls; Automatically add the target platform header files; Define execution space type aliases based on the target backend; Automatically add compiler macro definitions to support multi-backend compilation.
9. The method according to claim 1, characterized in that, The target platform's parallel programming model is Kokkos or RAJA.
10. The method according to claim 1, characterized in that, The various processor platforms include at least one of CPU, NVIDIA GPU, AMD GPU, and domestically produced GPU.
