LLVM 24.0.0git
X86LowerAMXIntrinsics.cpp
Go to the documentation of this file.
1//===-- X86LowerAMXIntrinsics.cpp -X86 Scalarize AMX Intrinsics------------===//
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/// \file Pass to transform amx intrinsics to scalar operations.
10/// This pass is always enabled and it skips when it is not -O0 and has no
11/// optnone attributes. With -O0 or optnone attribute, the def of shape to amx
12/// intrinsics is near the amx intrinsics code. We are not able to find a
13/// point which post-dominate all the shape and dominate all amx intrinsics.
14/// To decouple the dependency of the shape, we transform amx intrinsics
15/// to scalar operation, so that compiling doesn't fail. In long term, we
16/// should improve fast register allocation to allocate amx register.
17//===----------------------------------------------------------------------===//
18//
19#include "X86.h"
20#include "X86TargetMachine.h"
24#include "llvm/CodeGen/Passes.h"
27#include "llvm/IR/Analysis.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Dominators.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/IntrinsicsX86.h"
35#include "llvm/IR/MDBuilder.h"
36#include "llvm/IR/PassManager.h"
40#include "llvm/Pass.h"
44
45using namespace llvm;
46using namespace PatternMatch;
47
48#define DEBUG_TYPE "x86-lower-amx-intrinsics"
49
50#ifndef NDEBUG
51static bool isV256I32Ty(Type *Ty) {
52 if (auto *FVT = dyn_cast<FixedVectorType>(Ty))
53 return FVT->getNumElements() == 256 &&
54 FVT->getElementType()->isIntegerTy(32);
55 return false;
56}
57#endif
58
59namespace {
60class X86LowerAMXIntrinsics {
61 Function &Func;
62
63public:
64 X86LowerAMXIntrinsics(Function &F, DomTreeUpdater &DomTU, LoopInfo *LoopI)
65 : Func(F), DTU(DomTU), LI(LoopI) {}
66 bool visit();
67
68private:
69 DomTreeUpdater &DTU;
70 LoopInfo *LI;
71 BasicBlock *createLoop(BasicBlock *Preheader, BasicBlock *Exit, Value *Bound,
72 ConstantInt *Step, StringRef Name, IRBuilderBase &B,
73 Loop *L);
74 template <bool IsTileLoad>
75 Value *createTileLoadStoreLoops(BasicBlock *Start, BasicBlock *End,
76 IRBuilderBase &B, Value *Row, Value *Col,
77 Value *Ptr, Value *Stride, Value *Tile);
78 template <Intrinsic::ID IntrID>
79 std::enable_if_t<IntrID == Intrinsic::x86_tdpbssd_internal ||
80 IntrID == Intrinsic::x86_tdpbsud_internal ||
81 IntrID == Intrinsic::x86_tdpbusd_internal ||
82 IntrID == Intrinsic::x86_tdpbuud_internal ||
83 IntrID == Intrinsic::x86_tdpbf16ps_internal,
84 Value *>
85 createTileDPLoops(BasicBlock *Start, BasicBlock *End, IRBuilderBase &B,
86 Value *Row, Value *Col, Value *K, Value *Acc, Value *LHS,
87 Value *RHS);
88 template <bool IsTileLoad>
89 bool lowerTileLoadStore(Instruction *TileLoadStore);
90 template <Intrinsic::ID IntrID>
91 std::enable_if_t<IntrID == Intrinsic::x86_tdpbssd_internal ||
92 IntrID == Intrinsic::x86_tdpbsud_internal ||
93 IntrID == Intrinsic::x86_tdpbusd_internal ||
94 IntrID == Intrinsic::x86_tdpbuud_internal ||
95 IntrID == Intrinsic::x86_tdpbf16ps_internal,
96 bool>
97 lowerTileDP(Instruction *TileDP);
98 bool lowerTileZero(Instruction *TileZero);
99};
100} // anonymous namespace
101
102BasicBlock *X86LowerAMXIntrinsics::createLoop(BasicBlock *Preheader,
103 BasicBlock *Exit, Value *Bound,
104 ConstantInt *Step, StringRef Name,
105 IRBuilderBase &B, Loop *L) {
106 LLVMContext &Ctx = Preheader->getContext();
107 BasicBlock *Header =
108 BasicBlock::Create(Ctx, Name + ".header", Preheader->getParent(), Exit);
109 BasicBlock *Body =
110 BasicBlock::Create(Ctx, Name + ".body", Header->getParent(), Exit);
111 BasicBlock *Latch =
112 BasicBlock::Create(Ctx, Name + ".latch", Header->getParent(), Exit);
113
114 Type *I16Ty = Type::getInt16Ty(Ctx);
115 UncondBrInst::Create(Body, Header);
116 UncondBrInst::Create(Latch, Body);
117 PHINode *IV =
118 PHINode::Create(I16Ty, 2, Name + ".iv", Header->getTerminator()->getIterator());
119 IV->addIncoming(ConstantInt::get(I16Ty, 0), Preheader);
120
121 B.SetInsertPoint(Latch);
122 Value *Inc = B.CreateAdd(IV, Step, Name + ".step");
123 Value *Cond = B.CreateICmpNE(Inc, Bound, Name + ".cond");
124 auto *BR = CondBrInst::Create(Cond, Header, Exit, Latch);
125 if (auto *BoundInt = dyn_cast<ConstantInt>(Bound)) {
126 assert(Step->getZExtValue() != 0 &&
127 "Expected a non-zero step size. This is chosen by the pass and "
128 "should always be non-zero to imply a finite loop.");
129 MDBuilder MDB(Preheader->getContext());
131 *BR, {BoundInt->getZExtValue() / Step->getZExtValue(), 1}, false);
132 } else {
134 }
135 IV->addIncoming(Inc, Latch);
136
137 UncondBrInst *PreheaderBr = cast<UncondBrInst>(Preheader->getTerminator());
138 BasicBlock *Tmp = PreheaderBr->getSuccessor();
139 PreheaderBr->setSuccessor(Header);
141 {DominatorTree::Delete, Preheader, Tmp},
142 {DominatorTree::Insert, Header, Body},
143 {DominatorTree::Insert, Body, Latch},
144 {DominatorTree::Insert, Latch, Header},
145 {DominatorTree::Insert, Latch, Exit},
146 {DominatorTree::Insert, Preheader, Header},
147 });
148 if (LI) {
149 L->addBasicBlockToLoop(Header, *LI);
150 L->addBasicBlockToLoop(Body, *LI);
151 L->addBasicBlockToLoop(Latch, *LI);
152 }
153 return Body;
154}
155
156template <bool IsTileLoad>
157Value *X86LowerAMXIntrinsics::createTileLoadStoreLoops(
158 BasicBlock *Start, BasicBlock *End, IRBuilderBase &B, Value *Row,
159 Value *Col, Value *Ptr, Value *Stride, Value *Tile) {
160 std::string IntrinName = IsTileLoad ? "tileload" : "tilestore";
161 Loop *RowLoop = nullptr;
162 Loop *ColLoop = nullptr;
163 if (LI) {
164 RowLoop = LI->AllocateLoop();
165 ColLoop = LI->AllocateLoop();
166 RowLoop->addChildLoop(ColLoop);
167 if (Loop *ParentL = LI->getLoopFor(Start))
168 ParentL->addChildLoop(RowLoop);
169 else
170 LI->addTopLevelLoop(RowLoop);
171 }
172
173 BasicBlock *RowBody = createLoop(Start, End, Row, B.getInt16(1),
174 IntrinName + ".scalarize.rows", B, RowLoop);
175 BasicBlock *RowLatch = RowBody->getSingleSuccessor();
176
177 BasicBlock *ColBody = createLoop(RowBody, RowLatch, Col, B.getInt16(1),
178 IntrinName + ".scalarize.cols", B, ColLoop);
179
180 BasicBlock *ColLoopLatch = ColBody->getSingleSuccessor();
181 BasicBlock *ColLoopHeader = ColBody->getSinglePredecessor();
182 BasicBlock *RowLoopHeader = RowBody->getSinglePredecessor();
183 Value *CurrentRow = &*RowLoopHeader->begin();
184 Value *CurrentCol = &*ColLoopHeader->begin();
185 Type *EltTy = B.getInt32Ty();
186 FixedVectorType *V256I32Ty = FixedVectorType::get(EltTy, 256);
187
188 // Common part for tileload and tilestore
189 // *.scalarize.cols.body:
190 // Calculate %idxmem and %idxvec
191 B.SetInsertPoint(ColBody->getTerminator());
192 Value *CurrentRowZExt = B.CreateZExt(CurrentRow, Stride->getType());
193 Value *CurrentColZExt = B.CreateZExt(CurrentCol, Stride->getType());
194 Value *Offset =
195 B.CreateAdd(B.CreateMul(CurrentRowZExt, Stride), CurrentColZExt);
196 Value *EltPtr = B.CreateGEP(EltTy, Ptr, Offset);
197 Value *Idx = B.CreateAdd(B.CreateMul(CurrentRow, B.getInt16(16)), CurrentCol);
198 if (IsTileLoad) {
199 // tileload.scalarize.rows.header:
200 // %vec.phi.row = phi <256 x i32> [ zeroinitializer, %entry ], [ %ResVec,
201 // %tileload.scalarize.rows.latch ]
202 B.SetInsertPoint(RowLoopHeader->getTerminator());
203 Value *VecZero = Constant::getNullValue(V256I32Ty);
204 PHINode *VecCPhiRowLoop = B.CreatePHI(V256I32Ty, 2, "vec.phi.row");
205 VecCPhiRowLoop->addIncoming(VecZero, Start);
206
207 // tileload.scalarize.cols.header:
208 // %vec.phi = phi <256 x i32> [ %vec.phi.row, %tileload.scalarize.rows.body
209 // ], [ %ResVec, %tileload.scalarize.cols.latch ]
210 B.SetInsertPoint(ColLoopHeader->getTerminator());
211 PHINode *VecPhi = B.CreatePHI(V256I32Ty, 2, "vec.phi");
212 VecPhi->addIncoming(VecCPhiRowLoop, RowBody);
213
214 // tileload.scalarize.cols.body:
215 // Calculate %idxmem and %idxvec
216 // %eltptr = getelementptr i32, i32* %base, i64 %idxmem
217 // %elt = load i32, i32* %ptr
218 // %ResVec = insertelement <256 x i32> %vec.phi, i32 %elt, i16 %idxvec
219 B.SetInsertPoint(ColBody->getTerminator());
220 Value *Elt = B.CreateLoad(EltTy, EltPtr);
221 Value *ResVec = B.CreateInsertElement(VecPhi, Elt, Idx);
222 VecPhi->addIncoming(ResVec, ColLoopLatch);
223 VecCPhiRowLoop->addIncoming(ResVec, RowLatch);
224
225 return ResVec;
226 } else {
227 auto *BitCast = cast<BitCastInst>(Tile);
228 Value *Vec = BitCast->getOperand(0);
229 assert(isV256I32Ty(Vec->getType()) && "bitcast from non-v256i32 to x86amx");
230 // tilestore.scalarize.cols.body:
231 // %mul = mul i16 %row.iv, i16 16
232 // %idx = add i16 %mul, i16 %col.iv
233 // %vec = extractelement <16 x i32> %vec, i16 %idx
234 // store i32 %vec, i32* %ptr
235 B.SetInsertPoint(ColBody->getTerminator());
236 Value *Elt = B.CreateExtractElement(Vec, Idx);
237
238 B.CreateStore(Elt, EltPtr);
239 return nullptr;
240 }
241}
242
243template <Intrinsic::ID IntrID>
244std::enable_if_t<IntrID == Intrinsic::x86_tdpbssd_internal ||
245 IntrID == Intrinsic::x86_tdpbsud_internal ||
246 IntrID == Intrinsic::x86_tdpbusd_internal ||
247 IntrID == Intrinsic::x86_tdpbuud_internal ||
248 IntrID == Intrinsic::x86_tdpbf16ps_internal,
249 Value *>
250X86LowerAMXIntrinsics::createTileDPLoops(BasicBlock *Start, BasicBlock *End,
251 IRBuilderBase &B, Value *Row,
252 Value *Col, Value *K, Value *Acc,
253 Value *LHS, Value *RHS) {
254 std::string IntrinName;
255 switch (IntrID) {
256 case Intrinsic::x86_tdpbssd_internal:
257 IntrinName = "tiledpbssd";
258 break;
259 case Intrinsic::x86_tdpbsud_internal:
260 IntrinName = "tiledpbsud";
261 break;
262 case Intrinsic::x86_tdpbusd_internal:
263 IntrinName = "tiledpbusd";
264 break;
265 case Intrinsic::x86_tdpbuud_internal:
266 IntrinName = "tiledpbuud";
267 break;
268 case Intrinsic::x86_tdpbf16ps_internal:
269 IntrinName = "tiledpbf16ps";
270 break;
271 }
272 Loop *RowLoop = nullptr;
273 Loop *ColLoop = nullptr;
274 Loop *InnerLoop = nullptr;
275 if (LI) {
276 RowLoop = LI->AllocateLoop();
277 ColLoop = LI->AllocateLoop();
278 InnerLoop = LI->AllocateLoop();
279 ColLoop->addChildLoop(InnerLoop);
280 RowLoop->addChildLoop(ColLoop);
281 if (Loop *ParentL = LI->getLoopFor(Start))
282 ParentL->addChildLoop(RowLoop);
283 else
284 LI->addTopLevelLoop(RowLoop);
285 }
286
287 BasicBlock *RowBody = createLoop(Start, End, Row, B.getInt16(1),
288 IntrinName + ".scalarize.rows", B, RowLoop);
289 BasicBlock *RowLatch = RowBody->getSingleSuccessor();
290
291 BasicBlock *ColBody = createLoop(RowBody, RowLatch, Col, B.getInt16(1),
292 IntrinName + ".scalarize.cols", B, ColLoop);
293
294 BasicBlock *ColLoopLatch = ColBody->getSingleSuccessor();
295
296 B.SetInsertPoint(ColBody->getTerminator());
297 BasicBlock *InnerBody =
298 createLoop(ColBody, ColLoopLatch, K, B.getInt16(1),
299 IntrinName + ".scalarize.inner", B, InnerLoop);
300
301 BasicBlock *ColLoopHeader = ColBody->getSinglePredecessor();
302 BasicBlock *RowLoopHeader = RowBody->getSinglePredecessor();
303 BasicBlock *InnerLoopHeader = InnerBody->getSinglePredecessor();
304 BasicBlock *InnerLoopLatch = InnerBody->getSingleSuccessor();
305 Value *CurrentRow = &*RowLoopHeader->begin();
306 Value *CurrentCol = &*ColLoopHeader->begin();
307 Value *CurrentInner = &*InnerLoopHeader->begin();
308
309 FixedVectorType *V256I32Ty = FixedVectorType::get(B.getInt32Ty(), 256);
310 auto *BitCastAcc = cast<BitCastInst>(Acc);
311 Value *VecC = BitCastAcc->getOperand(0);
312 assert(isV256I32Ty(VecC->getType()) && "bitcast from non-v256i32 to x86amx");
313 // TODO else create BitCast from x86amx to v256i32.
314 // Store x86amx to memory, and reload from memory
315 // to vector. However with -O0, it doesn't happen.
316 auto *BitCastLHS = cast<BitCastInst>(LHS);
317 Value *VecA = BitCastLHS->getOperand(0);
318 assert(isV256I32Ty(VecA->getType()) && "bitcast from non-v256i32 to x86amx");
319 auto *BitCastRHS = cast<BitCastInst>(RHS);
320 Value *VecB = BitCastRHS->getOperand(0);
321 assert(isV256I32Ty(VecB->getType()) && "bitcast from non-v256i32 to x86amx");
322
323 // tiledpbssd.scalarize.rows.header:
324 // %vec.c.phi.row = phi <256 x i32> [ %VecC, %continue ], [ %NewVecC,
325 // %tiledpbssd.scalarize.rows.latch ]
326
327 // %vec.d.phi.row = phi <256 x i32> [ zeroinitializer, %continue ], [
328 // %NewVecD, %tiledpbssd.scalarize.rows.latch ]
329 B.SetInsertPoint(RowLoopHeader->getTerminator());
330 PHINode *VecCPhiRowLoop = B.CreatePHI(V256I32Ty, 2, "vec.c.phi.row");
331 VecCPhiRowLoop->addIncoming(VecC, Start);
332 Value *VecZero = Constant::getNullValue(V256I32Ty);
333 PHINode *VecDPhiRowLoop = B.CreatePHI(V256I32Ty, 2, "vec.d.phi.row");
334 VecDPhiRowLoop->addIncoming(VecZero, Start);
335
336 // tiledpbssd.scalarize.cols.header:
337 // %vec.c.phi.col = phi <256 x i32> [ %vec.c.phi.row,
338 // %tiledpbssd.scalarize.rows.body ], [ %NewVecC,
339 // %tiledpbssd.scalarize.cols.latch ]
340
341 // %vec.d.phi.col = phi <256 x i32> [
342 // %vec.d.phi.row, %tiledpbssd.scalarize.rows.body ], [ %NewVecD,
343 // %tiledpbssd.scalarize.cols.latch ]
344
345 // calculate idxc.
346 B.SetInsertPoint(ColLoopHeader->getTerminator());
347 PHINode *VecCPhiColLoop = B.CreatePHI(V256I32Ty, 2, "vec.c.phi.col");
348 VecCPhiColLoop->addIncoming(VecCPhiRowLoop, RowBody);
349 PHINode *VecDPhiColLoop = B.CreatePHI(V256I32Ty, 2, "vec.d.phi.col");
350 VecDPhiColLoop->addIncoming(VecDPhiRowLoop, RowBody);
351 Value *IdxC =
352 B.CreateAdd(B.CreateMul(CurrentRow, B.getInt16(16)), CurrentCol);
353
354 // tiledpbssd.scalarize.inner.header:
355 // %vec.c.inner.phi = phi <256 x i32> [ %vec.c.phi.col,
356 // %tiledpbssd.scalarize.cols.body ], [ %NewVecC,
357 // %tiledpbssd.scalarize.inner.latch ]
358
359 B.SetInsertPoint(InnerLoopHeader->getTerminator());
360 PHINode *VecCPhi = B.CreatePHI(V256I32Ty, 2, "vec.c.inner.phi");
361 VecCPhi->addIncoming(VecCPhiColLoop, ColBody);
362
363 B.SetInsertPoint(InnerBody->getTerminator());
364 Value *IdxA =
365 B.CreateAdd(B.CreateMul(CurrentRow, B.getInt16(16)), CurrentInner);
366 Value *IdxB =
367 B.CreateAdd(B.CreateMul(CurrentInner, B.getInt16(16)), CurrentCol);
368 Value *NewVecC = nullptr;
369
370 if (IntrID != Intrinsic::x86_tdpbf16ps_internal) {
371 // tiledpbssd.scalarize.inner.body:
372 // calculate idxa, idxb
373 // %eltc = extractelement <256 x i32> %vec.c.inner.phi, i16 %idxc
374 // %elta = extractelement <256 x i32> %veca, i16 %idxa
375 // %eltav4i8 = bitcast i32 %elta to <4 x i8>
376 // %eltb = extractelement <256 x i32> %vecb, i16 %idxb
377 // %eltbv4i8 = bitcast i32 %eltb to <4 x i8>
378 // %eltav4i32 = sext <4 x i8> %eltav4i8 to <4 x i32>
379 // %eltbv4i32 = sext <4 x i8> %eltbv4i8 to <4 x i32>
380 // %mulab = mul <4 x i32> %eltbv4i32, %eltav4i32
381 // %acc = call i32 @llvm.vector.reduce.add.v4i32(<4 x i32> %131)
382 // %neweltc = add i32 %elt, %acc
383 // %NewVecC = insertelement <256 x i32> %vec.c.inner.phi, i32 %neweltc,
384 // i16 %idxc
385 FixedVectorType *V4I8Ty = FixedVectorType::get(B.getInt8Ty(), 4);
386 FixedVectorType *V4I32Ty = FixedVectorType::get(B.getInt32Ty(), 4);
387 Value *EltC = B.CreateExtractElement(VecCPhi, IdxC);
388 Value *EltA = B.CreateExtractElement(VecA, IdxA);
389 Value *SubVecA = B.CreateBitCast(EltA, V4I8Ty);
390 Value *EltB = B.CreateExtractElement(VecB, IdxB);
391 Value *SubVecB = B.CreateBitCast(EltB, V4I8Ty);
392 Value *SEXTSubVecB = nullptr;
393 Value *SEXTSubVecA = nullptr;
394 switch (IntrID) {
395 case Intrinsic::x86_tdpbssd_internal:
396 SEXTSubVecB = B.CreateSExt(SubVecB, V4I32Ty);
397 SEXTSubVecA = B.CreateSExt(SubVecA, V4I32Ty);
398 break;
399 case Intrinsic::x86_tdpbsud_internal:
400 SEXTSubVecB = B.CreateZExt(SubVecB, V4I32Ty);
401 SEXTSubVecA = B.CreateSExt(SubVecA, V4I32Ty);
402 break;
403 case Intrinsic::x86_tdpbusd_internal:
404 SEXTSubVecB = B.CreateSExt(SubVecB, V4I32Ty);
405 SEXTSubVecA = B.CreateZExt(SubVecA, V4I32Ty);
406 break;
407 case Intrinsic::x86_tdpbuud_internal:
408 SEXTSubVecB = B.CreateZExt(SubVecB, V4I32Ty);
409 SEXTSubVecA = B.CreateZExt(SubVecA, V4I32Ty);
410 break;
411 default:
412 llvm_unreachable("Invalid intrinsic ID!");
413 }
414 Value *SubVecR = B.CreateAddReduce(B.CreateMul(SEXTSubVecA, SEXTSubVecB));
415 Value *ResElt = B.CreateAdd(EltC, SubVecR);
416 NewVecC = B.CreateInsertElement(VecCPhi, ResElt, IdxC);
417 } else {
418 // tiledpbf16ps.scalarize.inner.body:
419 // calculate idxa, idxb, idxc
420 // %eltc = extractelement <256 x i32> %vec.c.inner.phi, i16 %idxc
421 // %eltcf32 = bitcast i32 %eltc to float
422 // %elta = extractelement <256 x i32> %veca, i16 %idxa
423 // %eltav2i16 = bitcast i32 %elta to <2 x i16>
424 // %eltb = extractelement <256 x i32> %vecb, i16 %idxb
425 // %eltbv2i16 = bitcast i32 %eltb to <2 x i16>
426 // %shufflea = shufflevector <2 x i16> %elta, <2 x i16> zeroinitializer, <4
427 // x i32> <i32 2, i32 0, i32 3, i32 1>
428 // %eltav2f32 = bitcast <4 x i16> %shufflea to <2 x float>
429 // %shuffleb = shufflevector <2 x i16> %eltb, <2 xi16> zeroinitializer, <4 x
430 // i32> <i32 2, i32 0, i32 3, i32 1>
431 // %eltbv2f32 = bitcast <4 x i16> %shuffleb to <2 x float>
432 // %mulab = fmul <2 x float> %eltav2f32, %eltbv2f32
433 // %acc = call float
434 // @llvm.vector.reduce.fadd.v2f32(float %eltcf32, <2 x float> %mulab)
435 // %neweltc = bitcast float %acc to i32
436 // %NewVecC = insertelement <256 x i32> %vec.c.inner.phi, i32 %neweltc,
437 // i16 %idxc
438 // %NewVecD = insertelement <256 x i32> %vec.d.inner.phi, i32 %neweltc,
439 // i16 %idxc
440 FixedVectorType *V2I16Ty = FixedVectorType::get(B.getInt16Ty(), 2);
441 FixedVectorType *V2F32Ty = FixedVectorType::get(B.getFloatTy(), 2);
442 Value *EltC = B.CreateExtractElement(VecCPhi, IdxC);
443 Value *EltCF32 = B.CreateBitCast(EltC, B.getFloatTy());
444 Value *EltA = B.CreateExtractElement(VecA, IdxA);
445 Value *SubVecA = B.CreateBitCast(EltA, V2I16Ty);
446 Value *EltB = B.CreateExtractElement(VecB, IdxB);
447 Value *SubVecB = B.CreateBitCast(EltB, V2I16Ty);
448 Value *ZeroV2I16 = Constant::getNullValue(V2I16Ty);
449 int ShuffleMask[4] = {2, 0, 3, 1};
450 auto ShuffleArray = ArrayRef(ShuffleMask);
451 Value *AV2F32 = B.CreateBitCast(
452 B.CreateShuffleVector(SubVecA, ZeroV2I16, ShuffleArray), V2F32Ty);
453 Value *BV2F32 = B.CreateBitCast(
454 B.CreateShuffleVector(SubVecB, ZeroV2I16, ShuffleArray), V2F32Ty);
455 Value *SubVecR = B.CreateFAddReduce(EltCF32, B.CreateFMul(AV2F32, BV2F32));
456 Value *ResElt = B.CreateBitCast(SubVecR, B.getInt32Ty());
457 NewVecC = B.CreateInsertElement(VecCPhi, ResElt, IdxC);
458 }
459
460 // tiledpbssd.scalarize.cols.latch:
461 // %NewEltC = extractelement <256 x i32> %vec.c.phi.col, i16 %idxc
462 // %NewVecD = insertelement <256 x i32> %vec.d.phi.col, i32 %NewEltC,
463 // i16 %idxc
464 B.SetInsertPoint(ColLoopLatch->getTerminator());
465 Value *NewEltC = B.CreateExtractElement(NewVecC, IdxC);
466 Value *NewVecD = B.CreateInsertElement(VecDPhiColLoop, NewEltC, IdxC);
467
468 VecCPhi->addIncoming(NewVecC, InnerLoopLatch);
469 VecCPhiRowLoop->addIncoming(NewVecC, RowLatch);
470 VecCPhiColLoop->addIncoming(NewVecC, ColLoopLatch);
471 VecDPhiRowLoop->addIncoming(NewVecD, RowLatch);
472 VecDPhiColLoop->addIncoming(NewVecD, ColLoopLatch);
473
474 return NewVecD;
475}
476
477template <Intrinsic::ID IntrID>
478std::enable_if_t<IntrID == Intrinsic::x86_tdpbssd_internal ||
479 IntrID == Intrinsic::x86_tdpbsud_internal ||
480 IntrID == Intrinsic::x86_tdpbusd_internal ||
481 IntrID == Intrinsic::x86_tdpbuud_internal ||
482 IntrID == Intrinsic::x86_tdpbf16ps_internal,
483 bool>
484X86LowerAMXIntrinsics::lowerTileDP(Instruction *TileDP) {
485 Value *M, *N, *K, *C, *A, *B;
487 m_Value(C), m_Value(A), m_Value(B)));
488 Instruction *InsertI = TileDP;
489 IRBuilder<> PreBuilder(TileDP);
490 PreBuilder.SetInsertPoint(TileDP);
491 // We visit the loop with (m, n/4, k/4):
492 // %n_dword = lshr i16 %n, 2
493 // %k_dword = lshr i16 %k, 2
494 Value *NDWord = PreBuilder.CreateLShr(N, PreBuilder.getInt16(2));
495 Value *KDWord = PreBuilder.CreateLShr(K, PreBuilder.getInt16(2));
496 BasicBlock *Start = InsertI->getParent();
497 BasicBlock *End =
498 SplitBlock(InsertI->getParent(), InsertI, &DTU, LI, nullptr, "continue");
499 IRBuilder<> Builder(TileDP);
500 Value *ResVec = createTileDPLoops<IntrID>(Start, End, Builder, M, NDWord,
501 KDWord, C, A, B);
502 // we cannot assume there always be bitcast after tiledpbssd. So we need to
503 // insert one bitcast as required
504 Builder.SetInsertPoint(End->getFirstNonPHIIt());
505 Value *ResAMX =
506 Builder.CreateBitCast(ResVec, Type::getX86_AMXTy(Builder.getContext()));
507 // Delete TileDP intrinsic and do some clean-up.
508 for (Use &U : llvm::make_early_inc_range(TileDP->uses())) {
509 Instruction *I = cast<Instruction>(U.getUser());
510 Value *Vec;
511 if (match(I, m_BitCast(m_Value(Vec)))) {
512 I->replaceAllUsesWith(ResVec);
513 I->eraseFromParent();
514 }
515 }
516 TileDP->replaceAllUsesWith(ResAMX);
517 TileDP->eraseFromParent();
518 return true;
519}
520
521template <bool IsTileLoad>
522bool X86LowerAMXIntrinsics::lowerTileLoadStore(Instruction *TileLoadStore) {
523 Value *M, *N, *Ptr, *Stride, *Tile;
524 if (IsTileLoad)
525 match(TileLoadStore,
527 m_Value(M), m_Value(N), m_Value(Ptr), m_Value(Stride)));
528 else
530 m_Value(M), m_Value(N), m_Value(Ptr),
531 m_Value(Stride), m_Value(Tile)));
532
533 Instruction *InsertI = TileLoadStore;
534 IRBuilder<> PreBuilder(TileLoadStore);
535 PreBuilder.SetInsertPoint(TileLoadStore);
536 Value *NDWord = PreBuilder.CreateLShr(N, PreBuilder.getInt16(2));
537 Value *StrideDWord = PreBuilder.CreateLShr(Stride, PreBuilder.getInt64(2));
538 BasicBlock *Start = InsertI->getParent();
539 BasicBlock *End =
540 SplitBlock(InsertI->getParent(), InsertI, &DTU, LI, nullptr, "continue");
541 IRBuilder<> Builder(TileLoadStore);
542 Value *ResVec = createTileLoadStoreLoops<IsTileLoad>(
543 Start, End, Builder, M, NDWord, Ptr, StrideDWord,
544 IsTileLoad ? nullptr : Tile);
545 if (IsTileLoad) {
546 // we cannot assume there always be bitcast after tileload. So we need to
547 // insert one bitcast as required
548 Builder.SetInsertPoint(End->getFirstNonPHIIt());
549 Value *ResAMX =
550 Builder.CreateBitCast(ResVec, Type::getX86_AMXTy(Builder.getContext()));
551 // Delete tileloadd6 intrinsic and do some clean-up
552 for (Use &U : llvm::make_early_inc_range(TileLoadStore->uses())) {
553 Instruction *I = cast<Instruction>(U.getUser());
554 Value *Vec;
555 if (match(I, m_BitCast(m_Value(Vec)))) {
556 I->replaceAllUsesWith(ResVec);
557 I->eraseFromParent();
558 }
559 }
560 TileLoadStore->replaceAllUsesWith(ResAMX);
561 }
562 TileLoadStore->eraseFromParent();
563 return true;
564}
565
566bool X86LowerAMXIntrinsics::lowerTileZero(Instruction *TileZero) {
567 IRBuilder<> Builder(TileZero);
568 FixedVectorType *V256I32Ty = FixedVectorType::get(Builder.getInt32Ty(), 256);
569 Value *VecZero = Constant::getNullValue(V256I32Ty);
570 for (Use &U : llvm::make_early_inc_range(TileZero->uses())) {
571 Instruction *I = cast<Instruction>(U.getUser());
572 Value *Vec;
573 if (match(I, m_BitCast(m_Value(Vec)))) {
574 I->replaceAllUsesWith(VecZero);
575 I->eraseFromParent();
576 }
577 }
578 TileZero->eraseFromParent();
579 return true;
580}
581
582bool X86LowerAMXIntrinsics::visit() {
583 bool C = false;
585 for (BasicBlock *BB : depth_first(&Func)) {
586 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
587 if (auto *Inst = dyn_cast<IntrinsicInst>(&*II++)) {
588 switch (Inst->getIntrinsicID()) {
589 case Intrinsic::x86_tdpbssd_internal:
590 case Intrinsic::x86_tdpbsud_internal:
591 case Intrinsic::x86_tdpbusd_internal:
592 case Intrinsic::x86_tdpbuud_internal:
593 case Intrinsic::x86_tileloadd64_internal:
594 case Intrinsic::x86_tilestored64_internal:
595 case Intrinsic::x86_tilezero_internal:
596 case Intrinsic::x86_tdpbf16ps_internal:
597 WorkList.push_back(Inst);
598 break;
599 default:
600 break;
601 }
602 }
603 }
604 }
605
606 for (auto *Inst : WorkList) {
607 switch (Inst->getIntrinsicID()) {
608 case Intrinsic::x86_tdpbssd_internal:
609 C = lowerTileDP<Intrinsic::x86_tdpbssd_internal>(Inst) || C;
610 break;
611 case Intrinsic::x86_tdpbsud_internal:
612 C = lowerTileDP<Intrinsic::x86_tdpbsud_internal>(Inst) || C;
613 break;
614 case Intrinsic::x86_tdpbusd_internal:
615 C = lowerTileDP<Intrinsic::x86_tdpbusd_internal>(Inst) || C;
616 break;
617 case Intrinsic::x86_tdpbuud_internal:
618 C = lowerTileDP<Intrinsic::x86_tdpbuud_internal>(Inst) || C;
619 break;
620 case Intrinsic::x86_tdpbf16ps_internal:
621 C = lowerTileDP<Intrinsic::x86_tdpbf16ps_internal>(Inst) || C;
622 break;
623 case Intrinsic::x86_tileloadd64_internal:
624 C = lowerTileLoadStore<true>(Inst) || C;
625 break;
626 case Intrinsic::x86_tilestored64_internal:
627 C = lowerTileLoadStore<false>(Inst) || C;
628 break;
629 case Intrinsic::x86_tilezero_internal:
630 C = lowerTileZero(Inst) || C;
631 break;
632 default:
633 llvm_unreachable("invalid amx intrinsics!");
634 }
635 }
636
637 return C;
638}
639
640namespace {
641bool shouldRunLowerAMXIntrinsics(const Function &F, const TargetMachine *TM) {
642 const X86Options &CLOpts =
643 static_cast<const X86TargetMachine *>(TM)->getCLOpts();
644 return CLOpts.enable_x86_scalar_amx &&
645 (F.hasFnAttribute(Attribute::OptimizeNone) ||
646 TM->getOptLevel() == CodeGenOptLevel::None);
647}
648
649bool runLowerAMXIntrinsics(Function &F, DominatorTree *DT, LoopInfo *LI) {
650 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
651
652 X86LowerAMXIntrinsics LAT(F, DTU, LI);
653 return LAT.visit();
654}
655} // namespace
656
659 if (!shouldRunLowerAMXIntrinsics(F, TM))
660 return PreservedAnalyses::all();
661
662 DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
663 LoopInfo &LI = FAM.getResult<LoopAnalysis>(F);
664 bool Changed = runLowerAMXIntrinsics(F, &DT, &LI);
665 if (!Changed)
666 return PreservedAnalyses::all();
667
671 return PA;
672}
673
674namespace {
675class X86LowerAMXIntrinsicsLegacyPass : public FunctionPass {
676public:
677 static char ID;
678
679 X86LowerAMXIntrinsicsLegacyPass() : FunctionPass(ID) {}
680
681 bool runOnFunction(Function &F) override {
682 TargetMachine *TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
683 if (!shouldRunLowerAMXIntrinsics(F, TM))
684 return false;
685
686 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
687 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
688 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
689 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
690 return runLowerAMXIntrinsics(F, DT, LI);
691 }
692 StringRef getPassName() const override { return "Lower AMX intrinsics"; }
693
694 void getAnalysisUsage(AnalysisUsage &AU) const override {
695 AU.addPreserved<DominatorTreeWrapperPass>();
696 AU.addPreserved<LoopInfoWrapperPass>();
697 AU.addRequired<TargetPassConfig>();
698 }
699};
700} // namespace
701
702static const char PassName[] = "Lower AMX intrinsics";
703char X86LowerAMXIntrinsicsLegacyPass::ID = 0;
704INITIALIZE_PASS_BEGIN(X86LowerAMXIntrinsicsLegacyPass, DEBUG_TYPE, PassName,
705 false, false)
707INITIALIZE_PASS_END(X86LowerAMXIntrinsicsLegacyPass, DEBUG_TYPE, PassName,
709
711 return new X86LowerAMXIntrinsicsLegacyPass();
712}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
This header defines various interfaces for pass management in LLVM.
SmallVector< MachineOperand, 4 > Cond
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file contains the declarations for profiling metadata utility functions.
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
Target-Independent Code Generator Pass Configuration Options pass.
This pass exposes codegen information to IR-level passes.
static bool isV256I32Ty(Type *Ty)
static const char PassName[]
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:439
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
void applyUpdatesPermissive(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Primary interface to the complete machine description for the target machine.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
Target-Independent Code Generator Pass Configuration Options.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
void setSuccessor(BasicBlock *NewSucc)
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i=0) const
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
iterator_range< use_iterator > uses()
Definition Value.h:382
PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
const ParentTy * getParent() const
Definition ilist_node.h:34
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const AArch64MCOptions & getCLOpts(const MCTargetOptions &Options)
@ BR
Control flow instructions. These all have token chains.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
FunctionPass * createX86LowerAMXIntrinsicsLegacyPass()
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI void setFittedBranchWeights(Instruction &I, ArrayRef< uint64_t > Weights, bool IsExpected, bool ElideAllZero=false)
Variant of setBranchWeights where the Weights will be fit first to uint32_t by shifting right.
#define N