xref: /llvm-project/llvm/lib/Target/X86/X86PreTileConfig.cpp (revision c72a751dabff4260dcc309e48008941d51b31d21)
1 //===-- X86PreTileConfig.cpp - Tile Register Pre-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 pre-config the shapes of AMX registers
10 /// AMX register needs to be configured before use. The shapes of AMX register
11 /// are encoded in the 1st and 2nd machine operand of AMX pseudo instructions.
12 ///
13 /// The instruction ldtilecfg is used to config the shapes. It must be reachable
14 /// for all variable shapes. ldtilecfg will be inserted more than once if we
15 /// cannot find a dominating point for all AMX instructions.
16 ///
17 /// The configure register is caller saved according to ABI. We need to insert
18 /// ldtilecfg again after the call instruction if callee clobbers any AMX
19 /// registers.
20 ///
21 /// This pass calculates all points that ldtilecfg need to be inserted to and
22 /// insert them. It reports error if the reachability conditions aren't met.
23 //
24 //===----------------------------------------------------------------------===//
25 
26 #include "X86.h"
27 #include "X86InstrBuilder.h"
28 #include "X86MachineFunctionInfo.h"
29 #include "X86RegisterInfo.h"
30 #include "X86Subtarget.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/CodeGen/TargetInstrInfo.h"
39 #include "llvm/CodeGen/TargetRegisterInfo.h"
40 #include "llvm/IR/Module.h"
41 #include "llvm/InitializePasses.h"
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "tile-pre-config"
46 
47 static void emitErrorMsg(MachineFunction &MF) {
48   LLVMContext &Context = MF.getFunction().getContext();
49   Context.emitError(
50       MF.getName() +
51       ": Failed to config tile register, please define the shape earlier");
52 }
53 
54 namespace {
55 
56 struct MIRef {
57   MachineInstr *MI = nullptr;
58   MachineBasicBlock *MBB = nullptr;
59   // A virtual position for instruction that will be inserted after MI.
60   size_t Pos = 0;
61   MIRef() = default;
62   MIRef(MachineBasicBlock *MBB) : MBB(MBB) {
63     for (auto I = MBB->begin(), E = MBB->end(); I != E && I->isPHI();
64          ++I, ++Pos)
65       MI = &*I;
66   }
67   MIRef(MachineInstr *MI)
68       : MI(MI), MBB(MI->getParent()),
69         Pos(std::distance(MBB->instr_begin(), ++MI->getIterator())) {}
70   MIRef(MachineInstr *MI, MachineBasicBlock *MBB)
71       : MI(MI), MBB(MBB),
72         Pos(std::distance(MBB->instr_begin(), ++MI->getIterator())) {}
73   MIRef(MachineInstr *MI, MachineBasicBlock *MBB, size_t Pos)
74       : MI(MI), MBB(MBB), Pos(Pos) {}
75   operator bool() const { return MBB != nullptr; }
76   bool operator==(const MIRef &RHS) const {
77     return MI == RHS.MI && MBB == RHS.MBB;
78   }
79   bool operator!=(const MIRef &RHS) const { return !(*this == RHS); }
80   bool operator<(const MIRef &RHS) const {
81     // Comparison between different BBs happens when inserting a MIRef into set.
82     // So we compare MBB first to make the insertion happy.
83     return MBB < RHS.MBB || (MBB == RHS.MBB && Pos < RHS.Pos);
84   }
85   bool operator>(const MIRef &RHS) const {
86     // Comparison between different BBs happens when inserting a MIRef into set.
87     // So we compare MBB first to make the insertion happy.
88     return MBB > RHS.MBB || (MBB == RHS.MBB && Pos > RHS.Pos);
89   }
90 };
91 
92 struct BBInfo {
93   MIRef FirstAMX;
94   MIRef LastCall;
95   bool HasAMXRegLiveIn = false;
96   bool TileCfgForbidden = false;
97   bool NeedTileCfgLiveIn = false;
98 };
99 
100 class X86PreTileConfig : public MachineFunctionPass {
101   MachineRegisterInfo *MRI = nullptr;
102   const MachineLoopInfo *MLI = nullptr;
103   SmallSet<MachineInstr *, 8> DefVisited;
104   DenseMap<MachineBasicBlock *, BBInfo> BBVisitedInfo;
105   DenseMap<MachineBasicBlock *, SmallVector<MIRef, 8>> ShapeBBs;
106 
107   /// Check if the callee will clobber AMX registers.
108   bool isDestructiveCall(MachineInstr &MI, BitVector UsableRegs) {
109     auto Iter = llvm::find_if(
110         MI.operands(), [](MachineOperand &MO) { return MO.isRegMask(); });
111     if (Iter == MI.operands_end())
112       return false;
113     UsableRegs.clearBitsInMask(Iter->getRegMask());
114     return !UsableRegs.none();
115   }
116 
117   /// Check if MI is AMX pseudo instruction.
118   bool isAMXInstruction(MachineInstr &MI) {
119     if (MI.isPHI() || MI.isDebugInstr() || MI.getNumOperands() < 3)
120       return false;
121 
122     // PTILESTOREDV is the only exception that doesn't def a AMX register.
123     if (MI.getOpcode() == X86::PTILESTOREDV)
124       return true;
125 
126     // We can simply check if it is AMX instruction by its def.
127     // But we should exclude old API which uses physical registers.
128     MachineOperand &MO = MI.getOperand(0);
129     if (!MO.isReg() || !MO.getReg().isVirtual())
130       return false;
131 
132     unsigned Shapes = 0;
133     if (MRI->getRegClass(MO.getReg())->getID() == X86::TILERegClassID)
134       Shapes = 1;
135     if (MRI->getRegClass(MO.getReg())->getID() == X86::TILEPAIRRegClassID)
136       Shapes = 2;
137     if (!Shapes)
138       return false;
139 
140     collectShapeInfo(MI, Shapes);
141     return true;
142   }
143 
144   /// Check if it is an edge from loop bottom to loop head.
145   bool isLoopBackEdge(MachineBasicBlock *Header, MachineBasicBlock *Bottom) {
146     if (!MLI->isLoopHeader(Header))
147       return false;
148     auto *ML = MLI->getLoopFor(Header);
149     if (ML->contains(Bottom) && ML->isLoopLatch(Bottom))
150       return true;
151 
152     return false;
153   }
154 
155   /// Collect the shape def information for later use.
156   void collectShapeInfo(MachineInstr &MI, unsigned Shapes);
157 
158   /// Try to hoist shapes definded below AMX instructions.
159   bool hoistShapesInBB(MachineBasicBlock *MBB, SmallVectorImpl<MIRef> &Shapes) {
160     MIRef &FirstAMX = BBVisitedInfo[MBB].FirstAMX;
161     auto FirstShapeBelowAMX = llvm::lower_bound(Shapes, FirstAMX);
162     auto InsertPoint = FirstAMX.MI->getIterator();
163     for (auto I = FirstShapeBelowAMX, E = Shapes.end(); I != E; ++I) {
164       // Do not hoist instructions that access memory.
165       if (I->MI->mayLoadOrStore())
166         return false;
167       for (auto &MO : I->MI->operands()) {
168         if (MO.isDef())
169           continue;
170         // Do not hoist instructions if the sources' def under AMX instruction.
171         // TODO: We can handle isMoveImmediate MI here.
172         if (MO.isReg() && MIRef(MRI->getVRegDef(MO.getReg())) > FirstAMX)
173           return false;
174         // TODO: Maybe need more checks here.
175       }
176       MBB->insert(InsertPoint, I->MI->removeFromParent());
177     }
178     // We only need to mark the last shape in the BB now.
179     Shapes.clear();
180     Shapes.push_back(MIRef(&*--InsertPoint, MBB));
181     return true;
182   }
183 
184 public:
185   X86PreTileConfig() : MachineFunctionPass(ID) {}
186 
187   /// Return the pass name.
188   StringRef getPassName() const override {
189     return "Tile Register Pre-configure";
190   }
191 
192   /// X86PreTileConfig analysis usage.
193   void getAnalysisUsage(AnalysisUsage &AU) const override {
194     AU.setPreservesAll();
195     AU.addRequired<MachineLoopInfoWrapperPass>();
196     MachineFunctionPass::getAnalysisUsage(AU);
197   }
198 
199   /// Clear MF related structures.
200   void releaseMemory() override {
201     ShapeBBs.clear();
202     DefVisited.clear();
203     BBVisitedInfo.clear();
204   }
205 
206   /// Perform ldtilecfg instructions inserting.
207   bool runOnMachineFunction(MachineFunction &MF) override;
208 
209   static char ID;
210 };
211 
212 } // end anonymous namespace
213 
214 char X86PreTileConfig::ID = 0;
215 
216 INITIALIZE_PASS_BEGIN(X86PreTileConfig, "tilepreconfig",
217                       "Tile Register Pre-configure", false, false)
218 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
219 INITIALIZE_PASS_END(X86PreTileConfig, "tilepreconfig",
220                     "Tile Register Pre-configure", false, false)
221 
222 void X86PreTileConfig::collectShapeInfo(MachineInstr &MI, unsigned Shapes) {
223   auto RecordShape = [&](MachineInstr *MI, MachineBasicBlock *MBB) {
224     MIRef MIR(MI, MBB);
225     auto I = llvm::lower_bound(ShapeBBs[MBB], MIR);
226     if (I == ShapeBBs[MBB].end() || *I != MIR)
227       ShapeBBs[MBB].insert(I, MIR);
228   };
229 
230   // All shapes have same row in multi-tile operand.
231   SmallVector<Register, 8> WorkList;
232   for (unsigned I = 1; I < Shapes + 2; ++I)
233     WorkList.push_back(MI.getOperand(I).getReg());
234   while (!WorkList.empty()) {
235     Register R = WorkList.pop_back_val();
236     MachineInstr *DefMI = MRI->getVRegDef(R);
237     assert(DefMI && "R must has one define instruction");
238     MachineBasicBlock *DefMBB = DefMI->getParent();
239     if (DefMI->isMoveImmediate() || !DefVisited.insert(DefMI).second)
240       continue;
241 
242     // This happens when column = 0 in multi-tile operand.
243     if (DefMI->getOpcode() == X86::COPY) {
244       MachineInstr *MI = MRI->getVRegDef(DefMI->getOperand(1).getReg());
245       if (MI && MI->isMoveImmediate())
246         continue;
247     }
248 
249     if (DefMI->isPHI()) {
250       for (unsigned I = 1; I < DefMI->getNumOperands(); I += 2)
251         if (isLoopBackEdge(DefMBB, DefMI->getOperand(I + 1).getMBB()))
252           RecordShape(DefMI, DefMBB); // In this case, PHI is also a shape def.
253         else
254           WorkList.push_back(DefMI->getOperand(I).getReg());
255     } else {
256       RecordShape(DefMI, DefMBB);
257     }
258   }
259 }
260 
261 bool X86PreTileConfig::runOnMachineFunction(MachineFunction &MF) {
262   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
263   // Early exit in the common case of non-AMX code.
264   if (X86FI->getAMXProgModel() != AMXProgModelEnum::ManagedRA)
265     return false;
266 
267   const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
268   const TargetInstrInfo *TII = ST.getInstrInfo();
269   const TargetRegisterInfo *TRI = ST.getRegisterInfo();
270   const TargetRegisterClass *RC = TRI->getRegClass(X86::TILERegClassID);
271 
272   BitVector AMXRegs(TRI->getNumRegs());
273   for (unsigned I = 0; I < RC->getNumRegs(); I++)
274     AMXRegs.set(X86::TMM0 + I);
275 
276   // Iterate MF to collect information.
277   MRI = &MF.getRegInfo();
278   MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
279   SmallSet<MIRef, 8> CfgNeedInsert;
280   SmallVector<MachineBasicBlock *, 8> CfgLiveInBBs;
281   for (auto &MBB : MF) {
282     size_t Pos = 0;
283     for (auto &MI : MBB) {
284       ++Pos;
285       if (isAMXInstruction(MI)) {
286         // If there's call before the AMX, we need to reload tile config.
287         if (BBVisitedInfo[&MBB].LastCall)
288           CfgNeedInsert.insert(BBVisitedInfo[&MBB].LastCall);
289         else // Otherwise, we need tile config to live in this BB.
290           BBVisitedInfo[&MBB].NeedTileCfgLiveIn = true;
291         // Always record the first AMX in case there's shape def after it.
292         if (!BBVisitedInfo[&MBB].FirstAMX)
293           BBVisitedInfo[&MBB].FirstAMX = MIRef(&MI, &MBB, Pos);
294       } else if (MI.isCall() && isDestructiveCall(MI, AMXRegs)) {
295         // Record the call only if the callee clobbers all AMX registers.
296         BBVisitedInfo[&MBB].LastCall = MIRef(&MI, &MBB, Pos);
297       }
298     }
299     if (BBVisitedInfo[&MBB].NeedTileCfgLiveIn) {
300       if (&MBB == &MF.front())
301         CfgNeedInsert.insert(MIRef(&MBB));
302       else
303         CfgLiveInBBs.push_back(&MBB);
304     }
305     if (BBVisitedInfo[&MBB].FirstAMX || BBVisitedInfo[&MBB].HasAMXRegLiveIn)
306       for (auto *Succ : MBB.successors())
307         if (!isLoopBackEdge(Succ, &MBB))
308           BBVisitedInfo[Succ].HasAMXRegLiveIn = true;
309   }
310 
311   // Update NeedTileCfgLiveIn for predecessors.
312   while (!CfgLiveInBBs.empty()) {
313     MachineBasicBlock *MBB = CfgLiveInBBs.pop_back_val();
314     for (auto *Pred : MBB->predecessors()) {
315       if (BBVisitedInfo[Pred].LastCall) {
316         CfgNeedInsert.insert(BBVisitedInfo[Pred].LastCall);
317       } else if (!BBVisitedInfo[Pred].NeedTileCfgLiveIn) {
318         BBVisitedInfo[Pred].NeedTileCfgLiveIn = true;
319         if (Pred == &MF.front())
320           CfgNeedInsert.insert(MIRef(Pred));
321         else
322           CfgLiveInBBs.push_back(Pred);
323       }
324     }
325   }
326 
327   // There's no AMX instruction if we didn't find a tile config live in point.
328   if (CfgNeedInsert.empty())
329     return false;
330 
331   // Avoid to insert ldtilecfg before any shape defs.
332   SmallVector<MachineBasicBlock *, 8> WorkList;
333   for (auto &I : ShapeBBs) {
334     // TODO: We can hoist shapes across BBs here.
335     if (BBVisitedInfo[I.first].HasAMXRegLiveIn) {
336       // We are not able to config tile registers since the shape to config
337       // is not defined yet. Emit error message and continue. The function
338       // would not config tile registers.
339       emitErrorMsg(MF);
340       return false;
341     }
342     if (BBVisitedInfo[I.first].FirstAMX &&
343         BBVisitedInfo[I.first].FirstAMX < I.second.back() &&
344         !hoistShapesInBB(I.first, I.second)) {
345       emitErrorMsg(MF);
346       return false;
347     }
348     WorkList.push_back(I.first);
349   }
350   while (!WorkList.empty()) {
351     MachineBasicBlock *MBB = WorkList.pop_back_val();
352     for (auto *Pred : MBB->predecessors()) {
353       if (!BBVisitedInfo[Pred].TileCfgForbidden && !isLoopBackEdge(MBB, Pred)) {
354         BBVisitedInfo[Pred].TileCfgForbidden = true;
355         WorkList.push_back(Pred);
356       }
357     }
358   }
359 
360   DebugLoc DL;
361   SmallSet<MIRef, 8> VisitedOrInserted;
362   int SS = MF.getFrameInfo().CreateStackObject(
363       ST.getTileConfigSize(), ST.getTileConfigAlignment(), false);
364 
365   // Try to insert for the tile config live in points.
366   for (const auto &I : CfgNeedInsert) {
367     SmallSet<MIRef, 8> InsertPoints;
368     SmallVector<MIRef, 8> WorkList({I});
369     while (!WorkList.empty()) {
370       MIRef I = WorkList.pop_back_val();
371       if (!VisitedOrInserted.count(I)) {
372         if (!BBVisitedInfo[I.MBB].TileCfgForbidden) {
373           // If the BB is all shapes reachable, stop sink and try to insert.
374           InsertPoints.insert(I);
375         } else {
376           // Avoid the BB to be multi visited.
377           VisitedOrInserted.insert(I);
378           // Sink the inserting point along the chain with NeedTileCfgLiveIn =
379           // true when MBB isn't all shapes reachable.
380           for (auto *Succ : I.MBB->successors())
381             if (BBVisitedInfo[Succ].NeedTileCfgLiveIn)
382               WorkList.push_back(MIRef(Succ));
383         }
384       }
385     }
386 
387     // A given point might be forked due to shape conditions are not met.
388     for (MIRef I : InsertPoints) {
389       // Make sure we insert ldtilecfg after the last shape def in MBB.
390       if (ShapeBBs.count(I.MBB) && I < ShapeBBs[I.MBB].back())
391         I = ShapeBBs[I.MBB].back();
392       // There're chances the MBB is sunk more than once. Record it to avoid
393       // multi insert.
394       if (VisitedOrInserted.insert(I).second) {
395         auto II = I.MI ? I.MI->getIterator() : I.MBB->instr_begin();
396         addFrameReference(BuildMI(*I.MBB, ++II, DL, TII->get(X86::PLDTILECFGV)),
397                           SS);
398       }
399     }
400   }
401 
402   // Zero stack slot.
403   MachineBasicBlock &MBB = MF.front();
404   MachineInstr *MI = &*MBB.begin();
405   if (ST.hasAVX512()) {
406     Register Zmm = MRI->createVirtualRegister(&X86::VR512RegClass);
407     BuildMI(MBB, MI, DL, TII->get(X86::AVX512_512_SET0), Zmm);
408     addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::VMOVUPSZmr)), SS)
409         .addReg(Zmm);
410   } else if (ST.hasAVX2()) {
411     Register Ymm = MRI->createVirtualRegister(&X86::VR256RegClass);
412     BuildMI(MBB, MI, DL, TII->get(X86::AVX_SET0), Ymm);
413     addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::VMOVUPSYmr)), SS)
414         .addReg(Ymm);
415     addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::VMOVUPSYmr)), SS, 32)
416         .addReg(Ymm);
417   } else {
418     assert(ST.hasSSE2() && "AMX should assume SSE2 enabled");
419     unsigned StoreOpc = ST.hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
420     Register Xmm = MRI->createVirtualRegister(&X86::VR128RegClass);
421     BuildMI(MBB, MI, DL, TII->get(X86::V_SET0), Xmm);
422     addFrameReference(BuildMI(MBB, MI, DL, TII->get(StoreOpc)), SS).addReg(Xmm);
423     addFrameReference(BuildMI(MBB, MI, DL, TII->get(StoreOpc)), SS, 16)
424         .addReg(Xmm);
425     addFrameReference(BuildMI(MBB, MI, DL, TII->get(StoreOpc)), SS, 32)
426         .addReg(Xmm);
427     addFrameReference(BuildMI(MBB, MI, DL, TII->get(StoreOpc)), SS, 48)
428         .addReg(Xmm);
429   }
430   // Fill in the palette first.
431   addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::MOV8mi)), SS).addImm(1);
432 
433   return true;
434 }
435 
436 FunctionPass *llvm::createX86PreTileConfigPass() {
437   return new X86PreTileConfig();
438 }
439