LLVM 24.0.0git
X86FastPreTileConfig.cpp
Go to the documentation of this file.
1//===-- X86FastPreTileConfig.cpp - Fast Tile Register Configure------------===//
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 preconfig the shape of physical tile registers
10/// It inserts ldtilecfg ahead of each group of tile registers. The algorithm
11/// walk each instruction of basic block in reverse order. All the tile
12/// registers that live out the basic block would be spilled and reloaded
13/// before its user. It also check the depenedency of the shape to ensure
14/// the shape is defined before ldtilecfg.
15//
16//===----------------------------------------------------------------------===//
17
18#include "X86.h"
19#include "X86InstrBuilder.h"
21#include "X86RegisterInfo.h"
22#include "X86Subtarget.h"
24#include "llvm/ADT/Statistic.h"
31#include "llvm/CodeGen/Passes.h"
34#include "llvm/IR/Analysis.h"
35#include "llvm/Support/Debug.h"
36
37using namespace llvm;
38
39#define DEBUG_TYPE "x86-fast-pre-tile-config"
40
41STATISTIC(NumStores, "Number of stores added");
42STATISTIC(NumLoads, "Number of loads added");
43
44namespace {
45
46class X86FastPreTileConfigImpl {
47public:
48 X86FastPreTileConfigImpl() : StackSlotForVirtReg(-1) {}
49 bool runOnMachineFunction(MachineFunction &MF);
50
51private:
52 MachineFunction *MF = nullptr;
53 const X86Subtarget *ST = nullptr;
54 const TargetInstrInfo *TII = nullptr;
55 MachineRegisterInfo *MRI = nullptr;
56 X86MachineFunctionInfo *X86FI = nullptr;
57 MachineFrameInfo *MFI = nullptr;
58 const TargetRegisterInfo *TRI = nullptr;
59 MachineBasicBlock *MBB = nullptr;
60 int CfgSS = -1;
61 struct PHIInfo {
62 Register Row;
63 Register Col;
64 Register StackAddr;
65 };
66 DenseMap<MachineInstr *, struct PHIInfo> VisitedPHIs;
67
68 /// Maps virtual regs to the frame index where these values are spilled.
69 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
70
71 /// Has a bit set for tile virtual register for which it was determined
72 /// that it is alive across blocks.
73 BitVector MayLiveAcrossBlocks;
74
75 int getStackSpaceFor(Register VirtReg);
76 void InitializeTileConfigStackSpace();
77 bool mayLiveOut(Register VirtReg, MachineInstr *CfgMI);
78 void spill(MachineBasicBlock::iterator Before, Register VirtReg, bool Kill);
79 void reload(MachineBasicBlock::iterator UseMI, Register VirtReg,
80 MachineOperand *RowMO, MachineOperand *ColMO);
81 void canonicalizePHIs(MachineBasicBlock &MBB);
82 void convertPHI(MachineBasicBlock *MBB, MachineInstr &PHI);
83 void convertPHIs(MachineBasicBlock &MBB);
84 bool configBasicBlock(MachineBasicBlock &MBB);
85};
86
87class X86FastPreTileConfigLegacy : public MachineFunctionPass {
88public:
89 X86FastPreTileConfigLegacy() : MachineFunctionPass(ID) {}
90
91 /// Return the pass name.
92 StringRef getPassName() const override {
93 return "Fast Tile Register Preconfigure";
94 }
95
96 /// Perform tile register configure.
97 bool runOnMachineFunction(MachineFunction &MFunc) override;
98
99 static char ID;
100};
101
102} // end anonymous namespace
103
104char X86FastPreTileConfigLegacy::ID = 0;
105
106INITIALIZE_PASS_BEGIN(X86FastPreTileConfigLegacy, DEBUG_TYPE,
107 "Fast Tile Register Preconfigure", false, false)
108INITIALIZE_PASS_END(X86FastPreTileConfigLegacy, DEBUG_TYPE,
109 "Fast Tile Register Preconfigure", false, false)
110
114 auto MBBEnd = MBB.end();
115 if (B == MBBEnd)
116 return true;
117
119 for (; &*I != A && &*I != B; ++I)
120 ;
121
122 return &*I == A;
123}
124
125/// This allocates space for the specified virtual register to be held on the
126/// stack.
127int X86FastPreTileConfigImpl::getStackSpaceFor(Register VirtReg) {
128 // Find the location Reg would belong...
129 int SS = StackSlotForVirtReg[VirtReg];
130 // Already has space allocated?
131 if (SS != -1)
132 return SS;
133
134 // Allocate a new stack object for this spill location...
135 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
136 unsigned Size = TRI->getSpillSize(RC);
137 Align Alignment = TRI->getSpillAlign(RC);
138 int FrameIdx = MFI->CreateSpillStackObject(Size, Alignment);
139
140 // Assign the slot.
141 StackSlotForVirtReg[VirtReg] = FrameIdx;
142 return FrameIdx;
143}
144
145/// Returns false if \p VirtReg is known to not live out of the current config.
146/// If \p VirtReg live out of the current MBB, it must live out of the current
147/// config
148bool X86FastPreTileConfigImpl::mayLiveOut(Register VirtReg,
149 MachineInstr *CfgMI) {
150 if (MayLiveAcrossBlocks.test(VirtReg.virtRegIndex()))
151 return true;
152
153 for (const MachineInstr &UseInst : MRI->use_nodbg_instructions(VirtReg)) {
154 if (UseInst.getParent() != MBB) {
155 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
156 return true;
157 }
158
159 // The use and def are in the same MBB. If the tile register is
160 // reconfigured, it is crobbered and we need to spill and reload
161 // tile register.
162 if (CfgMI) {
163 if (dominates(*MBB, *CfgMI, UseInst)) {
164 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
165 return true;
166 }
167 }
168 }
169
170 return false;
171}
172
173void X86FastPreTileConfigImpl::InitializeTileConfigStackSpace() {
174 MachineBasicBlock &MBB = MF->front();
175 MachineInstr *MI = &*MBB.getFirstNonPHI();
176 DebugLoc DL;
177 if (ST->hasAVX512()) {
178 Register Xmm = MRI->createVirtualRegister(&X86::VR128XRegClass);
179 BuildMI(MBB, MI, DL, TII->get(X86::AVX512_128_SET0), Xmm);
180 Register Zmm = MRI->createVirtualRegister(&X86::VR512RegClass);
181 BuildMI(MBB, MI, DL, TII->get(X86::SUBREG_TO_REG), Zmm)
182 .addReg(Xmm)
183 .addImm(X86::sub_xmm);
184 addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::VMOVUPSZmr)), CfgSS)
185 .addReg(Zmm);
186 } else if (ST->hasAVX2()) {
187 Register Xmm = MRI->createVirtualRegister(&X86::VR128RegClass);
188 BuildMI(MBB, MI, DL, TII->get(X86::V_SET0), Xmm);
189 Register Ymm = MRI->createVirtualRegister(&X86::VR256RegClass);
190 BuildMI(MBB, MI, DL, TII->get(X86::SUBREG_TO_REG), Ymm)
191 .addReg(Xmm)
192 .addImm(X86::sub_xmm);
193 addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::VMOVUPSYmr)), CfgSS)
194 .addReg(Ymm);
195 addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::VMOVUPSYmr)), CfgSS,
196 32)
197 .addReg(Ymm);
198 } else {
199 assert(ST->hasSSE2() && "AMX should assume SSE2 enabled");
200 unsigned StoreOpc = ST->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
201 Register Xmm = MRI->createVirtualRegister(&X86::VR128RegClass);
202 BuildMI(MBB, MI, DL, TII->get(X86::V_SET0), Xmm);
203 addFrameReference(BuildMI(MBB, MI, DL, TII->get(StoreOpc)), CfgSS)
204 .addReg(Xmm);
205 addFrameReference(BuildMI(MBB, MI, DL, TII->get(StoreOpc)), CfgSS, 16)
206 .addReg(Xmm);
207 addFrameReference(BuildMI(MBB, MI, DL, TII->get(StoreOpc)), CfgSS, 32)
208 .addReg(Xmm);
209 addFrameReference(BuildMI(MBB, MI, DL, TII->get(StoreOpc)), CfgSS, 48)
210 .addReg(Xmm);
211 }
212 // Fill in the palette first.
213 // Use Palette 2 for ACE v1, Palette 1 for AMX.
214 int PaletteId =
215 X86FI->getACEProgModel() == ACEProgModelEnum::ACE_ManagedRA ? 2 : 1;
216 addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::MOV8mi)), CfgSS)
217 .addImm(PaletteId);
218}
219
220/// Insert spill instruction for \p AssignedReg before \p Before.
221/// TODO: Update DBG_VALUEs with \p VirtReg operands with the stack slot.
222void X86FastPreTileConfigImpl::spill(MachineBasicBlock::iterator Before,
223 Register VirtReg, bool Kill) {
224 LLVM_DEBUG(dbgs() << "Spilling " << printReg(VirtReg, TRI) << " \n");
225 int FI = getStackSpaceFor(VirtReg);
226 LLVM_DEBUG(dbgs() << " to stack slot #" << FI << '\n');
227
228 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
229
230 // Palette 2 has no TILESTORED - use TILEMOVROW row-by-row through a scratch
231 // ZMM. Only palette 2 tiles, since palette 1 has its own shape.
232 if (X86FI->getACEProgModel() == ACEProgModelEnum::ACE_ManagedRA) {
233 // Before is MBB.end() when the tile def ends the block, so it can't be
234 // dereferenced for a debug location.
235 DebugLoc DL;
236
237 const unsigned NumRows = 16;
238 const unsigned RowSize = 64;
239
240 for (unsigned Row = 0; Row < NumRows; ++Row) {
241 // The read form writes the whole ZMM, so each row needs its own.
242 Register ScratchZMM = MRI->createVirtualRegister(&X86::VR512RegClass);
243
244 // tilemovrow $row, %tmm, %zmm
245 BuildMI(*MBB, Before, DL, TII->get(X86::TILEMOVROWrti), ScratchZMM)
246 .addReg(VirtReg)
247 .addImm(Row);
248
249 // vmovups %zmm, row*64(%sp)
250 MachineInstrBuilder MIB =
251 BuildMI(*MBB, Before, DL, TII->get(X86::VMOVUPSZmr));
252 addFrameReference(MIB, FI, Row * RowSize);
253 MIB.addReg(ScratchZMM);
254 }
255 } else {
256 // AMX: Use storeRegToStackSlot (TILESTORED)
257 // Don't need shape information for tile store, because it is adjacent to
258 // the tile def instruction.
259 TII->storeRegToStackSlot(*MBB, Before, VirtReg, Kill, FI, &RC, Register());
260 }
261 ++NumStores;
262
263 // TODO: update DBG_VALUEs
264}
265
266/// Insert reload instruction for \p PhysReg before \p Before.
267void X86FastPreTileConfigImpl::reload(MachineBasicBlock::iterator UseMI,
268 Register OrigReg, MachineOperand *RowMO,
269 MachineOperand *ColMO) {
270 int FI = getStackSpaceFor(OrigReg);
271 const TargetRegisterClass &RC = *MRI->getRegClass(OrigReg);
272 Register TileReg;
273 // Fold copy to tileload
274 // BB1:
275 // spill src to s
276 //
277 // BB2:
278 // t = copy src
279 // -->
280 // t = tileload (s)
281 if (UseMI->isCopy())
282 TileReg = UseMI->getOperand(0).getReg();
283 else
284 TileReg = MRI->createVirtualRegister(&RC);
285
286 // ACE configures palette 2, which has no TILELOADD - use TILEMOVROW
287 // row-by-row through a scratch ZMM.
288 if (X86FI->getACEProgModel() == ACEProgModelEnum::ACE_ManagedRA) {
289 const DebugLoc &DL = UseMI->getDebugLoc();
290
291 const unsigned NumRows = 16;
292 const unsigned RowSize = 64;
293
294 // Each row write returns the tile with one more row in place, so thread a
295 // register through the rows and end at TileReg. Row 0 has nothing to
296 // merge with.
297 Register PartialTile = MRI->createVirtualRegister(&RC);
298 BuildMI(*UseMI->getParent(), UseMI, DL, TII->get(X86::IMPLICIT_DEF),
299 PartialTile);
300
301 for (unsigned Row = 0; Row < NumRows; ++Row) {
302 Register ScratchZMM = MRI->createVirtualRegister(&X86::VR512RegClass);
303 Register Filled =
304 Row + 1 == NumRows ? TileReg : MRI->createVirtualRegister(&RC);
305
306 // vmovups row*64(%sp), %zmm
307 MachineInstrBuilder MIB = BuildMI(*UseMI->getParent(), UseMI, DL,
308 TII->get(X86::VMOVUPSZrm), ScratchZMM);
309 addFrameReference(MIB, FI, Row * RowSize);
310
311 // tilemovrow $row, %zmm, %tmm
312 BuildMI(*UseMI->getParent(), UseMI, DL, TII->get(X86::TILEMOVROWtri),
313 Filled)
314 .addReg(PartialTile)
315 .addReg(ScratchZMM)
316 .addImm(Row);
317 PartialTile = Filled;
318 }
319 } else {
320 // AMX: Use PTILELOADDV
321 // Can't use TII->loadRegFromStackSlot(), because we need the shape
322 // information for reload.
323 // tileloadd (%sp, %idx), %tmm
324 unsigned Opc = X86::PTILELOADDV;
325 Register StrideReg = MRI->createVirtualRegister(&X86::GR64_NOSPRegClass);
326 // FIXME: MBB is not the parent of UseMI.
327 MachineInstr *NewMI = BuildMI(*UseMI->getParent(), UseMI, DebugLoc(),
328 TII->get(X86::MOV64ri), StrideReg)
329 .addImm(64);
330 NewMI = addFrameReference(
331 BuildMI(*UseMI->getParent(), UseMI, DebugLoc(), TII->get(Opc), TileReg)
332 .addReg(RowMO->getReg())
333 .addReg(ColMO->getReg()),
334 FI);
335 MachineOperand &MO = NewMI->getOperand(5);
336 MO.setReg(StrideReg);
337 RowMO->setIsKill(false);
338 ColMO->setIsKill(false);
339 }
340
341 // Erase copy instruction after it is folded.
342 if (UseMI->isCopy()) {
344 } else {
345 // Replace the register in the user MI.
346 for (auto &MO : UseMI->operands()) {
347 if (MO.isReg() && MO.getReg() == OrigReg)
348 MO.setReg(TileReg);
349 }
350 }
351
352 ++NumLoads;
353 LLVM_DEBUG(dbgs() << "Reloading " << printReg(OrigReg, TRI) << " into "
354 << printReg(TileReg, TRI) << '\n');
355}
356
358 if (Reg.isVirtual() &&
359 (MRI->getRegClass(Reg)->getID() == X86::TILERegClassID)) {
360 return true;
361 }
362
363 if (Reg >= X86::TMM0 && Reg <= X86::TMM7)
364 return true;
365
366 return false;
367}
368
370 // The instruction must have 3 operands: tile def, row, col.
371 if (MI.isDebugInstr() || MI.getNumOperands() < 3 || !MI.isPseudo())
372 return false;
373 MachineOperand &MO = MI.getOperand(0);
374
375 if (!MO.isReg())
376 return false;
377
378 return isTileRegister(MRI, MO.getReg());
379}
380
382 MachineInstr *MI = MRI->getVRegDef(TileReg);
383 if (isTileDef(MRI, *MI)) {
384 MachineOperand *RowMO = &MI->getOperand(1);
385 MachineOperand *ColMO = &MI->getOperand(2);
386 return ShapeT(RowMO, ColMO, MRI);
387 } else if (MI->isCopy()) {
388 TileReg = MI->getOperand(1).getReg();
389 return getShape(MRI, TileReg);
390 }
391
392 // The def should not be PHI node, because we walk the MBB in reverse post
393 // order.
394 assert(MI->isPHI() && "Unexpected PHI when get shape.");
395 llvm_unreachable("Unexpected MI when get shape.");
396}
397
398// BB0:
399// spill t0 to s0
400// BB1:
401// spill t1 to s1
402//
403// BB2:
404// t = phi [t0, bb0] [t1, bb1]
405// -->
406// row = phi [r0, bb0] [r1, bb1]
407// col = phi [c0, bb0] [c1, bb1]
408// s = phi [s0, bb0] [s1, bb1]
409// t = tileload row, col, s
410// The new instruction is inserted at the end of the phi node. The order
411// of the original phi node is not ensured.
412void X86FastPreTileConfigImpl::convertPHI(MachineBasicBlock *MBB,
413 MachineInstr &PHI) {
414 // 1. Create instruction to get stack slot address of each incoming block.
415 // 2. Create PHI node for the stack address.
416 // 3. Create PHI node for shape. If one of the incoming shape is immediate
417 // use the immediate and delete the PHI node.
418 // 4. Create tileload instruction from the stack address.
419 Register StackAddrReg = MRI->createVirtualRegister(&X86::GR64_NOSPRegClass);
420 MachineInstrBuilder AddrPHI = BuildMI(*MBB, ++PHI.getIterator(), DebugLoc(),
421 TII->get(X86::PHI), StackAddrReg);
422 Register RowReg = MRI->createVirtualRegister(&X86::GR16RegClass);
423 MachineInstrBuilder RowPHI = BuildMI(*MBB, ++PHI.getIterator(), DebugLoc(),
424 TII->get(X86::PHI), RowReg);
425 Register ColReg = MRI->createVirtualRegister(&X86::GR16RegClass);
426 MachineInstrBuilder ColPHI = BuildMI(*MBB, ++PHI.getIterator(), DebugLoc(),
427 TII->get(X86::PHI), ColReg);
428 // Record the mapping of phi node and its row/column information.
429 VisitedPHIs[&PHI] = {RowReg, ColReg, StackAddrReg};
430
431 for (unsigned I = 1, E = PHI.getNumOperands(); I != E; I += 2) {
432 // Get the 2 incoming value of tile register and MBB.
433 Register InTileReg = PHI.getOperand(I).getReg();
434 // Mark it as liveout, so that it will be spilled when visit
435 // the incoming MBB. Otherwise since phi will be deleted, it
436 // would miss spill when visit incoming MBB.
437 MayLiveAcrossBlocks.set(InTileReg.virtRegIndex());
438 MachineBasicBlock *InMBB = PHI.getOperand(I + 1).getMBB();
439
440 MachineInstr *TileDefMI = MRI->getVRegDef(InTileReg);
442 if (TileDefMI->isPHI()) {
443 InsertPos = TileDefMI->getParent()->getFirstNonPHI();
444 if (auto It = VisitedPHIs.find(TileDefMI);
445 It != VisitedPHIs.end()) { // circular phi reference
446 // def t1
447 // / \
448 // def t2 t3 = phi(t1, t4) <--
449 // \ / |
450 // t4 = phi(t2, t3)-------------
451 //
452 // For each (row, column and stack address) append phi incoming value.
453 // Create r3 = phi(r1, r4)
454 // Create r4 = phi(r2, r3)
455 Register InRowReg = It->second.Row;
456 Register InColReg = It->second.Col;
457 Register InStackAddrReg = It->second.StackAddr;
458 RowPHI.addReg(InRowReg).addMBB(InMBB);
459 ColPHI.addReg(InColReg).addMBB(InMBB);
460 AddrPHI.addReg(InStackAddrReg).addMBB(InMBB);
461 continue;
462 } else {
463 // Recursively convert PHI to tileload
464 convertPHI(TileDefMI->getParent(), *TileDefMI);
465 // The PHI node is coverted to tileload instruction. Get the stack
466 // address from tileload operands.
467 MachineInstr *TileLoad = MRI->getVRegDef(InTileReg);
468 assert(TileLoad && (TileLoad->getOpcode() == X86::PTILELOADDV ||
469 TileLoad->getOpcode() == X86::ACE_TILERELOADV));
470 Register InRowReg = TileLoad->getOperand(1).getReg();
471 Register InColReg = TileLoad->getOperand(2).getReg();
472 Register InStackAddrReg = TileLoad->getOperand(3).getReg();
473 RowPHI.addReg(InRowReg).addMBB(InMBB);
474 ColPHI.addReg(InColReg).addMBB(InMBB);
475 AddrPHI.addReg(InStackAddrReg).addMBB(InMBB);
476 }
477 } else {
478 InsertPos = TileDefMI->getIterator();
479
480 // Fill the incoming operand of row/column phi instruction.
481 ShapeT Shape = getShape(MRI, InTileReg);
482 Shape.getRow()->setIsKill(false);
483 Shape.getCol()->setIsKill(false);
484 RowPHI.addReg(Shape.getRow()->getReg()).addMBB(InMBB);
485 ColPHI.addReg(Shape.getCol()->getReg()).addMBB(InMBB);
486
487 // The incoming tile register live out of its def BB, it would be spilled.
488 // Create MI to get the spill stack slot address for the tile register
489 int FI = getStackSpaceFor(InTileReg);
490 Register InStackAddrReg =
491 MRI->createVirtualRegister(&X86::GR64_NOSPRegClass);
492 addOffset(BuildMI(*TileDefMI->getParent(), InsertPos, DebugLoc(),
493 TII->get(X86::LEA64r), InStackAddrReg)
494 .addFrameIndex(FI),
495 0);
496 AddrPHI.addReg(InStackAddrReg).addMBB(InMBB);
497 }
498 }
499
501 Register TileReg = PHI.getOperand(0).getReg();
502 if (X86FI->getACEProgModel() == ACEProgModelEnum::ACE_ManagedRA) {
503 // Palette 2 has no TILELOADD, so leave the row moves to X86LowerTileCopy.
504 addDirectMem(BuildMI(*MBB, InsertPos, DebugLoc(),
505 TII->get(X86::ACE_TILERELOADV), TileReg)
506 .addReg(RowReg)
507 .addReg(ColReg),
508 StackAddrReg);
509 } else {
510 Register StrideReg = MRI->createVirtualRegister(&X86::GR64_NOSPRegClass);
511 BuildMI(*MBB, InsertPos, DebugLoc(), TII->get(X86::MOV64ri), StrideReg)
512 .addImm(64);
513 MachineInstr *NewMI =
514 addDirectMem(BuildMI(*MBB, InsertPos, DebugLoc(),
515 TII->get(X86::PTILELOADDV), TileReg)
516 .addReg(RowReg)
517 .addReg(ColReg),
518 StackAddrReg);
519 MachineOperand &MO = NewMI->getOperand(5);
520 MO.setReg(StrideReg);
521 }
522 PHI.eraseFromParent();
523 VisitedPHIs.erase(&PHI);
524}
525
527 MachineOperand &MO = MI.getOperand(0);
528 if (MO.isReg() && MO.getReg().isVirtual() && isTileRegister(MRI, MO.getReg()))
529 return true;
530 return false;
531}
532
533void X86FastPreTileConfigImpl::canonicalizePHIs(MachineBasicBlock &MBB) {
534 SmallVector<MachineInstr *, 8> PHIs;
535
536 for (MachineInstr &MI : MBB) {
537 if (!MI.isPHI())
538 break;
539 if (!isTileRegDef(MRI, MI))
540 continue;
541 PHIs.push_back(&MI);
542 }
543 // Canonicalize the phi node first. One tile phi may depeneds previous
544 // phi node. For below case, we need convert %t4.
545 //
546 // BB0:
547 // %t3 = phi (t1 BB1, t2 BB0)
548 // %t4 = phi (t5 BB1, t3 BB0)
549 // -->
550 // %t3 = phi (t1 BB1, t2 BB0)
551 // %t4 = phi (t5 BB1, t2 BB0)
552 //
553 while (!PHIs.empty()) {
554 MachineInstr *PHI = PHIs.pop_back_val();
555
556 // Find the operand that is incoming from the same MBB and the def
557 // is also phi node.
558 MachineOperand *InMO = nullptr;
559 MachineInstr *DefMI = nullptr;
560 for (unsigned I = 1, E = PHI->getNumOperands(); I != E; I += 2) {
561 Register InTileReg = PHI->getOperand(I).getReg();
562 MachineBasicBlock *InMBB = PHI->getOperand(I + 1).getMBB();
563 DefMI = MRI->getVRegDef(InTileReg);
564 if (InMBB != &MBB || !DefMI->isPHI())
565 continue;
566
567 InMO = &PHI->getOperand(I);
568 break;
569 }
570 // If can't find such operand, do nothing.
571 if (!InMO)
572 continue;
573
574 // Current phi node depends on previous phi node. Break the
575 // dependency.
576 Register DefTileReg;
577 for (unsigned I = 1, E = DefMI->getNumOperands(); I != E; I += 2) {
578 MachineBasicBlock *InMBB = PHI->getOperand(I + 1).getMBB();
579 if (InMBB != &MBB)
580 continue;
581 DefTileReg = DefMI->getOperand(I).getReg();
582 InMO->setReg(DefTileReg);
583 break;
584 }
585 }
586}
587
588void X86FastPreTileConfigImpl::convertPHIs(MachineBasicBlock &MBB) {
589 SmallVector<MachineInstr *, 8> PHIs;
590 for (MachineInstr &MI : MBB) {
591 if (!MI.isPHI())
592 break;
593 if (!isTileRegDef(MRI, MI))
594 continue;
595 PHIs.push_back(&MI);
596 }
597 while (!PHIs.empty()) {
598 MachineInstr *MI = PHIs.pop_back_val();
599 VisitedPHIs.clear();
600 convertPHI(&MBB, *MI);
601 }
602}
603
604// PreTileConfig should configure the tile registers based on basic
605// block.
606bool X86FastPreTileConfigImpl::configBasicBlock(MachineBasicBlock &MBB) {
607 this->MBB = &MBB;
608 bool Change = false;
609 MachineInstr *LastShapeMI = nullptr;
610 MachineInstr *LastTileCfg = nullptr;
611 bool HasUnconfigTile = false;
612 // ldtilecfg resets the BSR, so palette 2 configures at the head of the block.
613 bool IsACEManaged =
614 X86FI->getACEProgModel() == ACEProgModelEnum::ACE_ManagedRA;
615
616 auto Config = [&](MachineInstr &Before) {
617 if (CfgSS == -1)
618 CfgSS = MFI->CreateStackObject(ST->getTileConfigSize(),
619 ST->getTileConfigAlignment(), false);
620 LastTileCfg = addFrameReference(
621 BuildMI(MBB, Before, DebugLoc(), TII->get(X86::PLDTILECFGV)), CfgSS);
622 LastTileCfg->setImplicitPhysRegDefsDead();
623 LastShapeMI = nullptr;
624 Change = true;
625 };
626 auto HasTileOperand = [](MachineRegisterInfo *MRI, MachineInstr &MI) {
627 for (const MachineOperand &MO : MI.operands()) {
628 if (!MO.isReg())
629 continue;
630 Register Reg = MO.getReg();
632 return true;
633 }
634 return false;
635 };
636 for (MachineInstr &MI : reverse(MBB)) {
637 // We have transformed phi node before configuring BB.
638 if (MI.isPHI())
639 break;
640 // Don't collect the shape of used tile, the tile should be defined
641 // before the tile use. Spill and reload would happen if there is only
642 // tile use after ldtilecfg, so the shape can be collected from reload.
643 // Take below code for example. %t would be reloaded before tilestore
644 // call
645 // ....
646 // tilestore %r, %c, %t
647 // -->
648 // call
649 // ldtilecfg
650 // %t = tileload %r, %c
651 // tilestore %r, %c, %t
652 if (HasTileOperand(MRI, MI))
653 HasUnconfigTile = true;
654 // According to AMX ABI, all the tile registers including config register
655 // are volatile. Caller need to save/restore config register.
656 if (MI.isCall() && HasUnconfigTile) {
658 if (LastShapeMI && dominates(MBB, MI, LastShapeMI))
659 I = ++LastShapeMI->getIterator();
660 else {
661 // Call can overwrite registers like rax, ensure the tile config
662 // instruction is sinked closer to first instruction that uses tile.
663 auto UseIt = MI.getIterator();
664 while (UseIt != MBB.end()) {
665 if (HasTileOperand(MRI, *UseIt))
666 break;
667 ++UseIt;
668 }
669 I = UseIt;
670 }
671 Config(*I);
672 HasUnconfigTile = false;
673 continue;
674 }
675 if (!isTileDef(MRI, MI))
676 continue;
677 //
678 //---------------------------------------------------------------------
679 // Don't handle COPY instruction. If the src and dst of the COPY can be
680 // in the same config in below case, we just check the shape of t0.
681 // def row0
682 // def col0
683 // ldtilecfg
684 // t0 = tielzero(row0, col0)
685 // t1 = copy t0
686 // ...
687 // If the src and dst of the COPY can NOT be in the same config in below
688 // case. Reload would be generated befor the copy instruction.
689 // def row0
690 // def col0
691 // t0 = tielzero(row0, col0)
692 // spill t0
693 // ...
694 // def row1
695 // def col1
696 // ldtilecfg
697 // t1 = tilezero(row1, col1)
698 // reload t0
699 // t1 = copy t0
700 //---------------------------------------------------------------------
701 //
702 // If MI dominate the last shape def instruction, we need insert
703 // ldtilecfg after LastShapeMI now. The config doesn't include
704 // current MI.
705 // def row0
706 // def col0
707 // tilezero(row0, col0) <- MI
708 // def row1
709 // def col1
710 // ldtilecfg <- insert
711 // tilezero(row1, col1)
712 if (LastShapeMI && dominates(MBB, MI, LastShapeMI))
713 Config(*(++LastShapeMI->getIterator()));
714 MachineOperand *RowMO = &MI.getOperand(1);
715 MachineOperand *ColMO = &MI.getOperand(2);
716 MachineInstr *RowMI = MRI->getVRegDef(RowMO->getReg());
717 MachineInstr *ColMI = MRI->getVRegDef(ColMO->getReg());
718 // If the shape is defined in current MBB, check the domination.
719 // FIXME how about loop?
720 if (!IsACEManaged) {
721 if (RowMI->getParent() == &MBB) {
722 if (!LastShapeMI)
723 LastShapeMI = RowMI;
724 else if (dominates(MBB, LastShapeMI, RowMI))
725 LastShapeMI = RowMI;
726 }
727 if (ColMI->getParent() == &MBB) {
728 if (!LastShapeMI)
729 LastShapeMI = ColMI;
730 else if (dominates(MBB, LastShapeMI, ColMI))
731 LastShapeMI = ColMI;
732 }
733 }
734
735 // If there is user live out of the tilecfg, spill it and reload in
736 // before the user.
737 Register TileReg = MI.getOperand(0).getReg();
738 if (mayLiveOut(TileReg, LastTileCfg))
739 spill(++MI.getIterator(), TileReg, false);
740 // reload() rewrites or erases UseMI.
741 for (MachineInstr &UseMI :
743 if (UseMI.getParent() == &MBB) {
744 // check user should not across ldtilecfg
745 if (!LastTileCfg || !dominates(MBB, LastTileCfg, UseMI))
746 continue;
747 // reload befor UseMI
748 reload(UseMI.getIterator(), TileReg, RowMO, ColMO);
749 } else {
750 // Don't reload for phi instruction, we handle phi reload separately.
751 // TODO: merge the reload for the same user MBB.
752 if (!UseMI.isPHI())
753 reload(UseMI.getIterator(), TileReg, RowMO, ColMO);
754 }
755 }
756 }
757
758 // Configure tile registers at the head of the MBB
759 if (HasUnconfigTile) {
760 MachineInstr *Before;
761 if (LastShapeMI == nullptr || LastShapeMI->isPHI())
762 Before = &*MBB.getFirstNonPHI();
763 else
764 Before = &*(++LastShapeMI->getIterator());
765
766 Config(*Before);
767 }
768
769 return Change;
770}
771
772bool X86FastPreTileConfigImpl::runOnMachineFunction(MachineFunction &MFunc) {
773 X86FI = MFunc.getInfo<X86MachineFunctionInfo>();
774 // Early exit in the common case of non-AMX/ACE code.
775 if (X86FI->getAMXProgModel() != AMXProgModelEnum::ManagedRA &&
776 X86FI->getACEProgModel() != ACEProgModelEnum::ACE_ManagedRA)
777 return false;
778
779 MF = &MFunc;
780 MRI = &MFunc.getRegInfo();
781 ST = &MFunc.getSubtarget<X86Subtarget>();
782 TII = ST->getInstrInfo();
783 MFI = &MFunc.getFrameInfo();
784 TRI = ST->getRegisterInfo();
785 CfgSS = -1;
786
787 unsigned NumVirtRegs = MRI->getNumVirtRegs();
788
789 StackSlotForVirtReg.resize(NumVirtRegs);
790 MayLiveAcrossBlocks.clear();
791 // We will create register during config. *3 is to make sure
792 // the virtual register number doesn't exceed the size of
793 // the bit vector.
794 MayLiveAcrossBlocks.resize(NumVirtRegs * 3);
795 bool Change = false;
796 assert(MRI->isSSA());
797
798 // Canonicalize the phi node first.
799 for (MachineBasicBlock &MBB : MFunc)
800 canonicalizePHIs(MBB);
801
802 // Loop over all of the basic blocks in reverse post order and insert
803 // ldtilecfg for tile registers. The reserse post order is to facilitate
804 // PHI node convert.
805 ReversePostOrderTraversal<MachineFunction *> RPOT(MF);
806 for (MachineBasicBlock *MBB : RPOT) {
807 convertPHIs(*MBB);
808 Change |= configBasicBlock(*MBB);
809 }
810
811 if (Change)
812 InitializeTileConfigStackSpace();
813
814 StackSlotForVirtReg.clear();
815 return Change;
816}
817
819 return new X86FastPreTileConfigLegacy();
820}
821
822bool X86FastPreTileConfigLegacy::runOnMachineFunction(MachineFunction &MF) {
823 X86FastPreTileConfigImpl Impl;
824 return Impl.runOnMachineFunction(MF);
825}
826
827PreservedAnalyses
830 X86FastPreTileConfigImpl Impl;
831 bool Changed = Impl.runOnMachineFunction(MF);
834}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
Rewrite undef for PHI
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
IRTranslator LLVM IR MI
unsigned Opc
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#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 builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
MachineRegisterInfo & MRI
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
static bool isTileRegDef(MachineRegisterInfo *MRI, MachineInstr &MI)
static ShapeT getShape(MachineRegisterInfo *MRI, Register TileReg)
static bool isTileDef(MachineRegisterInfo *MRI, MachineInstr &MI)
static bool isTileRegister(MachineRegisterInfo *MRI, Register Reg)
void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:483
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:356
void clear()
Removes all bits from the bitvector.
Definition BitVector.h:350
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
MachineInstrBundleIterator< const MachineInstr > const_iterator
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
LLVM_ABI int CreateSpillStackObject(uint64_t Size, Align Alignment, TargetStackID::Value StackID=TargetStackID::Default)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool isCopy() const
const MachineBasicBlock * getParent() const
unsigned getNumOperands() const
Retuns the total number of operands.
mop_range operands()
void setImplicitPhysRegDefsDead()
Mark the implicit physreg defs named by the instruction description as dead.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
unsigned virtRegIndex() const
Convert a virtual register number to a 0-based index.
Definition Register.h:87
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
MachineOperand * getRow() const
MachineOperand * getCol() const
void push_back(const T &Elt)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
ACEProgModelEnum getACEProgModel() const
AMXProgModelEnum getAMXProgModel() const
unsigned getTileConfigSize() const
Align getTileConfigAlignment() const
const X86InstrInfo * getInstrInfo() const override
bool hasAVX512() const
bool hasSSE2() const
const X86RegisterInfo * getRegisterInfo() const override
bool hasAVX() const
bool hasAVX2() const
self_iterator getIterator()
Definition ilist_node.h:123
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Kill
The last use of a register.
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
static const MachineInstrBuilder & addFrameReference(const MachineInstrBuilder &MIB, int FI, int Offset=0, bool mem=true)
addFrameReference - This function is used to add a reference to the base of an abstract object on the...
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
static const MachineInstrBuilder & addOffset(const MachineInstrBuilder &MIB, int Offset)
FunctionPass * createX86FastPreTileConfigLegacyPass()
static const MachineInstrBuilder & addDirectMem(const MachineInstrBuilder &MIB, Register Reg)
addDirectMem - This function is used to add a direct memory reference to the current instruction – th...
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58