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 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "arm64-simd-scalar"
38 #include "ARM64InstrInfo.h"
39 #include "ARM64RegisterInfo.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/CodeGen/MachineFunctionPass.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineRegisterInfo.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/raw_ostream.h"
52 AdvSIMDScalar("arm64-simd-scalar",
53 cl::desc("enable use of AdvSIMD scalar integer instructions"),
54 cl::init(false), cl::Hidden);
55 // Allow forcing all i64 operations with equivalent SIMD instructions to use
56 // them. For stress-testing the transformation function.
58 TransformAll("arm64-simd-scalar-force-all",
59 cl::desc("Force use of AdvSIMD scalar instructions everywhere"),
60 cl::init(false), cl::Hidden);
62 STATISTIC(NumScalarInsnsUsed, "Number of scalar instructions used");
63 STATISTIC(NumCopiesDeleted, "Number of cross-class copies deleted");
64 STATISTIC(NumCopiesInserted, "Number of cross-class copies inserted");
67 class ARM64AdvSIMDScalar : public MachineFunctionPass {
68 MachineRegisterInfo *MRI;
69 const ARM64InstrInfo *TII;
72 // isProfitableToTransform - Predicate function to determine whether an
73 // instruction should be transformed to its equivalent AdvSIMD scalar
74 // instruction. "add Xd, Xn, Xm" ==> "add Dd, Da, Db", for example.
75 bool isProfitableToTransform(const MachineInstr *MI) const;
77 // transformInstruction - Perform the transformation of an instruction
78 // to its equivalant AdvSIMD scalar instruction. Update inputs and outputs
79 // to be the correct register class, minimizing cross-class copies.
80 void transformInstruction(MachineInstr *MI);
82 // processMachineBasicBlock - Main optimzation loop.
83 bool processMachineBasicBlock(MachineBasicBlock *MBB);
86 static char ID; // Pass identification, replacement for typeid.
87 explicit ARM64AdvSIMDScalar() : MachineFunctionPass(ID) {}
89 virtual bool runOnMachineFunction(MachineFunction &F);
91 const char *getPassName() const {
92 return "AdvSIMD scalar operation optimization";
95 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
97 MachineFunctionPass::getAnalysisUsage(AU);
100 char ARM64AdvSIMDScalar::ID = 0;
101 } // end anonymous namespace
103 static bool isGPR64(unsigned Reg, unsigned SubReg,
104 const MachineRegisterInfo *MRI) {
107 if (TargetRegisterInfo::isVirtualRegister(Reg))
108 return MRI->getRegClass(Reg)->hasSuperClassEq(&ARM64::GPR64RegClass);
109 return ARM64::GPR64RegClass.contains(Reg);
112 static bool isFPR64(unsigned Reg, unsigned SubReg,
113 const MachineRegisterInfo *MRI) {
114 if (TargetRegisterInfo::isVirtualRegister(Reg))
115 return (MRI->getRegClass(Reg)->hasSuperClassEq(&ARM64::FPR64RegClass) &&
117 (MRI->getRegClass(Reg)->hasSuperClassEq(&ARM64::FPR128RegClass) &&
118 SubReg == ARM64::dsub);
119 // Physical register references just check the regist class directly.
120 return (ARM64::FPR64RegClass.contains(Reg) && SubReg == 0) ||
121 (ARM64::FPR128RegClass.contains(Reg) && SubReg == ARM64::dsub);
124 // getSrcFromCopy - Get the original source register for a GPR64 <--> FPR64
125 // copy instruction. Return zero_reg if the instruction is not a copy.
126 static unsigned getSrcFromCopy(const MachineInstr *MI,
127 const MachineRegisterInfo *MRI,
130 // The "FMOV Xd, Dn" instruction is the typical form.
131 if (MI->getOpcode() == ARM64::FMOVDXr || MI->getOpcode() == ARM64::FMOVXDr)
132 return MI->getOperand(1).getReg();
133 // A lane zero extract "UMOV.d Xd, Vn[0]" is equivalent. We shouldn't see
134 // these at this stage, but it's easy to check for.
135 if (MI->getOpcode() == ARM64::UMOVvi64 && MI->getOperand(2).getImm() == 0) {
136 SubReg = ARM64::dsub;
137 return MI->getOperand(1).getReg();
139 // Or just a plain COPY instruction. This can be directly to/from FPR64,
140 // or it can be a dsub subreg reference to an FPR128.
141 if (MI->getOpcode() == ARM64::COPY) {
142 if (isFPR64(MI->getOperand(0).getReg(), MI->getOperand(0).getSubReg(),
144 isGPR64(MI->getOperand(1).getReg(), MI->getOperand(1).getSubReg(), MRI))
145 return MI->getOperand(1).getReg();
146 if (isGPR64(MI->getOperand(0).getReg(), MI->getOperand(0).getSubReg(),
148 isFPR64(MI->getOperand(1).getReg(), MI->getOperand(1).getSubReg(),
150 SubReg = ARM64::dsub;
151 return MI->getOperand(1).getReg();
155 // Otherwise, this is some other kind of instruction.
159 // getTransformOpcode - For any opcode for which there is an AdvSIMD equivalent
160 // that we're considering transforming to, return that AdvSIMD opcode. For all
161 // others, return the original opcode.
162 static int getTransformOpcode(unsigned Opc) {
166 // FIXME: Lots more possibilities.
168 return ARM64::ADDv1i64;
170 return ARM64::SUBv1i64;
172 // No AdvSIMD equivalent, so just return the original opcode.
176 static bool isTransformable(const MachineInstr *MI) {
177 int Opc = MI->getOpcode();
178 return Opc != getTransformOpcode(Opc);
181 // isProfitableToTransform - Predicate function to determine whether an
182 // instruction should be transformed to its equivalent AdvSIMD scalar
183 // instruction. "add Xd, Xn, Xm" ==> "add Dd, Da, Db", for example.
184 bool ARM64AdvSIMDScalar::isProfitableToTransform(const MachineInstr *MI) const {
185 // If this instruction isn't eligible to be transformed (no SIMD equivalent),
186 // early exit since that's the common case.
187 if (!isTransformable(MI))
190 // Count the number of copies we'll need to add and approximate the number
191 // of copies that a transform will enable us to remove.
192 unsigned NumNewCopies = 3;
193 unsigned NumRemovableCopies = 0;
195 unsigned OrigSrc0 = MI->getOperand(1).getReg();
196 unsigned OrigSrc1 = MI->getOperand(2).getReg();
197 unsigned Src0 = 0, SubReg0;
198 unsigned Src1 = 0, SubReg1;
199 if (!MRI->def_empty(OrigSrc0)) {
200 MachineRegisterInfo::def_instr_iterator Def =
201 MRI->def_instr_begin(OrigSrc0);
202 assert(std::next(Def) == MRI->def_instr_end() && "Multiple def in SSA!");
203 Src0 = getSrcFromCopy(&*Def, MRI, SubReg0);
204 // If the source was from a copy, we don't need to insert a new copy.
207 // If there are no other users of the original source, we can delete
209 if (Src0 && MRI->hasOneNonDBGUse(OrigSrc0))
210 ++NumRemovableCopies;
212 if (!MRI->def_empty(OrigSrc1)) {
213 MachineRegisterInfo::def_instr_iterator Def =
214 MRI->def_instr_begin(OrigSrc1);
215 assert(std::next(Def) == MRI->def_instr_end() && "Multiple def in SSA!");
216 Src1 = getSrcFromCopy(&*Def, MRI, SubReg1);
219 // If there are no other users of the original source, we can delete
221 if (Src1 && MRI->hasOneNonDBGUse(OrigSrc1))
222 ++NumRemovableCopies;
225 // If any of the uses of the original instructions is a cross class copy,
226 // that's a copy that will be removable if we transform. Likewise, if
227 // any of the uses is a transformable instruction, it's likely the tranforms
228 // will chain, enabling us to save a copy there, too. This is an aggressive
229 // heuristic that approximates the graph based cost analysis described above.
230 unsigned Dst = MI->getOperand(0).getReg();
231 bool AllUsesAreCopies = true;
232 for (MachineRegisterInfo::use_instr_nodbg_iterator
233 Use = MRI->use_instr_nodbg_begin(Dst),
234 E = MRI->use_instr_nodbg_end();
237 if (getSrcFromCopy(&*Use, MRI, SubReg) || isTransformable(&*Use))
238 ++NumRemovableCopies;
239 // If the use is an INSERT_SUBREG, that's still something that can
240 // directly use the FPR64, so we don't invalidate AllUsesAreCopies. It's
241 // preferable to have it use the FPR64 in most cases, as if the source
242 // vector is an IMPLICIT_DEF, the INSERT_SUBREG just goes away entirely.
243 // Ditto for a lane insert.
244 else if (Use->getOpcode() == ARM64::INSERT_SUBREG ||
245 Use->getOpcode() == ARM64::INSvi64gpr)
248 AllUsesAreCopies = false;
250 // If all of the uses of the original destination register are copies to
251 // FPR64, then we won't end up having a new copy back to GPR64 either.
252 if (AllUsesAreCopies)
255 // If a transform will not increase the number of cross-class copies required,
257 if (NumNewCopies <= NumRemovableCopies)
260 // Finally, even if we otherwise wouldn't transform, check if we're forcing
261 // transformation of everything.
265 static MachineInstr *insertCopy(const ARM64InstrInfo *TII, MachineInstr *MI,
266 unsigned Dst, unsigned Src, bool IsKill) {
267 MachineInstrBuilder MIB =
268 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII->get(ARM64::COPY),
270 .addReg(Src, getKillRegState(IsKill));
271 DEBUG(dbgs() << " adding copy: " << *MIB);
276 // transformInstruction - Perform the transformation of an instruction
277 // to its equivalant AdvSIMD scalar instruction. Update inputs and outputs
278 // to be the correct register class, minimizing cross-class copies.
279 void ARM64AdvSIMDScalar::transformInstruction(MachineInstr *MI) {
280 DEBUG(dbgs() << "Scalar transform: " << *MI);
282 MachineBasicBlock *MBB = MI->getParent();
283 int OldOpc = MI->getOpcode();
284 int NewOpc = getTransformOpcode(OldOpc);
285 assert(OldOpc != NewOpc && "transform an instruction to itself?!");
287 // Check if we need a copy for the source registers.
288 unsigned OrigSrc0 = MI->getOperand(1).getReg();
289 unsigned OrigSrc1 = MI->getOperand(2).getReg();
290 unsigned Src0 = 0, SubReg0;
291 unsigned Src1 = 0, SubReg1;
292 if (!MRI->def_empty(OrigSrc0)) {
293 MachineRegisterInfo::def_instr_iterator Def =
294 MRI->def_instr_begin(OrigSrc0);
295 assert(std::next(Def) == MRI->def_instr_end() && "Multiple def in SSA!");
296 Src0 = getSrcFromCopy(&*Def, MRI, SubReg0);
297 // If there are no other users of the original source, we can delete
299 if (Src0 && MRI->hasOneNonDBGUse(OrigSrc0)) {
300 assert(Src0 && "Can't delete copy w/o a valid original source!");
301 Def->eraseFromParent();
305 if (!MRI->def_empty(OrigSrc1)) {
306 MachineRegisterInfo::def_instr_iterator Def =
307 MRI->def_instr_begin(OrigSrc1);
308 assert(std::next(Def) == MRI->def_instr_end() && "Multiple def in SSA!");
309 Src1 = getSrcFromCopy(&*Def, MRI, SubReg1);
310 // If there are no other users of the original source, we can delete
312 if (Src1 && MRI->hasOneNonDBGUse(OrigSrc1)) {
313 assert(Src1 && "Can't delete copy w/o a valid original source!");
314 Def->eraseFromParent();
318 // If we weren't able to reference the original source directly, create a
322 Src0 = MRI->createVirtualRegister(&ARM64::FPR64RegClass);
323 insertCopy(TII, MI, Src0, OrigSrc0, true);
327 Src1 = MRI->createVirtualRegister(&ARM64::FPR64RegClass);
328 insertCopy(TII, MI, Src1, OrigSrc1, true);
331 // Create a vreg for the destination.
332 // FIXME: No need to do this if the ultimate user expects an FPR64.
333 // Check for that and avoid the copy if possible.
334 unsigned Dst = MRI->createVirtualRegister(&ARM64::FPR64RegClass);
336 // For now, all of the new instructions have the same simple three-register
337 // form, so no need to special case based on what instruction we're
339 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(NewOpc), Dst)
340 .addReg(Src0, getKillRegState(true), SubReg0)
341 .addReg(Src1, getKillRegState(true), SubReg1);
343 // Now copy the result back out to a GPR.
344 // FIXME: Try to avoid this if all uses could actually just use the FPR64
346 insertCopy(TII, MI, MI->getOperand(0).getReg(), Dst, true);
348 // Erase the old instruction.
349 MI->eraseFromParent();
351 ++NumScalarInsnsUsed;
354 // processMachineBasicBlock - Main optimzation loop.
355 bool ARM64AdvSIMDScalar::processMachineBasicBlock(MachineBasicBlock *MBB) {
356 bool Changed = false;
357 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;) {
358 MachineInstr *MI = I;
360 if (isProfitableToTransform(MI)) {
361 transformInstruction(MI);
368 // runOnMachineFunction - Pass entry point from PassManager.
369 bool ARM64AdvSIMDScalar::runOnMachineFunction(MachineFunction &mf) {
370 // Early exit if pass disabled.
374 bool Changed = false;
375 DEBUG(dbgs() << "***** ARM64AdvSIMDScalar *****\n");
377 const TargetMachine &TM = mf.getTarget();
378 MRI = &mf.getRegInfo();
379 TII = static_cast<const ARM64InstrInfo *>(TM.getInstrInfo());
381 // Just check things on a one-block-at-a-time basis.
382 for (MachineFunction::iterator I = mf.begin(), E = mf.end(); I != E; ++I)
383 if (processMachineBasicBlock(I))
388 // createARM64AdvSIMDScalar - Factory function used by ARM64TargetMachine
389 // to add the pass to the PassManager.
390 FunctionPass *llvm::createARM64AdvSIMDScalar() {
391 return new ARM64AdvSIMDScalar();