LLVM 24.0.0git
X86LowerTileCopy.cpp
Go to the documentation of this file.
1//===-- X86LowerTileCopy.cpp - Expand Tile Copy Instructions---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the pass which lower AMX tile copy instructions. Since
10// there is no tile copy instruction, we need store tile register to stack
11// and load from stack to another tile register. We need extra GR to hold
12// the stride, and we need stack slot to hold the tile data register.
13// We would run this pass after copy propagation, so that we don't miss copy
14// optimization. And we would run this pass before prolog/epilog insertion,
15// so that we can allocate stack slot.
16//
17//===----------------------------------------------------------------------===//
18
19#include "X86.h"
20#include "X86InstrBuilder.h"
21#include "X86InstrInfo.h"
23#include "X86Subtarget.h"
33#include "llvm/CodeGen/Passes.h"
34#include "llvm/IR/DebugLoc.h"
35
36using namespace llvm;
37
38#define DEBUG_TYPE "x86-lower-tile-copy"
39
40// ACE has no TILELOADD/TILESTORED, so a tile moves to and from memory one row
41// at a time through a scratch ZMM. Each tile is 16 rows of 64 bytes (1KB).
42static const unsigned ACENumTileRows = 16;
43static const unsigned ACETileRowSize = 64;
44
45/// Emit the ACE tile spill sequence, storing \p SrcReg to \p TileSS.
48 const X86InstrInfo *TII, Register SrcReg,
49 bool SrcKill, int TileSS, Register ScratchZMM) {
50 const DebugLoc &DL = MI->getDebugLoc();
51 for (unsigned Row = 0; Row < ACENumTileRows; ++Row) {
52 // tilemovrow $row, %tmm, %zmm
53 // Only kill src on the last row read.
54 bool KillSrcNow = (Row == ACENumTileRows - 1) && SrcKill;
55 BuildMI(MBB, MI, DL, TII->get(X86::TILEMOVROWrti), ScratchZMM)
56 .addReg(SrcReg, getKillRegState(KillSrcNow))
57 .addImm(Row);
58
59 // vmovups %zmm, row*64(%sp)
60 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII->get(X86::VMOVUPSZmr));
61 addFrameReference(MIB, TileSS, Row * ACETileRowSize);
62 MIB.addReg(ScratchZMM, RegState::Kill);
63 }
64}
65
66/// Add tile row \p Row's address to \p MIB from \p MI's operands at \p MemIdx.
68 unsigned MemIdx, unsigned Row) {
69 for (unsigned I = 0; I != X86::AddrNumOperands; ++I) {
70 // Every row reads the address, so none of them may kill it.
71 MachineOperand MO = MI.getOperand(MemIdx + I);
72 if (MO.isReg())
73 MO.setIsKill(false);
74 if (I == X86::AddrDisp)
75 MIB.addImm(MO.getImm() + Row * ACETileRowSize);
76 else
77 MIB.add(MO);
78 }
79}
80
81/// Reload \p DstReg through \p ScratchZMM, a row at a time from \p AddRowAddr.
84 const X86InstrInfo *TII, Register DstReg, Register ScratchZMM,
85 function_ref<void(MachineInstrBuilder &, unsigned)> AddRowAddr) {
86 const DebugLoc &DL = MI->getDebugLoc();
87 for (unsigned Row = 0; Row < ACENumTileRows; ++Row) {
88 // vmovups row*64(%addr), %zmm
90 BuildMI(MBB, MI, DL, TII->get(X86::VMOVUPSZrm), ScratchZMM);
91 AddRowAddr(MIB, Row);
92
93 // tilemovrow $row, %zmm, %tmm
94 // Each write merges into the tile; row 0 has nothing to merge with.
95 BuildMI(MBB, MI, DL, TII->get(X86::TILEMOVROWtri), DstReg)
96 .addReg(DstReg, Row == 0 ? RegState::Undef : RegState::NoFlags)
97 .addReg(ScratchZMM, RegState::Kill)
98 .addImm(Row);
99 }
100}
101
102/// Pick a ZMM that is dead here, or NoRegister if none is available.
104 const TargetRegisterInfo *TRI,
105 const LiveRegUnits &UsedRegs) {
106 BitVector VR512Regs =
107 TRI->getAllocatableSet(MF, TRI->getRegClass(X86::VR512RegClassID));
108 for (auto RegT : VR512Regs.set_bits())
109 if (UsedRegs.available(RegT))
110 return RegT;
111 return X86::NoRegister;
112}
113
114namespace {
115
116class X86LowerTileCopyLegacy : public MachineFunctionPass {
117public:
118 static char ID;
119
120 X86LowerTileCopyLegacy() : MachineFunctionPass(ID) {}
121
122 void getAnalysisUsage(AnalysisUsage &AU) const override;
123
124 bool runOnMachineFunction(MachineFunction &MF) override;
125
126 StringRef getPassName() const override { return "X86 Lower Tile Copy"; }
127};
128
129} // namespace
130
131char X86LowerTileCopyLegacy::ID = 0;
132
133INITIALIZE_PASS_BEGIN(X86LowerTileCopyLegacy, DEBUG_TYPE, "Tile Copy Lowering",
134 false, false)
135INITIALIZE_PASS_END(X86LowerTileCopyLegacy, DEBUG_TYPE, "Tile Copy Lowering",
137
138void X86LowerTileCopyLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
139 AU.setPreservesAll();
141}
142
144 return new X86LowerTileCopyLegacy();
145}
146
149 if (FuncInfo->getAMXProgModel() != AMXProgModelEnum::ManagedRA &&
151 return false;
152
153 const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
154 assert((ST.hasAMXTILE() || ST.hasACEV1()) &&
155 "Only supported on AMX-TILE or ACE v1 targets");
156
157 const X86InstrInfo *TII = ST.getInstrInfo();
158 const TargetRegisterInfo *TRI = ST.getRegisterInfo();
159 BitVector GR64Regs =
160 TRI->getAllocatableSet(MF, TRI->getRegClass(X86::GR64RegClassID));
161 bool Changed = false;
162
163 for (MachineBasicBlock &MBB : MF) {
164 LiveRegUnits UsedRegs(*TRI);
165 UsedRegs.addLiveOuts(MBB);
167 if (MI.isDebugInstr())
168 continue;
169 UsedRegs.stepBackward(MI);
170
171 // Expand the tile spill/reload pseudos inserted by the register
172 // allocator. getLoadStoreRegOpcode is the only place these are created,
173 // and it only does so for palette 2 tiles.
174 unsigned Opcode = MI.getOpcode();
175 if (Opcode == X86::ACE_TILESPILL || Opcode == X86::ACE_TILERELOAD ||
176 Opcode == X86::ACE_TILERELOADV) {
178 "ACE tile spill pseudo outside an ACE function");
179 bool IsSpill = Opcode == X86::ACE_TILESPILL;
180 // Spill is (mem, tile); reloads (tile, [row, col,] mem).
181 MachineOperand &TileMO =
182 MI.getOperand(IsSpill ? X86::AddrNumOperands : 0);
183 unsigned MemIdx = 0;
184 if (Opcode == X86::ACE_TILERELOAD)
185 MemIdx = 1;
186 else if (Opcode == X86::ACE_TILERELOADV)
187 MemIdx = 3;
188 const DebugLoc &DL = MI.getDebugLoc();
189
190 Register ScratchZMM = findScratchZMM(MF, TRI, UsedRegs);
191 int ZmmSS = -1;
192 if (!ScratchZMM) {
193 // No available register? Save ZMM0 and reload it after use.
194 ScratchZMM = X86::ZMM0;
195 ZmmSS = MF.getFrameInfo().CreateSpillStackObject(64, Align(64));
196 addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::VMOVUPSZmr)),
197 ZmmSS)
198 .addReg(X86::ZMM0);
199 }
200
201 if (IsSpill)
202 emitACETileSpill(MBB, MI, TII, TileMO.getReg(), TileMO.isKill(),
203 MI.getOperand(MemIdx + X86::AddrBaseReg).getIndex(),
204 ScratchZMM);
205 else
206 emitACETileReload(MBB, MI, TII, TileMO.getReg(), ScratchZMM,
207 [&](MachineInstrBuilder &MIB, unsigned Row) {
208 addACETileRowAddr(MIB, MI, MemIdx, Row);
209 });
210
211 if (ZmmSS != -1)
213 BuildMI(MBB, MI, DL, TII->get(X86::VMOVUPSZrm), X86::ZMM0),
214 ZmmSS);
215
216 MI.eraseFromParent();
217 Changed = true;
218 continue;
219 }
220
221 if (!MI.isCopy())
222 continue;
223 MachineOperand &DstMO = MI.getOperand(0);
224 MachineOperand &SrcMO = MI.getOperand(1);
225 Register SrcReg = SrcMO.getReg();
226 Register DstReg = DstMO.getReg();
227 if (!X86::TILERegClass.contains(DstReg, SrcReg))
228 continue;
229
230 // Allocate stack slot for tile register (1KB for ACE, same for AMX)
231 unsigned Size = TRI->getSpillSize(X86::TILERegClass);
232 Align Alignment = TRI->getSpillAlign(X86::TILERegClass);
233 int TileSS = MF.getFrameInfo().CreateSpillStackObject(Size, Alignment);
234
235 const DebugLoc &DL = MI.getDebugLoc();
236
237 // Palette 2 has no TILELOADD/TILESTORED, so copy the tile row-by-row
238 // through a scratch ZMM.
240 Register ScratchZMM = findScratchZMM(MF, TRI, UsedRegs);
241 int ZmmSS = -1;
242 if (!ScratchZMM) {
243 // No available register? Save ZMM0 and reload it after use.
244 ScratchZMM = X86::ZMM0;
245 ZmmSS = MF.getFrameInfo().CreateSpillStackObject(64, Align(64));
246 addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::VMOVUPSZmr)),
247 ZmmSS)
248 .addReg(X86::ZMM0);
249 }
250
251 emitACETileSpill(MBB, MI, TII, SrcReg, SrcMO.isKill(), TileSS,
252 ScratchZMM);
253 emitACETileReload(MBB, MI, TII, DstReg, ScratchZMM,
254 [&](MachineInstrBuilder &MIB, unsigned Row) {
255 addFrameReference(MIB, TileSS,
256 Row * ACETileRowSize);
257 });
258
259 if (ZmmSS != -1)
261 BuildMI(MBB, MI, DL, TII->get(X86::VMOVUPSZrm), X86::ZMM0),
262 ZmmSS);
263 } else {
264 // AMX: Use TILESTORED/TILELOADD (original code)
265 int StrideSS = 0;
266
267 // Pick a killed register to avoid a save/reload.
268 Register GR64Cand = X86::NoRegister;
269 for (auto RegT : GR64Regs.set_bits()) {
270 if (UsedRegs.available(RegT)) {
271 GR64Cand = RegT;
272 break;
273 }
274 }
275
276 if (GR64Cand) {
277 // mov 64 %reg
278 BuildMI(MBB, MI, DL, TII->get(X86::MOV64ri), GR64Cand).addImm(64);
279 } else {
280 // No available register? Save RAX and reload it after use.
281
282 // Allocate stack slot for stride register
283 Size = TRI->getSpillSize(X86::GR64RegClass);
284 Alignment = TRI->getSpillAlign(X86::GR64RegClass);
285 StrideSS = MF.getFrameInfo().CreateSpillStackObject(Size, Alignment);
286
287 // mov %reg (%sp)
288 addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::MOV64mr)),
289 StrideSS)
290 .addReg(X86::RAX);
291 // mov 64 %reg
292 BuildMI(MBB, MI, DL, TII->get(X86::MOV64ri), X86::RAX).addImm(64);
293 }
294 // tilestored %tmm, (%sp, %idx)
295#define GET_EGPR_IF_ENABLED(OPC) (ST.hasEGPR() ? OPC##_EVEX : OPC)
296 unsigned Opc = GET_EGPR_IF_ENABLED(X86::TILESTORED);
297 MachineInstr *NewMI =
298 addFrameReference(BuildMI(MBB, MI, DL, TII->get(Opc)), TileSS)
299 .addReg(SrcReg, getKillRegState(SrcMO.isKill()));
301 MO->setReg(GR64Cand ? GR64Cand : X86::RAX);
302 // tileloadd (%sp, %idx), %tmm
303 Opc = GET_EGPR_IF_ENABLED(X86::TILELOADD);
304#undef GET_EGPR_IF_ENABLED
305 NewMI = addFrameReference(BuildMI(MBB, MI, DL, TII->get(Opc), DstReg),
306 TileSS);
307 MO = &NewMI->getOperand(1 + X86::AddrIndexReg);
308 MO->setReg(GR64Cand ? GR64Cand : X86::RAX);
309 MO->setIsKill(true);
310 if (!GR64Cand) {
311 // restore %rax
312 // mov (%sp) %rax
314 BuildMI(MBB, MI, DL, TII->get(X86::MOV64rm), X86::RAX), StrideSS);
315 }
316 }
317
318 MI.eraseFromParent();
319 Changed = true;
320 }
321 }
322 return Changed;
323}
324
325bool X86LowerTileCopyLegacy::runOnMachineFunction(MachineFunction &MF) {
326 return lowerTileCopy(MF);
327}
328
329PreservedAnalyses
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define DEBUG_TYPE
IRTranslator LLVM IR MI
A set of register units.
unsigned Opc
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
#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
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
static constexpr unsigned ACENumTileRows
static Register findScratchZMM(MachineFunction &MF, const TargetRegisterInfo *TRI, const LiveRegUnits &UsedRegs)
Pick a ZMM that is dead here, or NoRegister if none is available.
#define GET_EGPR_IF_ENABLED(OPC)
static bool lowerTileCopy(MachineFunction &MF)
static void addACETileRowAddr(MachineInstrBuilder &MIB, MachineInstr &MI, unsigned MemIdx, unsigned Row)
Add tile row Row's address to MIB from MI's operands at MemIdx.
static const unsigned ACETileRowSize
static void emitACETileReload(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const X86InstrInfo *TII, Register DstReg, Register ScratchZMM, function_ref< void(MachineInstrBuilder &, unsigned)> AddRowAddr)
Reload DstReg through ScratchZMM, a row at a time from AddRowAddr.
static void emitACETileSpill(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const X86InstrInfo *TII, Register SrcReg, bool SrcKill, int TileSS, Register ScratchZMM)
Emit the ACE tile spill sequence, storing SrcReg to TileSS.
Represent the analysis usage information of a pass.
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:160
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
A debug info location.
Definition DebugLoc.h:126
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
A set of register units used to track register liveness.
bool available(MCRegister Reg) const
Returns true if no part of physical register Reg is live.
LLVM_ABI void stepBackward(const MachineInstr &MI)
Updates liveness when stepping backwards over the instruction MI.
LLVM_ABI void addLiveOuts(const MachineBasicBlock &MBB)
Adds registers living out of block MBB.
MachineInstrBundleIterator< MachineInstr > iterator
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...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
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.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
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 & add(const MachineOperand &MO) const
Representation of each machine instruction.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
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.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
Wrapper class representing virtual and physical registers.
Definition Register.h:20
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
X86MachineFunctionInfo - This class is derived from MachineFunction and contains private X86 target-s...
ACEProgModelEnum getACEProgModel() const
AMXProgModelEnum getAMXProgModel() const
An efficient, type-erasing, non-owning reference to a callable.
@ AddrNumOperands
Definition X86BaseInfo.h:37
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.
@ Undef
Value of the register doesn't matter.
@ NoFlags
No Specific Flags.
constexpr RegState getKillRegState(bool B)
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.
FunctionPass * createX86LowerTileCopyLegacyPass()
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39