xref: /llvm-project/llvm/lib/Target/X86/X86FixupVectorConstants.cpp (revision a279a09ab9524d1d74ef29b34618102d4b202e2f)
1 //===-- X86FixupVectorConstants.cpp - optimize constant generation  -------===//
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 examines all full size vector constant pool loads and attempts to
10 // replace them with smaller constant pool entries, including:
11 // * Converting AVX512 memory-fold instructions to their broadcast-fold form
12 // * TODO: Broadcasting of full width loads.
13 // * TODO: Sign/Zero extension of full width loads.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "X86.h"
18 #include "X86InstrFoldTables.h"
19 #include "X86InstrInfo.h"
20 #include "X86Subtarget.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 
24 using namespace llvm;
25 
26 #define DEBUG_TYPE "x86-fixup-vector-constants"
27 
28 STATISTIC(NumInstChanges, "Number of instructions changes");
29 
30 namespace {
31 class X86FixupVectorConstantsPass : public MachineFunctionPass {
32 public:
33   static char ID;
34 
35   X86FixupVectorConstantsPass() : MachineFunctionPass(ID) {}
36 
37   StringRef getPassName() const override {
38     return "X86 Fixup Vector Constants";
39   }
40 
41   bool runOnMachineFunction(MachineFunction &MF) override;
42   bool processInstruction(MachineFunction &MF, MachineBasicBlock &MBB,
43                           MachineInstr &MI);
44 
45   // This pass runs after regalloc and doesn't support VReg operands.
46   MachineFunctionProperties getRequiredProperties() const override {
47     return MachineFunctionProperties().set(
48         MachineFunctionProperties::Property::NoVRegs);
49   }
50 
51 private:
52   const X86InstrInfo *TII = nullptr;
53   const X86Subtarget *ST = nullptr;
54   const MCSchedModel *SM = nullptr;
55 };
56 } // end anonymous namespace
57 
58 char X86FixupVectorConstantsPass::ID = 0;
59 
60 INITIALIZE_PASS(X86FixupVectorConstantsPass, DEBUG_TYPE, DEBUG_TYPE, false, false)
61 
62 FunctionPass *llvm::createX86FixupVectorConstants() {
63   return new X86FixupVectorConstantsPass();
64 }
65 
66 static const Constant *getConstantFromPool(const MachineInstr &MI,
67                                            const MachineOperand &Op) {
68   if (!Op.isCPI() || Op.getOffset() != 0)
69     return nullptr;
70 
71   ArrayRef<MachineConstantPoolEntry> Constants =
72       MI.getParent()->getParent()->getConstantPool()->getConstants();
73   const MachineConstantPoolEntry &ConstantEntry = Constants[Op.getIndex()];
74 
75   // Bail if this is a machine constant pool entry, we won't be able to dig out
76   // anything useful.
77   if (ConstantEntry.isMachineConstantPoolEntry())
78     return nullptr;
79 
80   return ConstantEntry.Val.ConstVal;
81 }
82 
83 // Attempt to extract the full width of bits data from the constant.
84 static std::optional<APInt> extractConstantBits(const Constant *C) {
85   unsigned NumBits = C->getType()->getPrimitiveSizeInBits();
86 
87   if (auto *CInt = dyn_cast<ConstantInt>(C))
88     return CInt->getValue();
89 
90   if (auto *CFP = dyn_cast<ConstantFP>(C))
91     return CFP->getValue().bitcastToAPInt();
92 
93   if (auto *CV = dyn_cast<ConstantVector>(C)) {
94     if (auto *CVSplat = CV->getSplatValue(/*AllowUndefs*/ true)) {
95       if (std::optional<APInt> Bits = extractConstantBits(CVSplat)) {
96         assert((NumBits % Bits->getBitWidth()) == 0 && "Illegal splat");
97         return APInt::getSplat(NumBits, *Bits);
98       }
99     }
100   }
101 
102   if (auto *CDS = dyn_cast<ConstantDataSequential>(C)) {
103     bool IsInteger = CDS->getElementType()->isIntegerTy();
104     bool IsFloat = CDS->getElementType()->isHalfTy() ||
105                    CDS->getElementType()->isBFloatTy() ||
106                    CDS->getElementType()->isFloatTy() ||
107                    CDS->getElementType()->isDoubleTy();
108     if (IsInteger || IsFloat) {
109       APInt Bits = APInt::getZero(NumBits);
110       unsigned EltBits = CDS->getElementType()->getPrimitiveSizeInBits();
111       for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) {
112         if (IsInteger)
113           Bits.insertBits(CDS->getElementAsAPInt(I), I * EltBits);
114         else
115           Bits.insertBits(CDS->getElementAsAPFloat(I).bitcastToAPInt(),
116                           I * EltBits);
117       }
118       return Bits;
119     }
120   }
121 
122   return std::nullopt;
123 }
124 
125 // Attempt to compute the splat width of bits data by normalizing the splat to
126 // remove undefs.
127 static std::optional<APInt> getSplatableConstant(const Constant *C,
128                                                  unsigned SplatBitWidth) {
129   const Type *Ty = C->getType();
130   assert((Ty->getPrimitiveSizeInBits() % SplatBitWidth) == 0 &&
131          "Illegal splat width");
132 
133   if (std::optional<APInt> Bits = extractConstantBits(C))
134     if (Bits->isSplat(SplatBitWidth))
135       return Bits->trunc(SplatBitWidth);
136 
137   // Detect general splats with undefs.
138   // TODO: Do we need to handle NumEltsBits > SplatBitWidth splitting?
139   if (auto *CV = dyn_cast<ConstantVector>(C)) {
140     unsigned NumOps = CV->getNumOperands();
141     unsigned NumEltsBits = Ty->getScalarSizeInBits();
142     unsigned NumScaleOps = SplatBitWidth / NumEltsBits;
143     if ((SplatBitWidth % NumEltsBits) == 0) {
144       // Collect the elements and ensure that within the repeated splat sequence
145       // they either match or are undef.
146       SmallVector<Constant *, 16> Sequence(NumScaleOps, nullptr);
147       for (unsigned Idx = 0; Idx != NumOps; ++Idx) {
148         if (Constant *Elt = CV->getAggregateElement(Idx)) {
149           if (isa<UndefValue>(Elt))
150             continue;
151           unsigned SplatIdx = Idx % NumScaleOps;
152           if (!Sequence[SplatIdx] || Sequence[SplatIdx] == Elt) {
153             Sequence[SplatIdx] = Elt;
154             continue;
155           }
156         }
157         return std::nullopt;
158       }
159       // Extract the constant bits forming the splat and insert into the bits
160       // data, leave undef as zero.
161       APInt SplatBits = APInt::getZero(SplatBitWidth);
162       for (unsigned I = 0; I != NumScaleOps; ++I) {
163         if (!Sequence[I])
164           continue;
165         if (std::optional<APInt> Bits = extractConstantBits(Sequence[I])) {
166           SplatBits.insertBits(*Bits, I * Bits->getBitWidth());
167           continue;
168         }
169         return std::nullopt;
170       }
171       return SplatBits;
172     }
173   }
174 
175   return std::nullopt;
176 }
177 
178 // Attempt to rebuild a normalized splat vector constant of the requested splat
179 // width, built up of potentially smaller scalar values.
180 // NOTE: We don't always bother converting to scalars if the vector length is 1.
181 static Constant *rebuildSplatableConstant(const Constant *C,
182                                           unsigned SplatBitWidth) {
183   std::optional<APInt> Splat = getSplatableConstant(C, SplatBitWidth);
184   if (!Splat)
185     return nullptr;
186 
187   // Determine scalar size to use for the constant splat vector, clamping as we
188   // might have found a splat smaller than the original constant data.
189   const Type *OriginalType = C->getType();
190   Type *SclTy = OriginalType->getScalarType();
191   unsigned NumSclBits = SclTy->getPrimitiveSizeInBits();
192   NumSclBits = std::min<unsigned>(NumSclBits, SplatBitWidth);
193 
194   if (NumSclBits == 8) {
195     SmallVector<uint8_t> RawBits;
196     for (unsigned I = 0; I != SplatBitWidth; I += 8)
197       RawBits.push_back(Splat->extractBits(8, I).getZExtValue());
198     return ConstantDataVector::get(OriginalType->getContext(), RawBits);
199   }
200 
201   if (NumSclBits == 16) {
202     SmallVector<uint16_t> RawBits;
203     for (unsigned I = 0; I != SplatBitWidth; I += 16)
204       RawBits.push_back(Splat->extractBits(16, I).getZExtValue());
205     if (SclTy->is16bitFPTy())
206       return ConstantDataVector::getFP(SclTy, RawBits);
207     return ConstantDataVector::get(OriginalType->getContext(), RawBits);
208   }
209 
210   if (NumSclBits == 32) {
211     SmallVector<uint32_t> RawBits;
212     for (unsigned I = 0; I != SplatBitWidth; I += 32)
213       RawBits.push_back(Splat->extractBits(32, I).getZExtValue());
214     if (SclTy->isFloatTy())
215       return ConstantDataVector::getFP(SclTy, RawBits);
216     return ConstantDataVector::get(OriginalType->getContext(), RawBits);
217   }
218 
219   // Fallback to i64 / double.
220   SmallVector<uint64_t> RawBits;
221   for (unsigned I = 0; I != SplatBitWidth; I += 64)
222     RawBits.push_back(Splat->extractBits(64, I).getZExtValue());
223   if (SclTy->isDoubleTy())
224     return ConstantDataVector::getFP(SclTy, RawBits);
225   return ConstantDataVector::get(OriginalType->getContext(), RawBits);
226 }
227 
228 bool X86FixupVectorConstantsPass::processInstruction(MachineFunction &MF,
229                                                      MachineBasicBlock &MBB,
230                                                      MachineInstr &MI) {
231   unsigned Opc = MI.getOpcode();
232   MachineConstantPool *CP = MI.getParent()->getParent()->getConstantPool();
233 
234   auto ConvertToBroadcast = [&](unsigned OpBcst256, unsigned OpBcst128,
235                                 unsigned OpBcst64, unsigned OpBcst32,
236                                 unsigned OpBcst16, unsigned OpBcst8,
237                                 unsigned OperandNo) {
238     assert(MI.getNumOperands() >= (OperandNo + X86::AddrNumOperands) &&
239            "Unexpected number of operands!");
240 
241     MachineOperand &CstOp = MI.getOperand(OperandNo + X86::AddrDisp);
242     if (auto *C = getConstantFromPool(MI, CstOp)) {
243       // Attempt to detect a suitable splat from increasing splat widths.
244       std::pair<unsigned, unsigned> Broadcasts[] = {
245           {8, OpBcst8},   {16, OpBcst16},   {32, OpBcst32},
246           {64, OpBcst64}, {128, OpBcst128}, {256, OpBcst256},
247       };
248       for (auto [BitWidth, OpBcst] : Broadcasts) {
249         if (OpBcst) {
250           // Construct a suitable splat constant and adjust the MI to
251           // use the new constant pool entry.
252           if (Constant *NewCst = rebuildSplatableConstant(C, BitWidth)) {
253             unsigned NewCPI =
254                 CP->getConstantPoolIndex(NewCst, Align(BitWidth / 8));
255             MI.setDesc(TII->get(OpBcst));
256             CstOp.setIndex(NewCPI);
257             return true;
258           }
259         }
260       }
261     }
262     return false;
263   };
264 
265   // Attempt to find a AVX512 mapping from a full width memory-fold instruction
266   // to a broadcast-fold instruction variant.
267   if ((MI.getDesc().TSFlags & X86II::EncodingMask) == X86II::EVEX) {
268     unsigned OpBcst32 = 0, OpBcst64 = 0;
269     unsigned OpNoBcst32 = 0, OpNoBcst64 = 0;
270     if (const X86MemoryFoldTableEntry *Mem2Bcst =
271             llvm::lookupBroadcastFoldTable(Opc, 32)) {
272       OpBcst32 = Mem2Bcst->DstOp;
273       OpNoBcst32 = Mem2Bcst->Flags & TB_INDEX_MASK;
274     }
275     if (const X86MemoryFoldTableEntry *Mem2Bcst =
276             llvm::lookupBroadcastFoldTable(Opc, 64)) {
277       OpBcst64 = Mem2Bcst->DstOp;
278       OpNoBcst64 = Mem2Bcst->Flags & TB_INDEX_MASK;
279     }
280     assert(((OpBcst32 == 0) || (OpBcst64 == 0) || (OpNoBcst32 == OpNoBcst64)) &&
281            "OperandNo mismatch");
282 
283     if (OpBcst32 || OpBcst64) {
284       unsigned OpNo = OpBcst32 == 0 ? OpNoBcst64 : OpNoBcst32;
285       return ConvertToBroadcast(0, 0, OpBcst64, OpBcst32, 0, 0, OpNo);
286     }
287   }
288 
289   return false;
290 }
291 
292 bool X86FixupVectorConstantsPass::runOnMachineFunction(MachineFunction &MF) {
293   LLVM_DEBUG(dbgs() << "Start X86FixupVectorConstants\n";);
294   bool Changed = false;
295   ST = &MF.getSubtarget<X86Subtarget>();
296   TII = ST->getInstrInfo();
297   SM = &ST->getSchedModel();
298 
299   for (MachineBasicBlock &MBB : MF) {
300     for (MachineInstr &MI : MBB) {
301       if (processInstruction(MF, MBB, MI)) {
302         ++NumInstChanges;
303         Changed = true;
304       }
305     }
306   }
307   LLVM_DEBUG(dbgs() << "End X86FixupVectorConstants\n";);
308   return Changed;
309 }
310