1//===- GlobalIdRewriter.cpp - Implementation of GlobalId rewriting -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements in-dialect rewriting of the global_id op for archs
10// where global_id.x = threadId.x + blockId.x * blockDim.x
11//
12//===----------------------------------------------------------------------===//
13
14#include "mlir/Dialect/Arith/IR/Arith.h"
15#include "mlir/Dialect/GPU/IR/GPUDialect.h"
16#include "mlir/Dialect/GPU/Transforms/Passes.h"
17#include "mlir/IR/PatternMatch.h"
18
19using namespace mlir;
20
21namespace {
22struct GpuGlobalIdRewriter : public OpRewritePattern<gpu::GlobalIdOp> {
23 using OpRewritePattern<gpu::GlobalIdOp>::OpRewritePattern;
24
25 LogicalResult matchAndRewrite(gpu::GlobalIdOp op,
26 PatternRewriter &rewriter) const override {
27 Location loc = op.getLoc();
28 auto dim = op.getDimension();
29 Value blockId = gpu::BlockIdOp::create(builder&: rewriter, location: loc, dimension: dim);
30 Value blockDim = gpu::BlockDimOp::create(builder&: rewriter, location: loc, dimension: dim);
31 auto indexType = rewriter.getIndexType();
32 // Compute blockId.x * blockDim.x
33 Value tmp =
34 arith::MulIOp::create(builder&: rewriter, location: loc, result: indexType, lhs: blockId, rhs: blockDim);
35 Value threadId = gpu::ThreadIdOp::create(builder&: rewriter, location: loc, dimension: dim);
36 // Compute threadId.x + blockId.x * blockDim.x
37 rewriter.replaceOpWithNewOp<arith::AddIOp>(op, args&: indexType, args&: threadId, args&: tmp);
38 return success();
39 }
40};
41} // namespace
42
43void mlir::populateGpuGlobalIdPatterns(RewritePatternSet &patterns) {
44 patterns.add<GpuGlobalIdRewriter>(arg: patterns.getContext());
45}
46