25#include "llvm/ADT/ArrayRef.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/Support/FormatVariadic.h"
28#include "llvm/Support/MathExtras.h"
36#include "llvm/ADT/TypeSwitch.h"
39#define GEN_PASS_DEF_CONVERTXEVMTOLLVMPASS
40#include "mlir/Conversion/Passes.h.inc"
48struct LLVMFuncAttributeOptions {
49 bool isConvergent =
false;
50 bool isNoUnwind =
false;
51 bool isWillReturn =
false;
52 LLVM::MemoryEffectsAttr memEffectsAttr{};
54static constexpr LLVMFuncAttributeOptions noUnwindAttrs = {
55 false,
true,
false, {}};
56static constexpr LLVMFuncAttributeOptions noUnwindWillReturnAttrs = {
57 false,
true,
true, {}};
58static constexpr LLVMFuncAttributeOptions convergentNoUnwindWillReturnAttrs = {
59 true,
true,
true, {}};
61std::string getTypeMangling(
Type ty,
bool isUnsigned =
false) {
63 .Case([isUnsigned](VectorType ty) -> std::string {
64 return "Dv" + std::to_string(ty.getNumElements()) +
"_" +
65 getTypeMangling(ty.getElementType(), isUnsigned);
67 .Case([](Float16Type) -> std::string {
return "Dh"; })
68 .Case([](Float32Type) -> std::string {
return "f"; })
69 .Case([](Float64Type) -> std::string {
return "d"; })
70 .Case([isUnsigned](IntegerType ty) -> std::string {
71 switch (ty.getWidth()) {
73 return isUnsigned ?
"h" :
"c";
75 return isUnsigned ?
"t" :
"s";
77 return isUnsigned ?
"j" :
"i";
79 return isUnsigned ?
"m" :
"l";
81 llvm_unreachable(
"unhandled integer type");
84 .DefaultUnreachable(
"unhandled type for mangling");
89 assert((isUnsigned.empty() || isUnsigned.size() == types.size()) &&
90 "Signedness info doesn't match");
92 llvm::raw_string_ostream os(s);
93 llvm::SmallDenseMap<Type, unsigned> substitutions;
94 os <<
"_Z" << baseName.size() << baseName;
95 for (
auto [idx, type] : llvm::enumerate(types)) {
96 auto it = substitutions.find(type);
97 if (it != substitutions.end()) {
100 if (
unsigned firstIdx = it->getSecond(); firstIdx > 0)
104 if (!type.isIntOrFloat())
105 substitutions[type] = substitutions.size();
106 os << getTypeMangling(type, isUnsigned.empty() ?
false : isUnsigned[idx]);
116std::string getGenISATypeMangling(
Type ty) {
118 .Case([](VectorType ty) -> std::string {
119 return "v" + std::to_string(ty.getNumElements()) +
120 getGenISATypeMangling(ty.getElementType());
122 .Case([](IntegerType ty) -> std::string {
123 return "i" + std::to_string(ty.getWidth());
125 .DefaultUnreachable(
"unhandled type for GenISA mangling");
128std::string builtinElemType(ElemType elemType) {
141 return stringifyElemType(elemType).str();
145static int32_t getL1CacheControl(LoadCacheControl cc) {
148 case LoadCacheControl::USE_DEFAULT:
151 case LoadCacheControl::L1C_L2UC_L3UC:
152 case LoadCacheControl::L1C_L2UC_L3C:
153 case LoadCacheControl::L1C_L2C_L3UC:
154 case LoadCacheControl::L1C_L2C_L3C:
157 case LoadCacheControl::L1S_L2UC_L3UC:
158 case LoadCacheControl::L1S_L2UC_L3C:
159 case LoadCacheControl::L1S_L2C_L3UC:
160 case LoadCacheControl::L1S_L2C_L3C:
163 case LoadCacheControl::INVALIDATE_READ:
172static int32_t getL1CacheControl(StoreCacheControl cc) {
175 case StoreCacheControl::USE_DEFAULT:
178 case StoreCacheControl::L1WT_L2UC_L3UC:
179 case StoreCacheControl::L1WT_L2UC_L3WB:
180 case StoreCacheControl::L1WT_L2WB_L3UC:
181 case StoreCacheControl::L1WT_L2WB_L3WB:
184 case StoreCacheControl::L1WB_L2UC_L3UC:
185 case StoreCacheControl::L1WB_L2WB_L3UC:
186 case StoreCacheControl::L1WB_L2UC_L3WB:
189 case StoreCacheControl::L1S_L2UC_L3UC:
190 case StoreCacheControl::L1S_L2UC_L3WB:
191 case StoreCacheControl::L1S_L2WB_L3UC:
192 case StoreCacheControl::L1S_L2WB_L3WB:
201static int32_t getL3CacheControl(LoadCacheControl cc) {
204 case LoadCacheControl::USE_DEFAULT:
207 case LoadCacheControl::L1UC_L2UC_L3C:
208 case LoadCacheControl::L1UC_L2C_L3C:
209 case LoadCacheControl::L1C_L2UC_L3C:
210 case LoadCacheControl::L1C_L2C_L3C:
211 case LoadCacheControl::L1S_L2UC_L3C:
212 case LoadCacheControl::L1S_L2C_L3C:
215 case LoadCacheControl::INVALIDATE_READ:
224static int32_t getL3CacheControl(StoreCacheControl cc) {
227 case StoreCacheControl::USE_DEFAULT:
230 case StoreCacheControl::L1UC_L2UC_L3WB:
231 case StoreCacheControl::L1UC_L2WB_L3WB:
232 case StoreCacheControl::L1WT_L2UC_L3WB:
233 case StoreCacheControl::L1WT_L2WB_L3WB:
234 case StoreCacheControl::L1S_L2UC_L3WB:
235 case StoreCacheControl::L1S_L2WB_L3WB:
236 case StoreCacheControl::L1WB_L2UC_L3WB:
245static std::optional<LoadCacheControl> getCacheControl(PrefetchOp op) {
246 return op.getCacheControl();
249static std::optional<LoadCacheControl> getCacheControl(BlockLoad2dOp op) {
250 return op.getCacheControl();
253static std::optional<LoadCacheControl> getCacheControl(BlockLoadOp op) {
254 return op.getCacheControl();
257static std::optional<LoadCacheControl> getCacheControl(BlockPrefetch2dOp op) {
258 return op.getCacheControl();
261static std::optional<StoreCacheControl> getCacheControl(BlockStore2dOp op) {
262 return op.getCacheControl();
265static std::optional<StoreCacheControl> getCacheControl(BlockStoreOp op) {
266 return op.getCacheControl();
269static std::optional<LoadCacheControl> getCacheControl(LLVM::LoadOp op) {
270 if (op->hasDiscardableAttr(
"cache_control")) {
271 auto attr = op->getDiscardableAttrOfType<xevm::LoadCacheControlAttr>(
275 return std::optional<LoadCacheControl>(attr.getValue());
280static std::optional<StoreCacheControl> getCacheControl(LLVM::StoreOp op) {
281 if (op->hasDiscardableAttr(
"cache_control")) {
282 auto attr = op->getDiscardableAttrOfType<xevm::StoreCacheControlAttr>(
286 return std::optional<StoreCacheControl>(attr.getValue());
291template <
typename OpType>
292int32_t getL1CacheControl(OpType op) {
293 return getL1CacheControl(*getCacheControl(op));
296template <
typename OpType>
297int32_t getL3CacheControl(OpType op) {
298 return getL3CacheControl(*getCacheControl(op));
301template <
typename OpType>
302static std::optional<ArrayAttr>
303getCacheControlMetadata(ConversionPatternRewriter &rewriter, OpType op) {
304 if (!getCacheControl(op))
307 constexpr int32_t decorationCacheControlArity{3};
308 constexpr int32_t loadCacheControlKey{6442};
309 constexpr int32_t storeCacheControlKey{6443};
310 constexpr bool isLoad = std::is_same_v<OpType, BlockLoad2dOp> ||
311 std::is_same_v<OpType, BlockPrefetch2dOp> ||
312 std::is_same_v<OpType, LLVM::LoadOp> ||
313 std::is_same_v<OpType, BlockLoadOp> ||
314 std::is_same_v<OpType, PrefetchOp>;
320 assert(((getL1CacheControl<OpType>(op) == -1) ==
321 (getL3CacheControl<OpType>(op) == -1)) &&
322 "If one of L1 or L3 cache control is USE_DEFAULT, both must be "
325 if (getL1CacheControl<OpType>(op) == -1 &&
326 getL3CacheControl<OpType>(op) == -1)
328 const int32_t controlKey{isLoad ? loadCacheControlKey : storeCacheControlKey};
330 controlKey, 0, getL1CacheControl<OpType>(op)};
332 controlKey, 1, getL3CacheControl<OpType>(op)};
333 auto arrayAttrL1 = rewriter.getI32ArrayAttr(decorationsL1);
334 auto arrayAttrL3 = rewriter.getI32ArrayAttr(decorationsL3);
337 return rewriter.getArrayAttr(combinedAttrs);
359 llvm::StringMap<bool> seen;
361 for (
auto arr : llvm::make_isa_range<ArrayAttr>(attrs)) {
362 auto vals = arr.getValue();
363 assert(vals.size() == 3 &&
364 "Expected exactly 3 integer values (Token, CacheLevel, "
365 "ControlValue) in cache control attribute.");
367 auto tokenAttr = dyn_cast<IntegerAttr>(vals[0]);
368 auto secondAttr = dyn_cast<IntegerAttr>(vals[1]);
369 auto thirdAttr = dyn_cast<IntegerAttr>(vals[2]);
371 if (!tokenAttr || !secondAttr || !thirdAttr)
377 llvm::formatv(
"{{{0}:\"{1},{2}\"}", tokenAttr.getValue().getZExtValue(),
378 secondAttr.getValue().getZExtValue(),
379 thirdAttr.getValue().getZExtValue());
382 if (!seen.insert({entry, true}).second)
385 payloads.push_back(std::move(entry));
390static std::atomic<uint64_t> globalNameCounter{0};
395static Value createMetadataStringPtr(ConversionPatternRewriter &rewriter,
397 StringRef value, StringRef nameHint) {
399 std::string strWithNull = value.str();
400 strWithNull.push_back(
'\0');
401 StringRef strRef(strWithNull.data(), strWithNull.size());
403 auto as1PtrTy = LLVM::LLVMPointerType::get(rewriter.getContext(), 1);
407 if (
auto existingGlobal = dyn_cast<LLVM::GlobalOp>(&op)) {
408 if (!existingGlobal.getSection() ||
409 *existingGlobal.getSection() !=
"llvm.metadata")
412 dyn_cast_or_null<StringAttr>(existingGlobal.getValueOrNull())) {
413 if (strAttr.getValue() == strRef) {
414 return LLVM::AddressOfOp::create(rewriter, loc, as1PtrTy,
415 existingGlobal.getSymName());
422 auto i8Type = rewriter.getI8Type();
423 auto arrayType = LLVM::LLVMArrayType::get(i8Type, strWithNull.size());
424 std::string globalName =
425 llvm::formatv(
"{0}.{1}", nameHint,
426 globalNameCounter.fetch_add(1, std::memory_order_relaxed))
431 rewriter.setInsertionPointToStart(&moduleOp->
getRegion(0).
front());
434 LLVM::GlobalOp::create(rewriter, loc, arrayType,
435 true, LLVM::Linkage::Private,
436 globalName, rewriter.getStringAttr(strRef));
437 globalOp.setSection(StringRef(
"llvm.metadata"));
438 globalOp.setUnnamedAddr(LLVM::UnnamedAddr::Global);
439 globalOp.setAlignment(1);
440 globalOp.setAddrSpace(1);
444 return LLVM::AddressOfOp::create(rewriter, loc, as1PtrTy, globalName);
467static Value annotatePtrWithCacheControl(ConversionPatternRewriter &rewriter,
472 buildCacheControlPayloads(cacheControls.getValue());
473 if (payloads.empty())
476 auto ptrType = cast<LLVM::LLVMPointerType>(
ptr.getType());
477 auto as1PtrTy = LLVM::LLVMPointerType::get(rewriter.getContext(), 1);
478 auto i32Ty = rewriter.getI32Type();
482 createMetadataStringPtr(rewriter, moduleOp, loc,
"",
".str.file");
483 Value lineVal = LLVM::ConstantOp::create(rewriter, loc, i32Ty, 0);
484 Value nullAS1 = LLVM::ZeroOp::create(rewriter, loc, as1PtrTy);
489 for (
const std::string &payload : payloads) {
490 Value annStr = createMetadataStringPtr(rewriter, moduleOp, loc, payload,
491 ".str.cachecontrol");
492 auto annOp = LLVM::PtrAnnotation::create(rewriter, loc, ptrType, curPtr,
493 annStr, fileStr, lineVal, nullAS1);
494 curPtr = annOp.getResult();
516template <
typename OpType>
518applyCacheControlAnnotation(ConversionPatternRewriter &rewriter,
Location loc,
520 Operation *moduleOp,
unsigned ptrIdx = 0) {
521 std::optional<ArrayAttr> optCacheControls =
522 getCacheControlMetadata(rewriter, op);
523 if (!optCacheControls)
526 Value annotatedPtr = annotatePtrWithCacheControl(rewriter, loc, args[ptrIdx],
527 *optCacheControls, moduleOp);
528 args[ptrIdx] = annotatedPtr;
535static LLVM::CallOp createDeviceFunctionCall(
536 ConversionPatternRewriter &rewriter, StringRef funcName,
Type retType,
539 LLVMFuncAttributeOptions funcAttributeOptions,
Operation *op) {
541 assert(moduleOp &&
"Expecting module");
546 assert(!
failed(funcOpRes));
547 LLVM::LLVMFuncOp funcOp = funcOpRes.value();
548 funcOp.setCConv(LLVM::cconv::CConv::SPIR_FUNC);
549 funcOp.setConvergent(funcAttributeOptions.isConvergent);
550 funcOp.setNoUnwind(funcAttributeOptions.isNoUnwind);
551 funcOp.setWillReturn(funcAttributeOptions.isWillReturn);
553 if (funcAttributeOptions.memEffectsAttr)
554 funcOp.setMemoryEffectsAttr(funcAttributeOptions.memEffectsAttr);
556 for (
auto [idx, attrName] : paramAttrs)
557 funcOp.setArgAttr(idx, attrName, rewriter.getUnitAttr());
559 auto callOp = LLVM::CallOp::create(rewriter, loc, funcOp, args);
561 auto copyAttr = [&](StringAttr name,
Attribute attr) {
562 if (callOp->getInherentAttr(name).has_value())
563 callOp->setInherentAttr(name, attr);
565 discardableAttrs.emplace_back(name, attr);
567 for (
NamedAttribute attr : funcOp->getDiscardableAttrDictionary())
568 copyAttr(attr.getName(), attr.getValue());
569 funcOp->getName().walkInherentAttrs(
570 funcOp, [&](StringRef name,
Attribute &attr) {
571 copyAttr(rewriter.getStringAttr(name), attr);
573 callOp->setDiscardableAttrs(discardableAttrs);
578static unsigned getNumOperandsPerDword(xevm::ElemType pTy) {
580 case xevm::ElemType::F32:
581 case xevm::ElemType::TF32:
583 case xevm::ElemType::BF16:
584 case xevm::ElemType::F16:
586 case xevm::ElemType::U8:
587 case xevm::ElemType::S8:
588 case xevm::ElemType::BF8:
589 case xevm::ElemType::F8:
591 case xevm::ElemType::E2M1:
592 case xevm::ElemType::U4:
593 case xevm::ElemType::S4:
596 llvm_unreachable(
"unsupported xevm::ElemType");
600class MMAToOCLPattern :
public OpConversionPattern<xevm::MMAOp> {
603 matchAndRewrite(xevm::MMAOp op, xevm::MMAOp::Adaptor adaptor,
604 ConversionPatternRewriter &rewriter)
const override {
606 return rewriter.notifyMatchFailure(op,
"OCL requires C operand");
608 auto precisionA = op.getTypes().getA();
609 auto precisionB = op.getTypes().getB();
610 auto precisionC = op.getTypes().getC();
611 auto precisionD = op.getTypes().getD();
612 if (precisionC != precisionD) {
613 return rewriter.notifyMatchFailure(op,
"type of C and D need to match");
615 if (precisionC != xevm::ElemType::S32 &&
616 precisionC != xevm::ElemType::F32 &&
617 precisionC != xevm::ElemType::F16 &&
618 precisionC != xevm::ElemType::BF16) {
619 return rewriter.notifyMatchFailure(
620 op,
"type of C and D must be S32, F32, F16 or BF16");
622 if (precisionA == xevm::ElemType::S32 ||
623 precisionA == xevm::ElemType::F32) {
624 return rewriter.notifyMatchFailure(op,
"type of A cannot be S32 or F32");
626 if (precisionB == xevm::ElemType::S32 ||
627 precisionB == xevm::ElemType::F32) {
628 return rewriter.notifyMatchFailure(op,
"type of B cannot be S32 or F32");
630 constexpr uint32_t bitWidthPackedA{16};
631 constexpr uint32_t bitWidthPackedB{32};
632 auto loc = op.getLoc();
634 auto castIfNeeded = [&](Value val, Type packedType) -> Value {
635 VectorType origTy = cast<VectorType>(val.
getType());
636 const uint32_t vecBitSize =
637 origTy.getNumElements() *
638 origTy.getElementType().getIntOrFloatBitWidth();
639 VectorType newTy = VectorType::get(
640 vecBitSize / packedType.getIntOrFloatBitWidth(), packedType);
642 val = LLVM::BitcastOp::create(rewriter, loc, newTy, val);
647 Type packedAType = (op.getTypes().getA() == xevm::ElemType::TF32)
648 ? cast<Type>(rewriter.getF32Type())
649 : rewriter.getIntegerType(bitWidthPackedA);
650 a = castIfNeeded(a, packedAType);
653 Type packedBType = (op.getTypes().getB() == xevm::ElemType::TF32)
654 ? cast<Type>(rewriter.getF32Type())
655 : rewriter.getIntegerType(bitWidthPackedB);
656 b = castIfNeeded(
b, packedBType);
659 VectorType cOrigTy = cast<VectorType>(c.
getType());
660 VectorType resOrigTy = cast<VectorType>(op->getResultTypes()[0]);
661 assert(cOrigTy == resOrigTy &&
"Accumulator and result type mismatch");
664 cOrigTy.getElementType().isBF16()
665 ? VectorType::get(cOrigTy.getShape(), rewriter.getIntegerType(16))
667 VectorType resTy = cTy;
669 c = LLVM::BitcastOp::create(rewriter, loc, cTy, c);
671 constexpr int32_t systolicDepth{8};
673 llvm::formatv(
"intel_sub_group_{0}_{1}_matrix_mad_k{2}",
674 stringifyElemType(op.getTypes().getA()).str(),
675 stringifyElemType(op.getTypes().getB()).str(),
677 getNumOperandsPerDword(op.getTypes().getA()))
679 SmallVector<Type> argTypes{a.
getType(),
b.getType(), cTy};
680 fnName = mangle(fnName, argTypes);
681 SmallVector<Value> args{a,
b, c};
683 auto memAttr = rewriter.getAttr<LLVM::MemoryEffectsAttr>(
684 LLVM::ModRefInfo::NoModRef,
685 LLVM::ModRefInfo::NoModRef,
686 LLVM::ModRefInfo::NoModRef,
687 LLVM::ModRefInfo::NoModRef,
688 LLVM::ModRefInfo::NoModRef,
689 LLVM::ModRefInfo::NoModRef);
690 auto funcAttrs = convergentNoUnwindWillReturnAttrs;
691 funcAttrs.memEffectsAttr = memAttr;
693 createDeviceFunctionCall(rewriter, fnName, resTy, argTypes, args, {},
694 funcAttrs, op.getOperation())
697 if (resOrigTy != resTy)
698 result = LLVM::BitcastOp::create(rewriter, loc, resOrigTy,
result);
700 rewriter.replaceOp(op,
result);
705class PrefetchToOCLPattern :
public OpConversionPattern<PrefetchOp> {
708 matchAndRewrite(PrefetchOp op, PrefetchOp::Adaptor adaptor,
709 ConversionPatternRewriter &rewriter)
const override {
710 auto loc = op.getLoc();
713 const std::string fnName{
"_Z8prefetchPU3AS1Kcm"};
715 LLVM::ConstantOp::create(rewriter, loc, rewriter.getI64Type(), 1);
716 SmallVector<Value> args{op.getPtr(), one};
719 applyCacheControlAnnotation(rewriter, loc, op, args, moduleOp,
722 SmallVector<Type> argTypes;
723 for (
auto arg : args)
724 argTypes.push_back(arg.getType());
725 auto funcAttr = noUnwindAttrs;
726 auto memAttr = rewriter.getAttr<LLVM::MemoryEffectsAttr>(
727 LLVM::ModRefInfo::NoModRef,
728 LLVM::ModRefInfo::Ref,
729 LLVM::ModRefInfo::NoModRef,
730 LLVM::ModRefInfo::NoModRef,
731 LLVM::ModRefInfo::NoModRef,
732 LLVM::ModRefInfo::NoModRef);
733 funcAttr.memEffectsAttr = memAttr;
735 createDeviceFunctionCall(rewriter, fnName,
736 LLVM::LLVMVoidType::get(rewriter.getContext()),
737 argTypes, args, {}, funcAttr, op.getOperation());
738 rewriter.eraseOp(op);
743class MemfenceToOCLPattern :
public OpConversionPattern<MemfenceOp> {
746 matchAndRewrite(MemfenceOp op, MemfenceOp::Adaptor adaptor,
747 ConversionPatternRewriter &rewriter)
const override {
748 auto loc = op.getLoc();
749 const std::string fnName{
"atomic_work_item_fence"};
750 int memScope, addrSpace;
751 switch (op.getAddrspace()) {
752 case xevm::AddrSpace::SHARED:
755 case xevm::AddrSpace::GLOBAL:
760 return rewriter.notifyMatchFailure(
761 op,
"Fence only supports global and shared address spaces.");
763 switch (op.getScope()) {
764 case xevm::MemScope::WORKGROUP:
767 case xevm::MemScope::DEVICE:
772 return rewriter.notifyMatchFailure(
773 op,
"Fence only supports workgroup and device memory scopes.");
775 Type i32Type = rewriter.getI32Type();
776 Value acqRel = LLVM::ConstantOp::create(rewriter, loc, i32Type, 4);
777 Value memScopeConst =
778 LLVM::ConstantOp::create(rewriter, loc, i32Type, memScope);
779 Value addrSpaceConst =
780 LLVM::ConstantOp::create(rewriter, loc, i32Type, addrSpace);
781 SmallVector<Value> args{addrSpaceConst, acqRel, memScopeConst};
782 SmallVector<Type> argTypes{3, i32Type};
783 createDeviceFunctionCall(rewriter, mangle(fnName, argTypes),
784 LLVM::LLVMVoidType::get(rewriter.getContext()),
785 argTypes, args, {}, noUnwindAttrs,
787 rewriter.eraseOp(op);
791template <
typename OpType>
792class LoadStorePrefetchToOCLPattern :
public OpConversionPattern<OpType> {
793 using OpConversionPattern<OpType>::OpConversionPattern;
795 matchAndRewrite(OpType op,
typename OpType::Adaptor adaptor,
796 ConversionPatternRewriter &rewriter)
const override {
797 constexpr bool isLoad = std::is_same_v<OpType, BlockLoad2dOp>;
798 constexpr bool isPrefetch = std::is_same_v<OpType, BlockPrefetch2dOp>;
800 auto loc = op.getLoc();
801 auto *moduleOp = op->template getParentWithTrait<OpTrait::SymbolTable>();
803 bool packReg =
false;
804 bool transpose =
false;
805 if constexpr (isLoad) {
806 vecType = op.getRes().getType();
807 packReg = op.getPackRegister();
808 transpose = op.getTranspose();
809 }
else if constexpr (!isPrefetch) {
810 vecType = op.getStoredVal().getType();
813 auto i32Type = rewriter.getI32Type();
815 LLVM::UndefOp::create(rewriter, loc, VectorType::get(2, i32Type));
816 Value zero = LLVM::ConstantOp::create(rewriter, loc, i32Type, 0);
817 Value one = LLVM::ConstantOp::create(rewriter, loc, i32Type, 1);
818 byteCoord = LLVM::InsertElementOp::create(
819 rewriter, loc, VectorType::get(2, i32Type), byteCoord, op.getX(), zero);
820 byteCoord = LLVM::InsertElementOp::create(
821 rewriter, loc, VectorType::get(2, i32Type), byteCoord, op.getY(), one);
822 SmallVector<Value> args{op.getPtr(), op.getBaseWidth(), op.getBaseHeight(),
823 op.getBasePitch(), byteCoord};
826 applyCacheControlAnnotation(rewriter, loc, op, args, moduleOp,
829 SmallVector<Type> retTypes;
831 std::string funcName{
"intel_sub_group_2d_block_"};
832 std::string bitWidthId;
833 LLVMFuncAttributeOptions funcAttr{noUnwindWillReturnAttrs};
834 SmallVector<std::pair<unsigned, StringRef>, 4> paramAttrs;
835 if constexpr (isPrefetch) {
836 funcName +=
"prefetch";
837 paramAttrs = {std::make_pair(0, LLVM::LLVMDialect::getNonNullAttrName())};
838 auto memAttr = rewriter.getAttr<LLVM::MemoryEffectsAttr>(
839 LLVM::ModRefInfo::NoModRef,
840 LLVM::ModRefInfo::Ref,
841 LLVM::ModRefInfo::NoModRef,
842 LLVM::ModRefInfo::NoModRef,
843 LLVM::ModRefInfo::NoModRef,
844 LLVM::ModRefInfo::NoModRef);
845 funcAttr = noUnwindAttrs;
846 funcAttr.memEffectsAttr = memAttr;
848 auto vecElemType = vecType.getElementType();
849 auto vecElemBitWidth = vecElemType.getIntOrFloatBitWidth();
850 auto vecNumElems = vecType.getNumElements();
856 if (op.getElemSizeInBits() == 8 && op.getTileWidth() == 32) {
857 vecElemBitWidth = 16;
858 vecElemType = rewriter.getI16Type();
859 vecNumElems = vecNumElems / 2;
862 LLVM::ConstantOp::create(rewriter, loc, i32Type, vecNumElems);
863 auto dstOrSrcPtr = LLVM::AllocaOp::create(
864 rewriter, loc, LLVM::LLVMPointerType::get(rewriter.getContext()),
865 vecElemType, numElems);
866 args.push_back(dstOrSrcPtr);
867 if constexpr (isLoad) {
869 bitWidthId = getTypeMangling(vecElemType,
true);
871 funcName +=
"_transform";
873 funcName +=
"_transpose";
874 spvLoadDstPtr = dstOrSrcPtr;
875 retTypes.push_back(vecType);
877 std::make_pair(0, LLVM::LLVMDialect::getNonNullAttrName()),
878 std::make_pair(0, LLVM::LLVMDialect::getReadonlyAttrName()),
879 std::make_pair(5, LLVM::LLVMDialect::getNonNullAttrName()),
880 std::make_pair(5, LLVM::LLVMDialect::getWriteOnlyAttrName()),
884 bitWidthId = (vecElemBitWidth == 32)
886 : ((vecElemBitWidth == 16) ?
"t" :
"h");
887 LLVM::StoreOp::create(rewriter, loc, op.getStoredVal(), dstOrSrcPtr);
889 std::make_pair(0, LLVM::LLVMDialect::getNonNullAttrName()),
890 std::make_pair(0, LLVM::LLVMDialect::getWriteOnlyAttrName()),
891 std::make_pair(5, LLVM::LLVMDialect::getNonNullAttrName()),
892 std::make_pair(5, LLVM::LLVMDialect::getReadonlyAttrName()),
898 llvm::formatv(
"{0}_{1}b_{2}r{3}x{4}c", funcName, op.getElemSizeInBits(),
899 op.getTileHeight(), op.getTileWidth(), op.getVBlocks())
901 std::string prefetchCode(
"");
904 funcName = llvm::formatv(
"_Z{0}{1}PU3AS1viiiDv2_i{2}{3}", funcName.size(),
905 funcName, prefetchCode, bitWidthId)
907 SmallVector<Type> argTypes;
908 for (
auto arg : args) {
909 argTypes.push_back(arg.getType());
911 createDeviceFunctionCall(
912 rewriter, funcName, LLVM::LLVMVoidType::get(rewriter.getContext()),
913 argTypes, args, paramAttrs, funcAttr, op.getOperation());
915 if constexpr (isLoad)
917 op, LLVM::LoadOp::create(rewriter, loc, vecType, spvLoadDstPtr));
919 rewriter.eraseOp(op);
924template <
typename OpType>
925class BlockLoadStore1DToOCLPattern :
public OpConversionPattern<OpType> {
926 using OpConversionPattern<OpType>::OpConversionPattern;
928 matchAndRewrite(OpType op,
typename OpType::Adaptor adaptor,
929 ConversionPatternRewriter &rewriter)
const override {
930 constexpr bool isStore = std::is_same_v<OpType, xevm::BlockStoreOp>;
931 auto loc = op.getLoc();
932 auto *moduleOp = op->template getParentWithTrait<OpTrait::SymbolTable>();
937 std::string funcName{
"intel_sub_group_block_"};
940 if constexpr (isStore) {
941 funcName +=
"write_u";
942 valOrResTy = op.getVal().getType();
944 funcName +=
"read_u";
945 valOrResTy = op.getType();
948 VectorType vecTy = dyn_cast<VectorType>(valOrResTy);
949 Type elemType = vecTy ? vecTy.getElementType() : valOrResTy;
950 funcName += getTypeMangling(elemType);
952 funcName += std::to_string(vecTy.getNumElements());
953 SmallVector<Type, 2> argTypes{};
957 SmallVector<bool, 2> isUnsigned{};
961 SmallVector<Value, 2> args{};
962 args.push_back(op.getPtr());
963 argTypes.push_back(op.getPtr().getType());
964 isUnsigned.push_back(
true);
967 applyCacheControlAnnotation(rewriter, loc, op, args, moduleOp,
971 argTypes[0] = args[0].getType();
974 if constexpr (isStore) {
975 args.push_back(op.getVal());
976 argTypes.push_back(op.getVal().getType());
977 isUnsigned.push_back(
true);
978 retType = LLVM::LLVMVoidType::get(rewriter.getContext());
980 retType = valOrResTy;
982 funcName = std::string(
"_Z") + std::to_string(funcName.size()) + funcName +
984 std::to_string(op.getPtr().getType().getAddressSpace());
985 funcName += getTypeMangling(elemType,
true);
986 if constexpr (isStore)
987 funcName += getTypeMangling(valOrResTy,
true);
988 LLVMFuncAttributeOptions funcAttr{noUnwindWillReturnAttrs};
991 createDeviceFunctionCall(rewriter, funcName, retType, argTypes, args,
992 {}, funcAttr, op.getOperation());
994 if constexpr (isStore)
995 rewriter.eraseOp(op);
997 rewriter.replaceOp(op, call->getResult(0));
1002template <
typename OpType>
1003class LLVMLoadStoreToOCLPattern :
public OpConversionPattern<OpType> {
1004 using OpConversionPattern<OpType>::OpConversionPattern;
1006 matchAndRewrite(OpType op,
typename OpType::Adaptor adaptor,
1007 ConversionPatternRewriter &rewriter)
const override {
1008 if (!op->hasDiscardableAttr(
"cache_control"))
1011 auto *moduleOp = op->template getParentWithTrait<OpTrait::SymbolTable>();
1012 std::optional<ArrayAttr> optCacheControls =
1013 getCacheControlMetadata(rewriter, op);
1014 if (!optCacheControls) {
1015 rewriter.modifyOpInPlace(
1016 op, [&]() { op->removeDiscardableAttr(
"cache_control"); });
1021 constexpr bool isStore = std::is_same_v<OpType, LLVM::StoreOp>;
1022 unsigned ptrIdx = isStore ? 1 : 0;
1023 Value ptr = op->getOperand(ptrIdx);
1026 Value annotatedPtr = annotatePtrWithCacheControl(
1027 rewriter, op->getLoc(), ptr, *optCacheControls, moduleOp);
1030 rewriter.modifyOpInPlace(op, [&]() {
1031 op->setOperand(ptrIdx, annotatedPtr);
1032 op->removeDiscardableAttr(
"cache_control");
1065static std::pair<StringRef, int64_t> getConfig(xevm::WorkitemIdXOp) {
1066 return {
"get_local_id", 0};
1068static std::pair<StringRef, int64_t> getConfig(xevm::WorkitemIdYOp) {
1069 return {
"get_local_id", 1};
1071static std::pair<StringRef, int64_t> getConfig(xevm::WorkitemIdZOp) {
1072 return {
"get_local_id", 2};
1074static std::pair<StringRef, int64_t> getConfig(xevm::WorkgroupDimXOp) {
1075 return {
"get_local_size", 0};
1077static std::pair<StringRef, int64_t> getConfig(xevm::WorkgroupDimYOp) {
1078 return {
"get_local_size", 1};
1080static std::pair<StringRef, int64_t> getConfig(xevm::WorkgroupDimZOp) {
1081 return {
"get_local_size", 2};
1083static std::pair<StringRef, int64_t> getConfig(xevm::WorkgroupIdXOp) {
1084 return {
"get_group_id", 0};
1086static std::pair<StringRef, int64_t> getConfig(xevm::WorkgroupIdYOp) {
1087 return {
"get_group_id", 1};
1089static std::pair<StringRef, int64_t> getConfig(xevm::WorkgroupIdZOp) {
1090 return {
"get_group_id", 2};
1092static std::pair<StringRef, int64_t> getConfig(xevm::GridDimXOp) {
1093 return {
"get_num_groups", 0};
1095static std::pair<StringRef, int64_t> getConfig(xevm::GridDimYOp) {
1096 return {
"get_num_groups", 1};
1098static std::pair<StringRef, int64_t> getConfig(xevm::GridDimZOp) {
1099 return {
"get_num_groups", 2};
1103template <
typename OpType>
1104class LaunchConfigOpToOCLPattern :
public OpConversionPattern<OpType> {
1105 using OpConversionPattern<OpType>::OpConversionPattern;
1107 matchAndRewrite(OpType op,
typename OpType::Adaptor adaptor,
1108 ConversionPatternRewriter &rewriter)
const override {
1109 Location loc = op->getLoc();
1110 auto [baseName, dim] = getConfig(op);
1111 Type dimTy = rewriter.getI32Type();
1112 Value dimVal = LLVM::ConstantOp::create(rewriter, loc, dimTy,
1113 static_cast<int64_t
>(dim));
1114 std::string func = mangle(baseName, {dimTy}, {
true});
1115 Type resTy = op.getType();
1117 createDeviceFunctionCall(rewriter, func, resTy, {dimTy}, {dimVal}, {},
1118 noUnwindWillReturnAttrs, op.getOperation());
1119 constexpr auto noModRef = LLVM::ModRefInfo::NoModRef;
1120 auto memAttr = rewriter.getAttr<LLVM::MemoryEffectsAttr>(
1126 call.setMemoryEffectsAttr(memAttr);
1127 rewriter.replaceOp(op, call);
1144static StringRef getConfig(xevm::LaneIdOp) {
return "get_sub_group_local_id"; }
1145static StringRef getConfig(xevm::SubgroupIdOp) {
return "get_sub_group_id"; }
1146static StringRef getConfig(xevm::SubgroupSizeOp) {
1147 return "get_sub_group_size";
1149template <
typename OpType>
1150class SubgroupOpWorkitemOpToOCLPattern :
public OpConversionPattern<OpType> {
1151 using OpConversionPattern<OpType>::OpConversionPattern;
1153 matchAndRewrite(OpType op,
typename OpType::Adaptor adaptor,
1154 ConversionPatternRewriter &rewriter)
const override {
1155 std::string func = mangle(getConfig(op).str(), {});
1156 Type resTy = op.getType();
1158 createDeviceFunctionCall(rewriter, func, resTy, {}, {}, {},
1159 noUnwindWillReturnAttrs, op.getOperation());
1160 constexpr auto noModRef = LLVM::ModRefInfo::NoModRef;
1161 auto memAttr = rewriter.getAttr<LLVM::MemoryEffectsAttr>(
1167 call.setMemoryEffectsAttr(memAttr);
1168 rewriter.replaceOp(op, call);
1175static bool isSupportedSPIRVVectorLength(
int64_t numElements) {
1176 return llvm::is_contained({2, 3, 4, 8, 16}, numElements);
1180static Value castIfNeeded(ConversionPatternRewriter &rewriter,
Location loc,
1184 return LLVM::BitcastOp::create(rewriter, loc, ty, val);
1190static Value takeLeadingElements(ConversionPatternRewriter &rewriter,
1192 auto vecTy = cast<VectorType>(val.
getType());
1193 if (vecTy.getNumElements() == numElements)
1196 llvm::to_vector(llvm::seq<int32_t>(0,
static_cast<int32_t
>(numElements)));
1197 return LLVM::ShuffleVectorOp::create(rewriter, loc, val, val, mask);
1211class TruncfToOCLPattern :
public OpConversionPattern<TruncfOp> {
1214 matchAndRewrite(TruncfOp op, TruncfOp::Adaptor adaptor,
1215 ConversionPatternRewriter &rewriter)
const override {
1217 auto srcEtype = op.getSrcEtype().getEtype();
1218 auto dstEtype = op.getDstEtype().getEtype();
1224 auto vecSrcTy = dyn_cast<VectorType>(op.getSrc().getType());
1226 return rewriter.notifyMatchFailure(op,
"Scalar src is not supported.");
1228 int64_t numElements = vecSrcTy.getNumElements();
1229 if (!isSupportedSPIRVVectorLength(numElements))
1230 return rewriter.notifyMatchFailure(
1231 op,
"src vector length must be 2, 3, 4, 8 or 16");
1234 Type dstTy = op.getDst().getType();
1235 Location loc = op.getLoc();
1236 Value src = op.getSrc();
1237 auto memAttr = rewriter.getAttr<LLVM::MemoryEffectsAttr>(
1238 LLVM::ModRefInfo::NoModRef,
1239 LLVM::ModRefInfo::NoModRef,
1240 LLVM::ModRefInfo::NoModRef,
1241 LLVM::ModRefInfo::NoModRef,
1242 LLVM::ModRefInfo::NoModRef,
1243 LLVM::ModRefInfo::NoModRef);
1244 auto funcAttrs = convergentNoUnwindWillReturnAttrs;
1245 funcAttrs.memEffectsAttr = memAttr;
1248 if (dstEtype == TruncfDstElemTypes::E2M1) {
1258 constexpr int kDnsclConvertToE2M1 = 1;
1259 constexpr int kDnsclModeBytes02 = 0;
1260 constexpr int kDnsclModeBytes13 = 2;
1263 int64_t numLanes = llvm::divideCeil(numElements, 2);
1265 Type i32Ty = rewriter.getI32Type();
1266 Type i8Ty = rewriter.getI8Type();
1270 if (numElements != numLanes * 2) {
1271 SmallVector<int32_t> mask = llvm::to_vector(
1272 llvm::seq<int32_t>(0,
static_cast<int32_t
>(numElements)));
1274 mask.append(
static_cast<size_t>(numLanes * 2 - numElements), 0);
1275 padded = LLVM::ShuffleVectorOp::create(rewriter, loc, src, src, mask);
1281 laneVec = LLVM::BitcastOp::create(
1282 rewriter, loc, VectorType::get(numLanes, i32Ty), padded);
1284 laneVec = LLVM::BitcastOp::create(rewriter, loc, i32Ty, padded);
1285 auto getLane = [&](int64_t idx) -> Value {
1289 LLVM::ConstantOp::create(rewriter, loc, rewriter.getI32Type(), idx);
1290 return LLVM::ExtractElementOp::create(rewriter, loc, laneVec, pos)
1294 std::string fnName =
"__builtin_IB_dnscl_";
1295 fnName += (srcEtype == TruncfSrcElemTypes::F16) ?
"hf16" :
"bf16";
1297 LLVM::ConstantOp::create(rewriter, loc, i32Ty, kDnsclConvertToE2M1);
1298 auto genDnscl = [&](Value lo, Value hi,
int mode) -> Value {
1299 Value modeVal = LLVM::ConstantOp::create(rewriter, loc, i32Ty, mode);
1300 SmallVector<Type> argTypes{lo.
getType(), hi.getType(),
1302 SmallVector<Value> args{lo, hi, convertTo, modeVal};
1303 return createDeviceFunctionCall(rewriter, fnName, i32Ty, argTypes, args,
1304 {}, funcAttrs, op.getOperation())
1309 if (numLanes <= 2) {
1312 Value lo = getLane(0);
1316 : LLVM::UndefOp::create(rewriter, loc, i32Ty)->getResult(0);
1317 Value dword = genDnscl(lo, hi, kDnsclModeBytes02);
1318 if (numLanes == 1) {
1320 result = LLVM::TruncOp::create(rewriter, loc, i8Ty, dword);
1322 Value bytes = LLVM::BitcastOp::create(
1323 rewriter, loc, VectorType::get(4, i8Ty), dword);
1324 result = LLVM::ShuffleVectorOp::create(rewriter, loc, bytes, bytes,
1325 ArrayRef<int32_t>{0, 2});
1329 SmallVector<Value> dwords;
1330 for (int64_t base = 0; base < numLanes; base += 4) {
1335 Value lane0 = getLane(base);
1336 Value lane2 = getLane(base + 2);
1337 Value even = genDnscl(lane0, lane2, kDnsclModeBytes02);
1338 Value lane1 = getLane(base + 1);
1339 Value lane3 = getLane(base + 3);
1340 Value odd = genDnscl(lane1, lane3, kDnsclModeBytes13);
1341 dwords.push_back(LLVM::OrOp::create(rewriter, loc, even, odd));
1343 if (dwords.size() == 1) {
1346 Type packedTy = VectorType::get(dwords.size(), i32Ty);
1347 result = LLVM::UndefOp::create(rewriter, loc, packedTy);
1348 for (
auto [idx, dword] : llvm::enumerate(dwords)) {
1349 Value pos = LLVM::ConstantOp::create(rewriter, loc, i32Ty, idx);
1351 LLVM::InsertElementOp::create(rewriter, loc,
result, dword, pos)
1356 rewriter.replaceOp(op, castIfNeeded(rewriter, loc, dstTy,
result));
1379 bool srcIsBF16 = srcEtype == TruncfSrcElemTypes::BF16;
1381 src = LLVM::BitcastOp::create(
1383 VectorType::get(vecSrcTy.getShape(), rewriter.getI16Type()), src);
1384 StringRef convertName;
1385 if (dstEtype == TruncfDstElemTypes::BF8) {
1386 convertName = srcIsBF16 ?
"__builtin_spirv_ConvertBF16ToE5M2EXT"
1387 :
"__builtin_spirv_ConvertFP16ToE5M2EXT";
1388 }
else if (dstEtype == TruncfDstElemTypes::F8) {
1389 convertName = srcIsBF16 ?
"__builtin_spirv_ConvertBF16ToE4M3EXT"
1390 :
"__builtin_spirv_ConvertFP16ToE4M3EXT";
1392 return rewriter.notifyMatchFailure(
1393 op,
"Unsupported src, dst element type pair.");
1395 SmallVector<Type> argTypes{src.
getType()};
1396 SmallVector<Value> args{src};
1397 Value
result = createDeviceFunctionCall(
1398 rewriter, mangle(convertName, argTypes), dstTy, argTypes,
1399 args, {}, funcAttrs, op.getOperation())
1401 rewriter.replaceOp(op,
result);
1406class ExtfToOCLPattern :
public OpConversionPattern<ExtfOp> {
1409 matchAndRewrite(ExtfOp op, ExtfOp::Adaptor adaptor,
1410 ConversionPatternRewriter &rewriter)
const override {
1413 auto srcEtype = op.getSrcEtype().getEtype();
1414 auto dstEtype = op.getDstEtype().getEtype();
1417 Type srcTy = op.getSrc().getType();
1419 auto vecDstTy = dyn_cast<VectorType>(op.getDst().getType());
1421 return rewriter.notifyMatchFailure(op,
"Scalar dst is not supported.");
1423 int64_t numElements = vecDstTy.getNumElements();
1424 if (!isSupportedSPIRVVectorLength(numElements))
1425 return rewriter.notifyMatchFailure(
1426 op,
"dst vector length must be 2, 3, 4, 8 or 16");
1427 Location loc = op.getLoc();
1428 Value src = op.getSrc();
1429 auto memAttr = rewriter.getAttr<LLVM::MemoryEffectsAttr>(
1430 LLVM::ModRefInfo::NoModRef,
1431 LLVM::ModRefInfo::NoModRef,
1432 LLVM::ModRefInfo::NoModRef,
1433 LLVM::ModRefInfo::NoModRef,
1434 LLVM::ModRefInfo::NoModRef,
1435 LLVM::ModRefInfo::NoModRef);
1436 auto funcAttrs = convergentNoUnwindWillReturnAttrs;
1437 funcAttrs.memEffectsAttr = memAttr;
1440 if (srcEtype == ExtfSrcElemTypes::E2M1) {
1453 int64_t numBytes = llvm::divideCeil(numElements, 2);
1454 constexpr int kLutE2M1ToF16 = 7;
1455 constexpr int kLutE2M1ToBF16 = 5;
1457 (dstEtype == ExtfDstElemTypes::F16) ? kLutE2M1ToF16 : kLutE2M1ToBF16;
1458 Value lutIdx = LLVM::ConstantOp::create(rewriter, loc,
1459 rewriter.getI32Type(), lutIndex);
1460 Type lutTy = VectorType::get(16, rewriter.getI32Type());
1462 createDeviceFunctionCall(rewriter,
"__builtin_IB_shfl_idx4_lut",
1463 lutTy, {lutIdx.
getType()}, {lutIdx}, {},
1464 funcAttrs, op.getOperation())
1468 Type i8Ty = rewriter.getI8Type();
1469 Type i32Ty = rewriter.getI32Type();
1470 std::string fnName =
"__builtin_IB_shfl_idx4_to_fp16_";
1471 Type argTy, packedResTy;
1472 if (numBytes == 1) {
1474 packedResTy = i32Ty;
1476 fnName += std::to_string(numBytes) +
"_";
1477 argTy = VectorType::get(numBytes, i8Ty);
1478 packedResTy = VectorType::get(numBytes, i32Ty);
1481 SmallVector<Type> convArgTypes{lut.
getType(), argTy};
1482 SmallVector<Value> convArgs{lut, castIfNeeded(rewriter, loc, argTy, src)};
1484 createDeviceFunctionCall(rewriter, fnName, packedResTy, convArgTypes,
1485 convArgs, {}, funcAttrs, op.getOperation())
1489 Type wideTy = VectorType::get(numBytes * 2, vecDstTy.getElementType());
1490 result = LLVM::BitcastOp::create(rewriter, loc, wideTy,
result);
1491 result = takeLeadingElements(rewriter, loc,
result, numElements);
1492 rewriter.replaceOp(op,
result);
1498 auto vecSrcTy = dyn_cast<VectorType>(srcTy);
1499 if (!vecSrcTy || vecSrcTy.getNumElements() != numElements)
1500 return rewriter.notifyMatchFailure(
1501 op,
"fp8 src and dst must have the same number of elements");
1509 bool dstIsBF16 = dstEtype == ExtfDstElemTypes::BF16;
1510 StringRef convertName;
1511 if (srcEtype == ExtfSrcElemTypes::BF8) {
1512 convertName = dstIsBF16 ?
"__builtin_spirv_ConvertE5M2ToBF16EXT"
1513 :
"__builtin_spirv_ConvertE5M2ToFP16EXT";
1515 convertName = dstIsBF16 ?
"__builtin_spirv_ConvertE4M3ToBF16EXT"
1516 :
"__builtin_spirv_ConvertE4M3ToFP16EXT";
1518 Type resElemTy = dstIsBF16 ? cast<Type>(rewriter.getI16Type())
1519 : cast<Type>(rewriter.getF16Type());
1520 Type resTy = VectorType::get(vecSrcTy.getShape(), resElemTy);
1521 SmallVector<Type> argTypes{src.
getType()};
1522 SmallVector<Value> args{src};
1523 Value
result = createDeviceFunctionCall(
1524 rewriter, mangle(convertName, argTypes), resTy, argTypes,
1525 args, {}, funcAttrs, op.getOperation())
1529 rewriter.replaceOp(op, castIfNeeded(rewriter, loc, vecDstTy,
result));
1534class MMAMxToOCLPattern :
public OpConversionPattern<MMAMxOp> {
1537 matchAndRewrite(MMAMxOp op, MMAMxOp::Adaptor adaptor,
1538 ConversionPatternRewriter &rewriter)
const override {
1540 return rewriter.notifyMatchFailure(op,
"OCL requires C operand");
1542 auto precisionC = op.getTypes().getC();
1543 auto precisionD = op.getTypes().getD();
1544 if (precisionC != precisionD) {
1545 return rewriter.notifyMatchFailure(op,
"type of C and D need to match");
1548 constexpr uint32_t bitWidthPackedA{16};
1549 constexpr uint32_t bitWidthPackedB{32};
1550 auto loc = op.getLoc();
1552 auto castIfNeeded = [&](Value val, Type packedType) -> Value {
1553 VectorType origTy = cast<VectorType>(val.
getType());
1554 const uint32_t vecBitSize =
1555 origTy.getNumElements() *
1556 origTy.getElementType().getIntOrFloatBitWidth();
1557 VectorType newTy = VectorType::get(
1558 vecBitSize / packedType.getIntOrFloatBitWidth(), packedType);
1559 if (origTy != newTy)
1560 val = LLVM::BitcastOp::create(rewriter, loc, newTy, val);
1564 Value a = op.getA();
1565 Type packedAType = (op.getTypes().getA() == xevm::ElemType::TF32)
1566 ? cast<Type>(rewriter.getF32Type())
1567 : rewriter.getIntegerType(bitWidthPackedA);
1568 a = castIfNeeded(a, packedAType);
1570 Value
b = op.getB();
1571 Type packedBType = (op.getTypes().getB() == xevm::ElemType::TF32)
1572 ? cast<Type>(rewriter.getF32Type())
1573 : rewriter.getIntegerType(bitWidthPackedB);
1574 b = castIfNeeded(
b, packedBType);
1576 Value c = op.getC();
1577 VectorType cOrigTy = cast<VectorType>(c.
getType());
1578 VectorType resOrigTy = cast<VectorType>(op->getResultTypes()[0]);
1579 assert(cOrigTy == resOrigTy &&
"Accumulator and result type mismatch");
1582 cOrigTy.getElementType().isBF16()
1583 ? VectorType::get(cOrigTy.getShape(), rewriter.getIntegerType(16))
1585 VectorType resTy = cTy;
1587 c = LLVM::BitcastOp::create(rewriter, loc, cTy, c);
1589 std::string fnName =
1590 llvm::formatv(
"__builtin_IB_sub_group16_bdpas_{0}_{1}_{2}_{3}_8_8",
1591 builtinElemType(op.getTypes().getD()),
1592 builtinElemType(op.getTypes().getC()),
1593 builtinElemType(op.getTypes().getA()),
1594 builtinElemType(op.getTypes().getB()))
1596 auto scaleA = op.getScaleA();
1597 auto scaleB = op.getScaleB();
1598 SmallVector<Type> argTypes{cTy, a.
getType(),
b.getType(), scaleA.getType(),
1600 SmallVector<Value> args{c, a,
b, scaleA, scaleB};
1602 auto memAttr = rewriter.getAttr<LLVM::MemoryEffectsAttr>(
1603 LLVM::ModRefInfo::NoModRef,
1604 LLVM::ModRefInfo::NoModRef,
1605 LLVM::ModRefInfo::NoModRef,
1606 LLVM::ModRefInfo::NoModRef,
1607 LLVM::ModRefInfo::NoModRef,
1608 LLVM::ModRefInfo::NoModRef);
1609 auto funcAttrs = convergentNoUnwindWillReturnAttrs;
1610 funcAttrs.memEffectsAttr = memAttr;
1612 createDeviceFunctionCall(rewriter, fnName, resTy, argTypes, args, {},
1613 funcAttrs, op.getOperation())
1616 if (resOrigTy != resTy)
1617 result = LLVM::BitcastOp::create(rewriter, loc, resOrigTy,
result);
1619 rewriter.replaceOp(op,
result);
1632class BitcastShuffleToGenISAPattern
1633 :
public OpConversionPattern<BitcastShuffleOp> {
1636 matchAndRewrite(BitcastShuffleOp op, BitcastShuffleOp::Adaptor adaptor,
1637 ConversionPatternRewriter &rewriter)
const override {
1638 Type srcTy = op.getSrc().getType();
1639 Type resTy = op.getRes().getType();
1641 std::string fnName =
"llvm.genx.GenISA.SubgroupBitcastShuffle." +
1642 getGenISATypeMangling(resTy) +
"." +
1643 getGenISATypeMangling(srcTy);
1645 Value
result = createDeviceFunctionCall(
1646 rewriter, fnName, resTy, {srcTy}, {adaptor.getSrc()}, {},
1647 convergentNoUnwindWillReturnAttrs, op.getOperation())
1650 rewriter.replaceOp(op,
result);
1655class AllocaToGlobalPattern :
public OpConversionPattern<LLVM::AllocaOp> {
1658 matchAndRewrite(LLVM::AllocaOp op, LLVM::AllocaOp::Adaptor adaptor,
1659 ConversionPatternRewriter &rewriter)
const override {
1660 auto ptrType = cast<LLVM::LLVMPointerType>(op.getType());
1661 auto addrSpace = ptrType.getAddressSpace();
1664 auto symTable = op->getParentWithTrait<OpTrait::SymbolTable>();
1668 if (ModuleOp mod = dyn_cast<ModuleOp>(*symTable)) {
1669 moduleBody = mod.getBody();
1670 }
else if (gpu::GPUModuleOp gpuMod =
1671 dyn_cast<gpu::GPUModuleOp>(*symTable)) {
1672 moduleBody = gpuMod.getBody();
1676 auto val = op.getArraySize();
1680 auto loc = op.getLoc();
1681 auto globalType = LLVM::LLVMArrayType::get(
1682 rewriter.getContext(), op.getElemType(), cst.getZExtValue());
1683 LLVM::GlobalOp globalVar;
1685 OpBuilder::InsertionGuard guard(rewriter);
1686 rewriter.setInsertionPointToStart(moduleBody);
1687 auto alignment = op.getAlignment();
1688 globalVar = LLVM::GlobalOp::create(
1689 rewriter, loc, globalType,
false,
1690 LLVM::Linkage::Internal,
1691 std::string(
"__global_alloca_") +
1692 std::to_string(getNextGlobalIdx()),
1694 alignment ? *alignment : 0, addrSpace);
1696 rewriter.replaceOpWithNewOp<LLVM::AddressOfOp>(op, globalVar);
1701 static unsigned getNextGlobalIdx() {
1702 static unsigned globalIdx = 0;
1715static bool isExtractingContiguousSlice(LLVM::ShuffleVectorOp op) {
1716 if (op.getV1() != op.getV2() &&
1717 !isa_and_present<LLVM::PoisonOp, LLVM::UndefOp>(
1718 op.getV2().getDefiningOp()))
1720 auto maskAttr = op.getMask();
1722 int64_t sourceSize = op.getV1().getType().getNumElements();
1723 if (maskSize > sourceSize)
1725 int64_t firstIndex = maskAttr[0];
1726 if (firstIndex < 0 || firstIndex >= sourceSize)
1728 for (
int64_t i = 1; i < maskSize; ++i) {
1730 if (
index != firstIndex + i)
1732 if (
index >= sourceSize)
1748 return rewriter.
create(state);
1763class HandleVectorExtractPattern
1765 using OpRewritePattern<LLVM::ShuffleVectorOp>::OpRewritePattern;
1767 void initialize() { setHasBoundedRewriteRecursion(); }
1769 LogicalResult matchAndRewrite(LLVM::ShuffleVectorOp op,
1770 PatternRewriter &rewriter)
const override {
1772 if (!isExtractingContiguousSlice(op))
1775 auto mask = op.getMask();
1776 auto loc = op.getLoc();
1777 auto ty = op.getType();
1779 auto src = op.getV1();
1782 if (isa<LLVM::FPExtOp>(srcOp) || isa<LLVM::FPTruncOp>(srcOp)) {
1783 Value srcInput = srcOp->getOperand(0);
1785 auto srcVecTy = dyn_cast<VectorType>(srcInput.
getType());
1788 auto newShuffleVecTy =
1789 VectorType::get(mask.size(), srcVecTy.getElementType());
1790 auto newShuffle = LLVM::ShuffleVectorOp::create(
1791 rewriter, loc, newShuffleVecTy, srcInput, srcInput, mask);
1794 if (isa<LLVM::FPExtOp>(srcOp)) {
1795 newUnaryOp = LLVM::FPExtOp::create(rewriter, loc, ty, newShuffle);
1797 newUnaryOp = LLVM::FPTruncOp::create(rewriter, loc, ty, newShuffle);
1800 }
else if (isa<LLVM::BitcastOp>(srcOp)) {
1801 Value srcInput = srcOp->getOperand(0);
1804 auto srcInputVecTy = dyn_cast<VectorType>(srcInput.
getType());
1805 auto srcResVecTy = dyn_cast<VectorType>(srcOp->getResult(0).getType());
1806 if (!srcInputVecTy || !srcResVecTy)
1808 auto srcInputSize = srcInputVecTy.getNumElements();
1809 auto srcResSize = srcResVecTy.getNumElements();
1810 auto maskSize =
static_cast<int32_t
>(mask.size());
1811 if (srcInputSize > srcResSize) {
1814 if (srcResSize % srcInputSize != 0) {
1817 auto maskScale = srcResSize / srcInputSize;
1822 SmallVector<int32_t> newMask;
1823 if (maskScale != 1) {
1826 if (mask[0] % maskScale != 0 || maskSize % maskScale != 0) {
1830 int32_t newMaskSize = maskSize / maskScale;
1831 int32_t maskStart = mask[0] / maskScale;
1832 for (int32_t i = 0; i < newMaskSize; ++i) {
1833 newMask.push_back(maskStart + i);
1837 auto newShuffleVecTy = VectorType::get(
1838 static_cast<int64_t
>(mask.size()), srcInputVecTy.getElementType());
1839 auto newShuffle = LLVM::ShuffleVectorOp::create(
1840 rewriter, loc, newShuffleVecTy, srcInput, srcInput, mask);
1843 LLVM::BitcastOp::create(rewriter, loc, ty, newShuffle);
1845 }
else if (isa<LLVM::ShuffleVectorOp>(srcOp)) {
1850 auto srcShuffle = cast<LLVM::ShuffleVectorOp>(srcOp);
1851 if (!isExtractingContiguousSlice(srcShuffle))
1853 auto srcMask = srcShuffle.getMask();
1854 SmallVector<int32_t> combinedMask;
1855 for (
auto index : mask) {
1856 combinedMask.push_back(srcMask[index]);
1858 auto newShuffle = LLVM::ShuffleVectorOp::create(
1859 rewriter, loc, ty, srcShuffle.getV1(), srcShuffle.getV1(),
1862 }
else if (isa<LLVM::LoadOp>(srcOp)) {
1864 auto loadOp = cast<LLVM::LoadOp>(srcOp);
1865 auto loadPtr = loadOp.getAddr();
1866 auto loadAddrSpace = loadPtr.getType().getAddressSpace();
1867 if (loadAddrSpace != 0)
1869 auto loadTy = dyn_cast<VectorType>(loadOp.getType());
1872 auto elemTy = loadTy.getElementType();
1873 auto firstIndex = mask[0];
1874 auto newVecTy = VectorType::get(mask.size(), elemTy);
1877 auto newPtr = LLVM::GEPOp::create(
1879 LLVM::LLVMPointerType::get(rewriter.
getContext(), loadAddrSpace),
1880 elemTy, loadPtr, ArrayRef<LLVM::GEPArg>{firstIndex});
1881 auto newLoad = LLVM::LoadOp::create(rewriter, loc, newVecTy, newPtr);
1884 auto newLoad = LLVM::LoadOp::create(rewriter, loc, newVecTy, loadPtr);
1888 srcOp->getNumOperands() >= 1 &&
1892 cast<VectorType>(src.
getType()).getNumElements() > 16 &&
1893 llvm::all_of(srcOp->getOperands(), [&](Value operand) {
1894 auto operandTy = dyn_cast<VectorType>(operand.getType());
1895 auto srcTy = cast<VectorType>(src.getType());
1896 return operandTy && operandTy.getRank() == 1 &&
1897 operandTy.getNumElements() == srcTy.getNumElements();
1904 SmallVector<Value> newOperands;
1905 newOperands.reserve(srcOp->getNumOperands());
1906 for (Value operand : srcOp->getOperands()) {
1907 auto operandTy = cast<VectorType>(operand.
getType());
1909 VectorType::get(mask.size(), operandTy.getElementType());
1910 newOperands.push_back(LLVM::ShuffleVectorOp::create(
1911 rewriter, loc, sliceTy, operand, operand, mask));
1931struct ConvertXeVMToLLVMPass
1935 void getDependentDialects(DialectRegistry ®istry)
const override {
1936 registry.
insert<LLVM::LLVMDialect, XeVMDialect>();
1939 void runOnOperation()
override {
1943 if (
failed(applyPartialConversion(getOperation(),
target,
1944 std::move(patterns))))
1945 signalPassFailure();
1949 RewritePatternSet vectorPatterns(&
getContext());
1950 vectorPatterns.add<HandleVectorExtractPattern>(&
getContext());
1951 GreedyRewriteConfig config{};
1956 config.enableFolding(
false);
1973 target.addDynamicallyLegalDialect<LLVM::LLVMDialect>([](
Operation *op) {
1977 if (isa<LLVM::AllocaOp>(op)) {
1978 LLVM::AllocaOp aOp = cast<LLVM::AllocaOp>(op);
1979 LLVM::LLVMPointerType pTy = cast<LLVM::LLVMPointerType>(aOp.getType());
1980 auto addrSpace = pTy.getAddressSpace();
1981 return addrSpace != 3;
1984 return !op->hasDiscardableAttr(
"cache_control");
1986 target.addIllegalDialect<XeVMDialect>();
1987 patterns.
add<LoadStorePrefetchToOCLPattern<BlockLoad2dOp>,
1988 LoadStorePrefetchToOCLPattern<BlockStore2dOp>,
1989 LoadStorePrefetchToOCLPattern<BlockPrefetch2dOp>,
1990 MMAToOCLPattern, MemfenceToOCLPattern, PrefetchToOCLPattern,
1991 LLVMLoadStoreToOCLPattern<LLVM::LoadOp>,
1992 LLVMLoadStoreToOCLPattern<LLVM::StoreOp>,
1993 BlockLoadStore1DToOCLPattern<BlockLoadOp>,
1994 BlockLoadStore1DToOCLPattern<BlockStoreOp>,
1995 LaunchConfigOpToOCLPattern<WorkitemIdXOp>,
1996 LaunchConfigOpToOCLPattern<WorkitemIdYOp>,
1997 LaunchConfigOpToOCLPattern<WorkitemIdZOp>,
1998 LaunchConfigOpToOCLPattern<WorkgroupDimXOp>,
1999 LaunchConfigOpToOCLPattern<WorkgroupDimYOp>,
2000 LaunchConfigOpToOCLPattern<WorkgroupDimZOp>,
2001 LaunchConfigOpToOCLPattern<WorkgroupIdXOp>,
2002 LaunchConfigOpToOCLPattern<WorkgroupIdYOp>,
2003 LaunchConfigOpToOCLPattern<WorkgroupIdZOp>,
2004 LaunchConfigOpToOCLPattern<GridDimXOp>,
2005 LaunchConfigOpToOCLPattern<GridDimYOp>,
2006 LaunchConfigOpToOCLPattern<GridDimZOp>,
2007 SubgroupOpWorkitemOpToOCLPattern<LaneIdOp>,
2008 SubgroupOpWorkitemOpToOCLPattern<SubgroupIdOp>,
2009 SubgroupOpWorkitemOpToOCLPattern<SubgroupSizeOp>,
2010 TruncfToOCLPattern, ExtfToOCLPattern, MMAMxToOCLPattern,
2011 BitcastShuffleToGenISAPattern, AllocaToGlobalPattern>(
LogicalResult initialize(unsigned origNumLoops, ArrayRef< ReassociationIndices > foldedIterationDims)
static Operation * cloneOpWithOperandsAndTypes(RewriterBase &rewriter, Location loc, Operation *op, ArrayRef< Value > operands, ArrayRef< Type > resultTypes)
Attributes are known-constant values of operations.
MLIRContext * getContext() const
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
NamedAttribute represents a combination of a name and an Attribute value.
RAII guard to reset the insertion point of the builder when destroyed.
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
A trait used to provide symbol table functionalities to a region operation.
StringRef getStringRef() const
Return the name of this operation. This always succeeds.
Operation is the basic unit of execution within MLIR.
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Operation * getParentWithTrait()
Returns the closest surrounding parent operation with trait Trait.
Location getLoc()
The source location the operation was defined or derived from.
DictionaryAttr getRawDictionaryAttrs()
Return all attributes that are not stored as properties.
Attribute getPropertiesAsAttribute()
Return the properties converted to an attribute.
OperationName getName()
The name of an operation is the key identifier for it.
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< int32_t > content)
FailureOr< LLVM::LLVMFuncOp > lookupOrCreateFn(OpBuilder &b, Operation *moduleOp, StringRef name, ArrayRef< Type > paramTypes={}, Type resultType={}, bool isVarArg=false, bool isReserved=false, SymbolTableCollection *symbolTables=nullptr)
Create a FuncOp with signature resultType(paramTypes) and name name`.
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
detail::constant_int_value_binder m_ConstantInt(IntegerAttr::ValueType *bind_value)
Matches a constant holding a scalar/vector/tensor integer (splat) and writes the integer value to bin...
LogicalResult applyPatternsGreedily(Region ®ion, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
void populateXeVMToLLVMConversionPatterns(ConversionTarget &target, RewritePatternSet &patterns)
llvm::TypeSwitch< T, ResultT > TypeSwitch
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
This represents an operation in an abstracted form, suitable for use with the builder APIs.