LLVM 22.0.0git
X86CompressEVEX.cpp
Go to the documentation of this file.
1//===- X86CompressEVEX.cpp ------------------------------------------------===//
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 pass compresses instructions from EVEX space to legacy/VEX/EVEX space
10// when possible in order to reduce code size or facilitate HW decoding.
11//
12// Possible compression:
13// a. AVX512 instruction (EVEX) -> AVX instruction (VEX)
14// b. Promoted instruction (EVEX) -> pre-promotion instruction (legacy/VEX)
15// c. NDD (EVEX) -> non-NDD (legacy)
16// d. NF_ND (EVEX) -> NF (EVEX)
17// e. NonNF (EVEX) -> NF (EVEX)
18// f. SETZUCCm (EVEX) -> SETCCm (legacy)
19//
20// Compression a, b and c can always reduce code size, with some exceptions
21// such as promoted 16-bit CRC32 which is as long as the legacy version.
22//
23// legacy:
24// crc32w %si, %eax ## encoding: [0x66,0xf2,0x0f,0x38,0xf1,0xc6]
25// promoted:
26// crc32w %si, %eax ## encoding: [0x62,0xf4,0x7d,0x08,0xf1,0xc6]
27//
28// From performance perspective, these should be same (same uops and same EXE
29// ports). From a FMV perspective, an older legacy encoding is preferred b/c it
30// can execute in more places (broader HW install base). So we will still do
31// the compression.
32//
33// Compression d can help hardware decode (HW may skip reading the NDD
34// register) although the instruction length remains unchanged.
35//
36// Compression e can help hardware skip updating EFLAGS although the instruction
37// length remains unchanged.
38//===----------------------------------------------------------------------===//
39
41#include "X86.h"
42#include "X86InstrInfo.h"
43#include "X86Subtarget.h"
44#include "llvm/ADT/StringRef.h"
51#include "llvm/IR/Analysis.h"
52#include "llvm/MC/MCInstrDesc.h"
53#include "llvm/Pass.h"
54#include <atomic>
55#include <cassert>
56#include <cstdint>
57
58using namespace llvm;
59
60#define COMP_EVEX_DESC "Compressing EVEX instrs when possible"
61#define COMP_EVEX_NAME "x86-compress-evex"
62
63#define DEBUG_TYPE COMP_EVEX_NAME
64
66
67namespace {
68// Including the generated EVEX compression tables.
69#define GET_X86_COMPRESS_EVEX_TABLE
70#include "X86GenInstrMapping.inc"
71
72class CompressEVEXLegacy : public MachineFunctionPass {
73public:
74 static char ID;
75 CompressEVEXLegacy() : MachineFunctionPass(ID) {}
76 StringRef getPassName() const override { return COMP_EVEX_DESC; }
77
78 bool runOnMachineFunction(MachineFunction &MF) override;
79
80 // This pass runs after regalloc and doesn't support VReg operands.
81 MachineFunctionProperties getRequiredProperties() const override {
82 return MachineFunctionProperties().setNoVRegs();
83 }
84};
85
86} // end anonymous namespace
87
88char CompressEVEXLegacy::ID = 0;
89
91 auto isHiRegIdx = [](MCRegister Reg) {
92 // Check for XMM register with indexes between 16 - 31.
93 if (Reg >= X86::XMM16 && Reg <= X86::XMM31)
94 return true;
95 // Check for YMM register with indexes between 16 - 31.
96 if (Reg >= X86::YMM16 && Reg <= X86::YMM31)
97 return true;
98 // Check for GPR with indexes between 16 - 31.
100 return true;
101 return false;
102 };
103
104 // Check that operands are not ZMM regs or
105 // XMM/YMM regs with hi indexes between 16 - 31.
106 for (const MachineOperand &MO : MI.explicit_operands()) {
107 if (!MO.isReg())
108 continue;
109
110 MCRegister Reg = MO.getReg().asMCReg();
112 "ZMM instructions should not be in the EVEX->VEX tables");
113 if (isHiRegIdx(Reg))
114 return true;
115 }
116
117 return false;
118}
119
120// Do any custom cleanup needed to finalize the conversion.
121static bool performCustomAdjustments(MachineInstr &MI, unsigned NewOpc) {
122 (void)NewOpc;
123 unsigned Opc = MI.getOpcode();
124 switch (Opc) {
125 case X86::VALIGNDZ128rri:
126 case X86::VALIGNDZ128rmi:
127 case X86::VALIGNQZ128rri:
128 case X86::VALIGNQZ128rmi: {
129 assert((NewOpc == X86::VPALIGNRrri || NewOpc == X86::VPALIGNRrmi) &&
130 "Unexpected new opcode!");
131 unsigned Scale =
132 (Opc == X86::VALIGNQZ128rri || Opc == X86::VALIGNQZ128rmi) ? 8 : 4;
133 MachineOperand &Imm = MI.getOperand(MI.getNumExplicitOperands() - 1);
134 Imm.setImm(Imm.getImm() * Scale);
135 break;
136 }
137 case X86::VSHUFF32X4Z256rmi:
138 case X86::VSHUFF32X4Z256rri:
139 case X86::VSHUFF64X2Z256rmi:
140 case X86::VSHUFF64X2Z256rri:
141 case X86::VSHUFI32X4Z256rmi:
142 case X86::VSHUFI32X4Z256rri:
143 case X86::VSHUFI64X2Z256rmi:
144 case X86::VSHUFI64X2Z256rri: {
145 assert((NewOpc == X86::VPERM2F128rri || NewOpc == X86::VPERM2I128rri ||
146 NewOpc == X86::VPERM2F128rmi || NewOpc == X86::VPERM2I128rmi) &&
147 "Unexpected new opcode!");
148 MachineOperand &Imm = MI.getOperand(MI.getNumExplicitOperands() - 1);
149 int64_t ImmVal = Imm.getImm();
150 // Set bit 5, move bit 1 to bit 4, copy bit 0.
151 Imm.setImm(0x20 | ((ImmVal & 2) << 3) | (ImmVal & 1));
152 break;
153 }
154 case X86::VRNDSCALEPDZ128rri:
155 case X86::VRNDSCALEPDZ128rmi:
156 case X86::VRNDSCALEPSZ128rri:
157 case X86::VRNDSCALEPSZ128rmi:
158 case X86::VRNDSCALEPDZ256rri:
159 case X86::VRNDSCALEPDZ256rmi:
160 case X86::VRNDSCALEPSZ256rri:
161 case X86::VRNDSCALEPSZ256rmi:
162 case X86::VRNDSCALESDZrri:
163 case X86::VRNDSCALESDZrmi:
164 case X86::VRNDSCALESSZrri:
165 case X86::VRNDSCALESSZrmi:
166 case X86::VRNDSCALESDZrri_Int:
167 case X86::VRNDSCALESDZrmi_Int:
168 case X86::VRNDSCALESSZrri_Int:
169 case X86::VRNDSCALESSZrmi_Int:
170 const MachineOperand &Imm = MI.getOperand(MI.getNumExplicitOperands() - 1);
171 int64_t ImmVal = Imm.getImm();
172 // Ensure that only bits 3:0 of the immediate are used.
173 if ((ImmVal & 0xf) != ImmVal)
174 return false;
175 break;
176 }
177
178 return true;
179}
180
182 const X86Subtarget &ST) {
183 uint64_t TSFlags = MI.getDesc().TSFlags;
184
185 // Check for EVEX instructions only.
186 if ((TSFlags & X86II::EncodingMask) != X86II::EVEX)
187 return false;
188
189 // Instructions with mask or 512-bit vector can't be converted to VEX.
190 if (TSFlags & (X86II::EVEX_K | X86II::EVEX_L2))
191 return false;
192
193 auto IsRedundantNewDataDest = [&](unsigned &Opc) {
194 // $rbx = ADD64rr_ND $rbx, $rax / $rbx = ADD64rr_ND $rax, $rbx
195 // ->
196 // $rbx = ADD64rr $rbx, $rax
197 const MCInstrDesc &Desc = MI.getDesc();
198 Register Reg0 = MI.getOperand(0).getReg();
199 const MachineOperand &Op1 = MI.getOperand(1);
200 if (!Op1.isReg() || X86::getFirstAddrOperandIdx(MI) == 1 ||
201 X86::isCFCMOVCC(MI.getOpcode()))
202 return false;
203 Register Reg1 = Op1.getReg();
204 if (Reg1 == Reg0)
205 return true;
206
207 // Op1 and Op2 may be commutable for ND instructions.
208 if (!Desc.isCommutable() || Desc.getNumOperands() < 3 ||
209 !MI.getOperand(2).isReg() || MI.getOperand(2).getReg() != Reg0)
210 return false;
211 // Opcode may change after commute, e.g. SHRD -> SHLD
212 ST.getInstrInfo()->commuteInstruction(MI, false, 1, 2);
213 Opc = MI.getOpcode();
214 return true;
215 };
216
217 // EVEX_B has several meanings.
218 // AVX512:
219 // register form: rounding control or SAE
220 // memory form: broadcast
221 //
222 // APX:
223 // MAP4: NDD, ZU
224 //
225 // For AVX512 cases, EVEX prefix is needed in order to carry this information
226 // thus preventing the transformation to VEX encoding.
227 bool IsND = X86II::hasNewDataDest(TSFlags);
228 unsigned Opc = MI.getOpcode();
229 bool IsSetZUCCm = Opc == X86::SETZUCCm;
230 if (TSFlags & X86II::EVEX_B && !IsND && !IsSetZUCCm)
231 return false;
232 // MOVBE*rr is special because it has semantic of NDD but not set EVEX_B.
233 bool IsNDLike = IsND || Opc == X86::MOVBE32rr || Opc == X86::MOVBE64rr;
234 bool IsRedundantNDD = IsNDLike ? IsRedundantNewDataDest(Opc) : false;
235
236 auto GetCompressedOpc = [&](unsigned Opc) -> unsigned {
237 ArrayRef<X86TableEntry> Table = ArrayRef(X86CompressEVEXTable);
238 const auto I = llvm::lower_bound(Table, Opc);
239 if (I == Table.end() || I->OldOpc != Opc)
240 return 0;
241
242 if (usesExtendedRegister(MI) || !checkPredicate(I->NewOpc, &ST) ||
243 !performCustomAdjustments(MI, I->NewOpc))
244 return 0;
245 return I->NewOpc;
246 };
247
248 Register Dst = MI.getOperand(0).getReg();
249 if (IsRedundantNDD) {
250 // Redundant NDD ops cannot be safely compressed if either:
251 // - the legacy op would introduce a partial write that BreakFalseDeps
252 // identified as a potential stall, or
253 // - the op is writing to a subregister of a live register, i.e. the
254 // full (zeroed) result is used.
255 // Both cases are indicated by an implicit def of the superregister.
256 if (Dst &&
257 (X86::GR16RegClass.contains(Dst) || X86::GR8RegClass.contains(Dst))) {
258 Register Super = getX86SubSuperRegister(Dst, 64);
259 if (MI.definesRegister(Super, /*TRI=*/nullptr))
260 IsRedundantNDD = false;
261 }
262
263 // ADDrm/mr instructions with NDD + relocation had been transformed to the
264 // instructions without NDD in X86SuppressAPXForRelocation pass. That is to
265 // keep backward compatibility with linkers without APX support.
268 "Unexpected NDD instruction with relocation!");
269 } else if (Opc == X86::ADD32ri_ND || Opc == X86::ADD64ri32_ND ||
270 Opc == X86::ADD32rr_ND || Opc == X86::ADD64rr_ND) {
271 // Non-redundant NDD ADD can be compressed to LEA when:
272 // - No EGPR register used and
273 // - EFLAGS is dead.
274 if (!usesExtendedRegister(MI) &&
275 MI.registerDefIsDead(X86::EFLAGS, /*TRI=*/nullptr)) {
276 Register Src1 = MI.getOperand(1).getReg();
277 const MachineOperand &Src2 = MI.getOperand(2);
278 bool Is32BitReg = Opc == X86::ADD32ri_ND || Opc == X86::ADD32rr_ND;
279 const MCInstrDesc &NewDesc =
280 ST.getInstrInfo()->get(Is32BitReg ? X86::LEA64_32r : X86::LEA64r);
281 if (Is32BitReg)
282 Src1 = getX86SubSuperRegister(Src1, 64);
283 MachineInstrBuilder MIB = BuildMI(MBB, MI, MI.getDebugLoc(), NewDesc, Dst)
284 .addReg(Src1)
285 .addImm(1);
286 if (Opc == X86::ADD32ri_ND || Opc == X86::ADD64ri32_ND)
287 MIB.addReg(0).add(Src2);
288 else if (Is32BitReg)
289 MIB.addReg(getX86SubSuperRegister(Src2.getReg(), 64)).addImm(0);
290 else
291 MIB.add(Src2).addImm(0);
292 MIB.addReg(0);
293 MI.removeFromParent();
294 return true;
295 }
296 }
297
298 // NonNF -> NF only if it's not a compressible NDD instruction and eflags is
299 // dead.
300 unsigned NewOpc = IsRedundantNDD
302 : ((IsNDLike && ST.hasNF() &&
303 MI.registerDefIsDead(X86::EFLAGS, /*TRI=*/nullptr))
305 : GetCompressedOpc(Opc));
306
307 if (!NewOpc)
308 return false;
309
310 const MCInstrDesc &NewDesc = ST.getInstrInfo()->get(NewOpc);
311 MI.setDesc(NewDesc);
312 unsigned AsmComment;
313 switch (NewDesc.TSFlags & X86II::EncodingMask) {
314 case X86II::LEGACY:
315 AsmComment = X86::AC_EVEX_2_LEGACY;
316 break;
317 case X86II::VEX:
318 AsmComment = X86::AC_EVEX_2_VEX;
319 break;
320 case X86II::EVEX:
321 AsmComment = X86::AC_EVEX_2_EVEX;
322 assert(IsND && (NewDesc.TSFlags & X86II::EVEX_NF) &&
323 "Unknown EVEX2EVEX compression");
324 break;
325 default:
326 llvm_unreachable("Unknown EVEX compression");
327 }
328 MI.setAsmPrinterFlag(AsmComment);
329 if (IsRedundantNDD)
330 MI.tieOperands(0, 1);
331
332 return true;
333}
334
335static bool runOnMF(MachineFunction &MF) {
336 LLVM_DEBUG(dbgs() << "Start X86CompressEVEXPass\n";);
337#ifndef NDEBUG
338 // Make sure the tables are sorted.
339 static std::atomic<bool> TableChecked(false);
340 if (!TableChecked.load(std::memory_order_relaxed)) {
341 assert(llvm::is_sorted(X86CompressEVEXTable) &&
342 "X86CompressEVEXTable is not sorted!");
343 TableChecked.store(true, std::memory_order_relaxed);
344 }
345#endif
346 const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
347 if (!ST.hasAVX512() && !ST.hasEGPR() && !ST.hasNDD() && !ST.hasZU())
348 return false;
349
350 bool Changed = false;
351
352 for (MachineBasicBlock &MBB : MF) {
353 // Traverse the basic block.
356 }
357 LLVM_DEBUG(dbgs() << "End X86CompressEVEXPass\n";);
358 return Changed;
359}
360
362 false)
363
365 return new CompressEVEXLegacy();
366}
367
368bool CompressEVEXLegacy::runOnMachineFunction(MachineFunction &MF) {
369 return runOnMF(MF);
370}
371
372PreservedAnalyses
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:487
#define LLVM_DEBUG(...)
Definition Debug.h:114
#define COMP_EVEX_DESC
static bool performCustomAdjustments(MachineInstr &MI, unsigned NewOpc)
#define COMP_EVEX_NAME
cl::opt< bool > X86EnableAPXForRelocation
static bool runOnMF(MachineFunction &MF)
static bool CompressEVEXImpl(MachineInstr &MI, MachineBasicBlock &MBB, const X86Subtarget &ST)
static bool usesExtendedRegister(const MachineInstr &MI)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:131
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
Describe properties that are true of each instruction in the target description file.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Properties which a MachineFunction may have at a given point in time.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
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
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Changed
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
bool isZMMReg(MCRegister Reg)
bool hasNewDataDest(uint64_t TSFlags)
@ EVEX
EVEX - Specifies that this instruction use EVEX form which provides syntax support up to 32 512-bit r...
@ VEX
VEX - encoding using 0xC4/0xC5.
@ LEGACY
LEGACY - encoding using REX/REX2 or w/o opcode prefix.
bool isApxExtendedReg(MCRegister Reg)
int getFirstAddrOperandIdx(const MachineInstr &MI)
Return the index of the instruction's first address operand, if it has a memory reference,...
unsigned getNonNDVariant(unsigned Opc)
unsigned getNFVariant(unsigned Opc)
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
FunctionPass * createX86CompressEVEXLegacyPass()
static bool isAddMemInstrWithRelocation(const MachineInstr &MI)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
MCRegister getX86SubSuperRegister(MCRegister Reg, unsigned Size, bool High=false)
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:632
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
Op::Description Desc
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition STLExtras.h:1968
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2042
ArrayRef(const T &OneElt) -> ArrayRef< T >