1 //===-- ARM64AdvSIMDScalar.cpp - Replace dead defs w/ zero reg --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 // When profitable, replace GPR targeting i64 instructions with their
10 // AdvSIMD scalar equivalents. Generally speaking, "profitable" is defined
11 // as minimizing the number of cross-class register copies.
12 //===----------------------------------------------------------------------===//
14 //===----------------------------------------------------------------------===//
15 // TODO: Graph based predicate heuristics.
16 // Walking the instruction list linearly will get many, perhaps most, of
17 // the cases, but to do a truly thorough job of this, we need a more
18 // wholistic approach.
20 // This optimization is very similar in spirit to the register allocator's
21 // spill placement, only here we're determining where to place cross-class
22 // register copies rather than spills. As such, a similar approach is
25 // We want to build up a set of graphs of all instructions which are candidates
26 // for transformation along with instructions which generate their inputs and
27 // consume their outputs. For each edge in the graph, we assign a weight
28 // based on whether there is a copy required there (weight zero if not) and
29 // the block frequency of the block containing the defining or using
30 // instruction, whichever is less. Our optimization is then a graph problem
31 // to minimize the total weight of all the graphs, then transform instructions
32 // and add or remove copy instructions as called for to implement the
34 //===----------------------------------------------------------------------===//
37 #include "ARM64InstrInfo.h"
38 #include "ARM64RegisterInfo.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/CodeGen/MachineFunctionPass.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineRegisterInfo.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/raw_ostream.h"
50 #define DEBUG_TYPE "arm64-simd-scalar"
52 // Allow forcing all i64 operations with equivalent SIMD instructions to use
53 // them. For stress-testing the transformation function.
55 TransformAll("arm64-simd-scalar-force-all",
56 cl::desc("Force use of AdvSIMD scalar instructions everywhere"),
57 cl::init(false), cl::Hidden);
59 STATISTIC(NumScalarInsnsUsed, "Number of scalar instructions used");
60 STATISTIC(NumCopiesDeleted, "Number of cross-class copies deleted");
61 STATISTIC(NumCopiesInserted, "Number of cross-class copies inserted");
64 class ARM64AdvSIMDScalar : public MachineFunctionPass {
65 MachineRegisterInfo *MRI;
66 const ARM64InstrInfo *TII;
69 // isProfitableToTransform - Predicate function to determine whether an
70 // instruction should be transformed to its equivalent AdvSIMD scalar
71 // instruction. "add Xd, Xn, Xm" ==> "add Dd, Da, Db", for example.
72 bool isProfitableToTransform(const MachineInstr *MI) const;
74 // transformInstruction - Perform the transformation of an instruction
75 // to its equivalant AdvSIMD scalar instruction. Update inputs and outputs
76 // to be the correct register class, minimizing cross-class copies.
77 void transformInstruction(MachineInstr *MI);
79 // processMachineBasicBlock - Main optimzation loop.
80 bool processMachineBasicBlock(MachineBasicBlock *MBB);
83 static char ID; // Pass identification, replacement for typeid.
84 explicit ARM64AdvSIMDScalar() : MachineFunctionPass(ID) {}
86 bool runOnMachineFunction(MachineFunction &F) override;
88 const char *getPassName() const override {
89 return "AdvSIMD Scalar Operation Optimization";
92 void getAnalysisUsage(AnalysisUsage &AU) const override {
94 MachineFunctionPass::getAnalysisUsage(AU);
97 char ARM64AdvSIMDScalar::ID = 0;
98 } // end anonymous namespace
100 static bool isGPR64(unsigned Reg, unsigned SubReg,
101 const MachineRegisterInfo *MRI) {
104 if (TargetRegisterInfo::isVirtualRegister(Reg))
105 return MRI->getRegClass(Reg)->hasSuperClassEq(&ARM64::GPR64RegClass);
106 return ARM64::GPR64RegClass.contains(Reg);
109 static bool isFPR64(unsigned Reg, unsigned SubReg,
110 const MachineRegisterInfo *MRI) {
111 if (TargetRegisterInfo::isVirtualRegister(Reg))
112 return (MRI->getRegClass(Reg)->hasSuperClassEq(&ARM64::FPR64RegClass) &&
114 (MRI->getRegClass(Reg)->hasSuperClassEq(&ARM64::FPR128RegClass) &&
115 SubReg == ARM64::dsub);
116 // Physical register references just check the register class directly.
117 return (ARM64::FPR64RegClass.contains(Reg) && SubReg == 0) ||
118 (ARM64::FPR128RegClass.contains(Reg) && SubReg == ARM64::dsub);
121 // getSrcFromCopy - Get the original source register for a GPR64 <--> FPR64
122 // copy instruction. Return zero_reg if the instruction is not a copy.
123 static unsigned getSrcFromCopy(const MachineInstr *MI,
124 const MachineRegisterInfo *MRI,
127 // The "FMOV Xd, Dn" instruction is the typical form.
128 if (MI->getOpcode() == ARM64::FMOVDXr || MI->getOpcode() == ARM64::FMOVXDr)
129 return MI->getOperand(1).getReg();
130 // A lane zero extract "UMOV.d Xd, Vn[0]" is equivalent. We shouldn't see
131 // these at this stage, but it's easy to check for.
132 if (MI->getOpcode() == ARM64::UMOVvi64 && MI->getOperand(2).getImm() == 0) {
133 SubReg = ARM64::dsub;
134 return MI->getOperand(1).getReg();
136 // Or just a plain COPY instruction. This can be directly to/from FPR64,
137 // or it can be a dsub subreg reference to an FPR128.
138 if (MI->getOpcode() == ARM64::COPY) {
139 if (isFPR64(MI->getOperand(0).getReg(), MI->getOperand(0).getSubReg(),
141 isGPR64(MI->getOperand(1).getReg(), MI->getOperand(1).getSubReg(), MRI))
142 return MI->getOperand(1).getReg();
143 if (isGPR64(MI->getOperand(0).getReg(), MI->getOperand(0).getSubReg(),
145 isFPR64(MI->getOperand(1).getReg(), MI->getOperand(1).getSubReg(),
147 SubReg = MI->getOperand(1).getSubReg();
148 return MI->getOperand(1).getReg();
152 // Otherwise, this is some other kind of instruction.
156 // getTransformOpcode - For any opcode for which there is an AdvSIMD equivalent
157 // that we're considering transforming to, return that AdvSIMD opcode. For all
158 // others, return the original opcode.
159 static int getTransformOpcode(unsigned Opc) {
163 // FIXME: Lots more possibilities.
165 return ARM64::ADDv1i64;
167 return ARM64::SUBv1i64;
169 // No AdvSIMD equivalent, so just return the original opcode.
173 static bool isTransformable(const MachineInstr *MI) {
174 int Opc = MI->getOpcode();
175 return Opc != getTransformOpcode(Opc);
178 // isProfitableToTransform - Predicate function to determine whether an
179 // instruction should be transformed to its equivalent AdvSIMD scalar
180 // instruction. "add Xd, Xn, Xm" ==> "add Dd, Da, Db", for example.
181 bool ARM64AdvSIMDScalar::isProfitableToTransform(const MachineInstr *MI) const {
182 // If this instruction isn't eligible to be transformed (no SIMD equivalent),
183 // early exit since that's the common case.
184 if (!isTransformable(MI))
187 // Count the number of copies we'll need to add and approximate the number
188 // of copies that a transform will enable us to remove.
189 unsigned NumNewCopies = 3;
190 unsigned NumRemovableCopies = 0;
192 unsigned OrigSrc0 = MI->getOperand(1).getReg();
193 unsigned OrigSrc1 = MI->getOperand(2).getReg();
194 unsigned Src0 = 0, SubReg0;
195 unsigned Src1 = 0, SubReg1;
196 if (!MRI->def_empty(OrigSrc0)) {
197 MachineRegisterInfo::def_instr_iterator Def =
198 MRI->def_instr_begin(OrigSrc0);
199 assert(std::next(Def) == MRI->def_instr_end() && "Multiple def in SSA!");
200 Src0 = getSrcFromCopy(&*Def, MRI, SubReg0);
201 // If the source was from a copy, we don't need to insert a new copy.
204 // If there are no other users of the original source, we can delete
206 if (Src0 && MRI->hasOneNonDBGUse(OrigSrc0))
207 ++NumRemovableCopies;
209 if (!MRI->def_empty(OrigSrc1)) {
210 MachineRegisterInfo::def_instr_iterator Def =
211 MRI->def_instr_begin(OrigSrc1);
212 assert(std::next(Def) == MRI->def_instr_end() && "Multiple def in SSA!");
213 Src1 = getSrcFromCopy(&*Def, MRI, SubReg1);
216 // If there are no other users of the original source, we can delete
218 if (Src1 && MRI->hasOneNonDBGUse(OrigSrc1))
219 ++NumRemovableCopies;
222 // If any of the uses of the original instructions is a cross class copy,
223 // that's a copy that will be removable if we transform. Likewise, if
224 // any of the uses is a transformable instruction, it's likely the tranforms
225 // will chain, enabling us to save a copy there, too. This is an aggressive
226 // heuristic that approximates the graph based cost analysis described above.
227 unsigned Dst = MI->getOperand(0).getReg();
228 bool AllUsesAreCopies = true;
229 for (MachineRegisterInfo::use_instr_nodbg_iterator
230 Use = MRI->use_instr_nodbg_begin(Dst),
231 E = MRI->use_instr_nodbg_end();
234 if (getSrcFromCopy(&*Use, MRI, SubReg) || isTransformable(&*Use))
235 ++NumRemovableCopies;
236 // If the use is an INSERT_SUBREG, that's still something that can
237 // directly use the FPR64, so we don't invalidate AllUsesAreCopies. It's
238 // preferable to have it use the FPR64 in most cases, as if the source
239 // vector is an IMPLICIT_DEF, the INSERT_SUBREG just goes away entirely.
240 // Ditto for a lane insert.
241 else if (Use->getOpcode() == ARM64::INSERT_SUBREG ||
242 Use->getOpcode() == ARM64::INSvi64gpr)
245 AllUsesAreCopies = false;
247 // If all of the uses of the original destination register are copies to
248 // FPR64, then we won't end up having a new copy back to GPR64 either.
249 if (AllUsesAreCopies)
252 // If a transform will not increase the number of cross-class copies required,
254 if (NumNewCopies <= NumRemovableCopies)
257 // Finally, even if we otherwise wouldn't transform, check if we're forcing
258 // transformation of everything.
262 static MachineInstr *insertCopy(const ARM64InstrInfo *TII, MachineInstr *MI,
263 unsigned Dst, unsigned Src, bool IsKill) {
264 MachineInstrBuilder MIB =
265 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII->get(ARM64::COPY),
267 .addReg(Src, getKillRegState(IsKill));
268 DEBUG(dbgs() << " adding copy: " << *MIB);
273 // transformInstruction - Perform the transformation of an instruction
274 // to its equivalant AdvSIMD scalar instruction. Update inputs and outputs
275 // to be the correct register class, minimizing cross-class copies.
276 void ARM64AdvSIMDScalar::transformInstruction(MachineInstr *MI) {
277 DEBUG(dbgs() << "Scalar transform: " << *MI);
279 MachineBasicBlock *MBB = MI->getParent();
280 int OldOpc = MI->getOpcode();
281 int NewOpc = getTransformOpcode(OldOpc);
282 assert(OldOpc != NewOpc && "transform an instruction to itself?!");
284 // Check if we need a copy for the source registers.
285 unsigned OrigSrc0 = MI->getOperand(1).getReg();
286 unsigned OrigSrc1 = MI->getOperand(2).getReg();
287 unsigned Src0 = 0, SubReg0;
288 unsigned Src1 = 0, SubReg1;
289 if (!MRI->def_empty(OrigSrc0)) {
290 MachineRegisterInfo::def_instr_iterator Def =
291 MRI->def_instr_begin(OrigSrc0);
292 assert(std::next(Def) == MRI->def_instr_end() && "Multiple def in SSA!");
293 Src0 = getSrcFromCopy(&*Def, MRI, SubReg0);
294 // If there are no other users of the original source, we can delete
296 if (Src0 && MRI->hasOneNonDBGUse(OrigSrc0)) {
297 assert(Src0 && "Can't delete copy w/o a valid original source!");
298 Def->eraseFromParent();
302 if (!MRI->def_empty(OrigSrc1)) {
303 MachineRegisterInfo::def_instr_iterator Def =
304 MRI->def_instr_begin(OrigSrc1);
305 assert(std::next(Def) == MRI->def_instr_end() && "Multiple def in SSA!");
306 Src1 = getSrcFromCopy(&*Def, MRI, SubReg1);
307 // If there are no other users of the original source, we can delete
309 if (Src1 && MRI->hasOneNonDBGUse(OrigSrc1)) {
310 assert(Src1 && "Can't delete copy w/o a valid original source!");
311 Def->eraseFromParent();
315 // If we weren't able to reference the original source directly, create a
319 Src0 = MRI->createVirtualRegister(&ARM64::FPR64RegClass);
320 insertCopy(TII, MI, Src0, OrigSrc0, true);
324 Src1 = MRI->createVirtualRegister(&ARM64::FPR64RegClass);
325 insertCopy(TII, MI, Src1, OrigSrc1, true);
328 // Create a vreg for the destination.
329 // FIXME: No need to do this if the ultimate user expects an FPR64.
330 // Check for that and avoid the copy if possible.
331 unsigned Dst = MRI->createVirtualRegister(&ARM64::FPR64RegClass);
333 // For now, all of the new instructions have the same simple three-register
334 // form, so no need to special case based on what instruction we're
336 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(NewOpc), Dst)
337 .addReg(Src0, getKillRegState(true), SubReg0)
338 .addReg(Src1, getKillRegState(true), SubReg1);
340 // Now copy the result back out to a GPR.
341 // FIXME: Try to avoid this if all uses could actually just use the FPR64
343 insertCopy(TII, MI, MI->getOperand(0).getReg(), Dst, true);
345 // Erase the old instruction.
346 MI->eraseFromParent();
348 ++NumScalarInsnsUsed;
351 // processMachineBasicBlock - Main optimzation loop.
352 bool ARM64AdvSIMDScalar::processMachineBasicBlock(MachineBasicBlock *MBB) {
353 bool Changed = false;
354 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;) {
355 MachineInstr *MI = I;
357 if (isProfitableToTransform(MI)) {
358 transformInstruction(MI);
365 // runOnMachineFunction - Pass entry point from PassManager.
366 bool ARM64AdvSIMDScalar::runOnMachineFunction(MachineFunction &mf) {
367 bool Changed = false;
368 DEBUG(dbgs() << "***** ARM64AdvSIMDScalar *****\n");
370 const TargetMachine &TM = mf.getTarget();
371 MRI = &mf.getRegInfo();
372 TII = static_cast<const ARM64InstrInfo *>(TM.getInstrInfo());
374 // Just check things on a one-block-at-a-time basis.
375 for (MachineFunction::iterator I = mf.begin(), E = mf.end(); I != E; ++I)
376 if (processMachineBasicBlock(I))
381 // createARM64AdvSIMDScalar - Factory function used by ARM64TargetMachine
382 // to add the pass to the PassManager.
383 FunctionPass *llvm::createARM64AdvSIMDScalar() {
384 return new ARM64AdvSIMDScalar();