xref: /freebsd/contrib/llvm-project/llvm/lib/Target/X86/X86FixupBWInsts.cpp (revision 85868e8a1daeaae7a0e48effb2ea2310ae3b02c6)
1 //===-- X86FixupBWInsts.cpp - Fixup Byte or Word instructions -----------===//
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 /// \file
9 /// This file defines the pass that looks through the machine instructions
10 /// late in the compilation, and finds byte or word instructions that
11 /// can be profitably replaced with 32 bit instructions that give equivalent
12 /// results for the bits of the results that are used. There are two possible
13 /// reasons to do this.
14 ///
15 /// One reason is to avoid false-dependences on the upper portions
16 /// of the registers.  Only instructions that have a destination register
17 /// which is not in any of the source registers can be affected by this.
18 /// Any instruction where one of the source registers is also the destination
19 /// register is unaffected, because it has a true dependence on the source
20 /// register already.  So, this consideration primarily affects load
21 /// instructions and register-to-register moves.  It would
22 /// seem like cmov(s) would also be affected, but because of the way cmov is
23 /// really implemented by most machines as reading both the destination and
24 /// and source registers, and then "merging" the two based on a condition,
25 /// it really already should be considered as having a true dependence on the
26 /// destination register as well.
27 ///
28 /// The other reason to do this is for potential code size savings.  Word
29 /// operations need an extra override byte compared to their 32 bit
30 /// versions. So this can convert many word operations to their larger
31 /// size, saving a byte in encoding. This could introduce partial register
32 /// dependences where none existed however.  As an example take:
33 ///   orw  ax, $0x1000
34 ///   addw ax, $3
35 /// now if this were to get transformed into
36 ///   orw  ax, $1000
37 ///   addl eax, $3
38 /// because the addl encodes shorter than the addw, this would introduce
39 /// a use of a register that was only partially written earlier.  On older
40 /// Intel processors this can be quite a performance penalty, so this should
41 /// probably only be done when it can be proven that a new partial dependence
42 /// wouldn't be created, or when your know a newer processor is being
43 /// targeted, or when optimizing for minimum code size.
44 ///
45 //===----------------------------------------------------------------------===//
46 
47 #include "X86.h"
48 #include "X86InstrInfo.h"
49 #include "X86Subtarget.h"
50 #include "llvm/ADT/Statistic.h"
51 #include "llvm/CodeGen/LivePhysRegs.h"
52 #include "llvm/CodeGen/MachineFunctionPass.h"
53 #include "llvm/CodeGen/MachineInstrBuilder.h"
54 #include "llvm/CodeGen/MachineLoopInfo.h"
55 #include "llvm/CodeGen/MachineRegisterInfo.h"
56 #include "llvm/CodeGen/Passes.h"
57 #include "llvm/CodeGen/TargetInstrInfo.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/raw_ostream.h"
60 using namespace llvm;
61 
62 #define FIXUPBW_DESC "X86 Byte/Word Instruction Fixup"
63 #define FIXUPBW_NAME "x86-fixup-bw-insts"
64 
65 #define DEBUG_TYPE FIXUPBW_NAME
66 
67 // Option to allow this optimization pass to have fine-grained control.
68 static cl::opt<bool>
69     FixupBWInsts("fixup-byte-word-insts",
70                  cl::desc("Change byte and word instructions to larger sizes"),
71                  cl::init(true), cl::Hidden);
72 
73 namespace {
74 class FixupBWInstPass : public MachineFunctionPass {
75   /// Loop over all of the instructions in the basic block replacing applicable
76   /// byte or word instructions with better alternatives.
77   void processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
78 
79   /// This sets the \p SuperDestReg to the 32 bit super reg of the original
80   /// destination register of the MachineInstr passed in. It returns true if
81   /// that super register is dead just prior to \p OrigMI, and false if not.
82   bool getSuperRegDestIfDead(MachineInstr *OrigMI,
83                              Register &SuperDestReg) const;
84 
85   /// Change the MachineInstr \p MI into the equivalent extending load to 32 bit
86   /// register if it is safe to do so.  Return the replacement instruction if
87   /// OK, otherwise return nullptr.
88   MachineInstr *tryReplaceLoad(unsigned New32BitOpcode, MachineInstr *MI) const;
89 
90   /// Change the MachineInstr \p MI into the equivalent 32-bit copy if it is
91   /// safe to do so.  Return the replacement instruction if OK, otherwise return
92   /// nullptr.
93   MachineInstr *tryReplaceCopy(MachineInstr *MI) const;
94 
95   /// Change the MachineInstr \p MI into the equivalent extend to 32 bit
96   /// register if it is safe to do so.  Return the replacement instruction if
97   /// OK, otherwise return nullptr.
98   MachineInstr *tryReplaceExtend(unsigned New32BitOpcode,
99                                  MachineInstr *MI) const;
100 
101   // Change the MachineInstr \p MI into an eqivalent 32 bit instruction if
102   // possible.  Return the replacement instruction if OK, return nullptr
103   // otherwise.
104   MachineInstr *tryReplaceInstr(MachineInstr *MI, MachineBasicBlock &MBB) const;
105 
106 public:
107   static char ID;
108 
109   StringRef getPassName() const override { return FIXUPBW_DESC; }
110 
111   FixupBWInstPass() : MachineFunctionPass(ID) { }
112 
113   void getAnalysisUsage(AnalysisUsage &AU) const override {
114     AU.addRequired<MachineLoopInfo>(); // Machine loop info is used to
115                                        // guide some heuristics.
116     MachineFunctionPass::getAnalysisUsage(AU);
117   }
118 
119   /// Loop over all of the basic blocks, replacing byte and word instructions by
120   /// equivalent 32 bit instructions where performance or code size can be
121   /// improved.
122   bool runOnMachineFunction(MachineFunction &MF) override;
123 
124   MachineFunctionProperties getRequiredProperties() const override {
125     return MachineFunctionProperties().set(
126         MachineFunctionProperties::Property::NoVRegs);
127   }
128 
129 private:
130   MachineFunction *MF;
131 
132   /// Machine instruction info used throughout the class.
133   const X86InstrInfo *TII;
134 
135   /// Local member for function's OptForSize attribute.
136   bool OptForSize;
137 
138   /// Machine loop info used for guiding some heruistics.
139   MachineLoopInfo *MLI;
140 
141   /// Register Liveness information after the current instruction.
142   LivePhysRegs LiveRegs;
143 };
144 char FixupBWInstPass::ID = 0;
145 }
146 
147 INITIALIZE_PASS(FixupBWInstPass, FIXUPBW_NAME, FIXUPBW_DESC, false, false)
148 
149 FunctionPass *llvm::createX86FixupBWInsts() { return new FixupBWInstPass(); }
150 
151 bool FixupBWInstPass::runOnMachineFunction(MachineFunction &MF) {
152   if (!FixupBWInsts || skipFunction(MF.getFunction()))
153     return false;
154 
155   this->MF = &MF;
156   TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
157   OptForSize = MF.getFunction().hasOptSize();
158   MLI = &getAnalysis<MachineLoopInfo>();
159   LiveRegs.init(TII->getRegisterInfo());
160 
161   LLVM_DEBUG(dbgs() << "Start X86FixupBWInsts\n";);
162 
163   // Process all basic blocks.
164   for (auto &MBB : MF)
165     processBasicBlock(MF, MBB);
166 
167   LLVM_DEBUG(dbgs() << "End X86FixupBWInsts\n";);
168 
169   return true;
170 }
171 
172 /// Check if after \p OrigMI the only portion of super register
173 /// of the destination register of \p OrigMI that is alive is that
174 /// destination register.
175 ///
176 /// If so, return that super register in \p SuperDestReg.
177 bool FixupBWInstPass::getSuperRegDestIfDead(MachineInstr *OrigMI,
178                                             Register &SuperDestReg) const {
179   auto *TRI = &TII->getRegisterInfo();
180 
181   Register OrigDestReg = OrigMI->getOperand(0).getReg();
182   SuperDestReg = getX86SubSuperRegister(OrigDestReg, 32);
183 
184   const auto SubRegIdx = TRI->getSubRegIndex(SuperDestReg, OrigDestReg);
185 
186   // Make sure that the sub-register that this instruction has as its
187   // destination is the lowest order sub-register of the super-register.
188   // If it isn't, then the register isn't really dead even if the
189   // super-register is considered dead.
190   if (SubRegIdx == X86::sub_8bit_hi)
191     return false;
192 
193   // If neither the destination-super register nor any applicable subregisters
194   // are live after this instruction, then the super register is safe to use.
195   if (!LiveRegs.contains(SuperDestReg)) {
196     // If the original destination register was not the low 8-bit subregister
197     // then the super register check is sufficient.
198     if (SubRegIdx != X86::sub_8bit)
199       return true;
200     // If the original destination register was the low 8-bit subregister and
201     // we also need to check the 16-bit subregister and the high 8-bit
202     // subregister.
203     if (!LiveRegs.contains(getX86SubSuperRegister(OrigDestReg, 16)) &&
204         !LiveRegs.contains(getX86SubSuperRegister(SuperDestReg, 8,
205                                                   /*High=*/true)))
206       return true;
207     // Otherwise, we have a little more checking to do.
208   }
209 
210   // If we get here, the super-register destination (or some part of it) is
211   // marked as live after the original instruction.
212   //
213   // The X86 backend does not have subregister liveness tracking enabled,
214   // so liveness information might be overly conservative. Specifically, the
215   // super register might be marked as live because it is implicitly defined
216   // by the instruction we are examining.
217   //
218   // However, for some specific instructions (this pass only cares about MOVs)
219   // we can produce more precise results by analysing that MOV's operands.
220   //
221   // Indeed, if super-register is not live before the mov it means that it
222   // was originally <read-undef> and so we are free to modify these
223   // undef upper bits. That may happen in case where the use is in another MBB
224   // and the vreg/physreg corresponding to the move has higher width than
225   // necessary (e.g. due to register coalescing with a "truncate" copy).
226   // So, we would like to handle patterns like this:
227   //
228   //   %bb.2: derived from LLVM BB %if.then
229   //   Live Ins: %rdi
230   //   Predecessors according to CFG: %bb.0
231   //   %ax<def> = MOV16rm killed %rdi, 1, %noreg, 0, %noreg, implicit-def %eax
232   //                                 ; No implicit %eax
233   //   Successors according to CFG: %bb.3(?%)
234   //
235   //   %bb.3: derived from LLVM BB %if.end
236   //   Live Ins: %eax                            Only %ax is actually live
237   //   Predecessors according to CFG: %bb.2 %bb.1
238   //   %ax = KILL %ax, implicit killed %eax
239   //   RET 0, %ax
240   unsigned Opc = OrigMI->getOpcode(); (void)Opc;
241   // These are the opcodes currently known to work with the code below, if
242   // something // else will be added we need to ensure that new opcode has the
243   // same properties.
244   if (Opc != X86::MOV8rm && Opc != X86::MOV16rm && Opc != X86::MOV8rr &&
245       Opc != X86::MOV16rr)
246     return false;
247 
248   bool IsDefined = false;
249   for (auto &MO: OrigMI->implicit_operands()) {
250     if (!MO.isReg())
251       continue;
252 
253     assert((MO.isDef() || MO.isUse()) && "Expected Def or Use only!");
254 
255     if (MO.isDef() && TRI->isSuperRegisterEq(OrigDestReg, MO.getReg()))
256       IsDefined = true;
257 
258     // If MO is a use of any part of the destination register but is not equal
259     // to OrigDestReg or one of its subregisters, we cannot use SuperDestReg.
260     // For example, if OrigDestReg is %al then an implicit use of %ah, %ax,
261     // %eax, or %rax will prevent us from using the %eax register.
262     if (MO.isUse() && !TRI->isSubRegisterEq(OrigDestReg, MO.getReg()) &&
263         TRI->regsOverlap(SuperDestReg, MO.getReg()))
264       return false;
265   }
266   // Reg is not Imp-def'ed -> it's live both before/after the instruction.
267   if (!IsDefined)
268     return false;
269 
270   // Otherwise, the Reg is not live before the MI and the MOV can't
271   // make it really live, so it's in fact dead even after the MI.
272   return true;
273 }
274 
275 MachineInstr *FixupBWInstPass::tryReplaceLoad(unsigned New32BitOpcode,
276                                               MachineInstr *MI) const {
277   Register NewDestReg;
278 
279   // We are going to try to rewrite this load to a larger zero-extending
280   // load.  This is safe if all portions of the 32 bit super-register
281   // of the original destination register, except for the original destination
282   // register are dead. getSuperRegDestIfDead checks that.
283   if (!getSuperRegDestIfDead(MI, NewDestReg))
284     return nullptr;
285 
286   // Safe to change the instruction.
287   MachineInstrBuilder MIB =
288       BuildMI(*MF, MI->getDebugLoc(), TII->get(New32BitOpcode), NewDestReg);
289 
290   unsigned NumArgs = MI->getNumOperands();
291   for (unsigned i = 1; i < NumArgs; ++i)
292     MIB.add(MI->getOperand(i));
293 
294   MIB.setMemRefs(MI->memoperands());
295 
296   return MIB;
297 }
298 
299 MachineInstr *FixupBWInstPass::tryReplaceCopy(MachineInstr *MI) const {
300   assert(MI->getNumExplicitOperands() == 2);
301   auto &OldDest = MI->getOperand(0);
302   auto &OldSrc = MI->getOperand(1);
303 
304   Register NewDestReg;
305   if (!getSuperRegDestIfDead(MI, NewDestReg))
306     return nullptr;
307 
308   Register NewSrcReg = getX86SubSuperRegister(OldSrc.getReg(), 32);
309 
310   // This is only correct if we access the same subregister index: otherwise,
311   // we could try to replace "movb %ah, %al" with "movl %eax, %eax".
312   auto *TRI = &TII->getRegisterInfo();
313   if (TRI->getSubRegIndex(NewSrcReg, OldSrc.getReg()) !=
314       TRI->getSubRegIndex(NewDestReg, OldDest.getReg()))
315     return nullptr;
316 
317   // Safe to change the instruction.
318   // Don't set src flags, as we don't know if we're also killing the superreg.
319   // However, the superregister might not be defined; make it explicit that
320   // we don't care about the higher bits by reading it as Undef, and adding
321   // an imp-use on the original subregister.
322   MachineInstrBuilder MIB =
323       BuildMI(*MF, MI->getDebugLoc(), TII->get(X86::MOV32rr), NewDestReg)
324           .addReg(NewSrcReg, RegState::Undef)
325           .addReg(OldSrc.getReg(), RegState::Implicit);
326 
327   // Drop imp-defs/uses that would be redundant with the new def/use.
328   for (auto &Op : MI->implicit_operands())
329     if (Op.getReg() != (Op.isDef() ? NewDestReg : NewSrcReg))
330       MIB.add(Op);
331 
332   return MIB;
333 }
334 
335 MachineInstr *FixupBWInstPass::tryReplaceExtend(unsigned New32BitOpcode,
336                                                 MachineInstr *MI) const {
337   Register NewDestReg;
338   if (!getSuperRegDestIfDead(MI, NewDestReg))
339     return nullptr;
340 
341   // Don't interfere with formation of CBW instructions which should be a
342   // shorter encoding than even the MOVSX32rr8. It's also immunte to partial
343   // merge issues on Intel CPUs.
344   if (MI->getOpcode() == X86::MOVSX16rr8 &&
345       MI->getOperand(0).getReg() == X86::AX &&
346       MI->getOperand(1).getReg() == X86::AL)
347     return nullptr;
348 
349   // Safe to change the instruction.
350   MachineInstrBuilder MIB =
351       BuildMI(*MF, MI->getDebugLoc(), TII->get(New32BitOpcode), NewDestReg);
352 
353   unsigned NumArgs = MI->getNumOperands();
354   for (unsigned i = 1; i < NumArgs; ++i)
355     MIB.add(MI->getOperand(i));
356 
357   MIB.setMemRefs(MI->memoperands());
358 
359   return MIB;
360 }
361 
362 MachineInstr *FixupBWInstPass::tryReplaceInstr(MachineInstr *MI,
363                                                MachineBasicBlock &MBB) const {
364   // See if this is an instruction of the type we are currently looking for.
365   switch (MI->getOpcode()) {
366 
367   case X86::MOV8rm:
368     // Only replace 8 bit loads with the zero extending versions if
369     // in an inner most loop and not optimizing for size. This takes
370     // an extra byte to encode, and provides limited performance upside.
371     if (MachineLoop *ML = MLI->getLoopFor(&MBB))
372       if (ML->begin() == ML->end() && !OptForSize)
373         return tryReplaceLoad(X86::MOVZX32rm8, MI);
374     break;
375 
376   case X86::MOV16rm:
377     // Always try to replace 16 bit load with 32 bit zero extending.
378     // Code size is the same, and there is sometimes a perf advantage
379     // from eliminating a false dependence on the upper portion of
380     // the register.
381     return tryReplaceLoad(X86::MOVZX32rm16, MI);
382 
383   case X86::MOV8rr:
384   case X86::MOV16rr:
385     // Always try to replace 8/16 bit copies with a 32 bit copy.
386     // Code size is either less (16) or equal (8), and there is sometimes a
387     // perf advantage from eliminating a false dependence on the upper portion
388     // of the register.
389     return tryReplaceCopy(MI);
390 
391   case X86::MOVSX16rr8:
392     return tryReplaceExtend(X86::MOVSX32rr8, MI);
393   case X86::MOVSX16rm8:
394     return tryReplaceExtend(X86::MOVSX32rm8, MI);
395   case X86::MOVZX16rr8:
396     return tryReplaceExtend(X86::MOVZX32rr8, MI);
397   case X86::MOVZX16rm8:
398     return tryReplaceExtend(X86::MOVZX32rm8, MI);
399 
400   default:
401     // nothing to do here.
402     break;
403   }
404 
405   return nullptr;
406 }
407 
408 void FixupBWInstPass::processBasicBlock(MachineFunction &MF,
409                                         MachineBasicBlock &MBB) {
410 
411   // This algorithm doesn't delete the instructions it is replacing
412   // right away.  By leaving the existing instructions in place, the
413   // register liveness information doesn't change, and this makes the
414   // analysis that goes on be better than if the replaced instructions
415   // were immediately removed.
416   //
417   // This algorithm always creates a replacement instruction
418   // and notes that and the original in a data structure, until the
419   // whole BB has been analyzed.  This keeps the replacement instructions
420   // from making it seem as if the larger register might be live.
421   SmallVector<std::pair<MachineInstr *, MachineInstr *>, 8> MIReplacements;
422 
423   // Start computing liveness for this block. We iterate from the end to be able
424   // to update this for each instruction.
425   LiveRegs.clear();
426   // We run after PEI, so we need to AddPristinesAndCSRs.
427   LiveRegs.addLiveOuts(MBB);
428 
429   for (auto I = MBB.rbegin(); I != MBB.rend(); ++I) {
430     MachineInstr *MI = &*I;
431 
432     if (MachineInstr *NewMI = tryReplaceInstr(MI, MBB))
433       MIReplacements.push_back(std::make_pair(MI, NewMI));
434 
435     // We're done with this instruction, update liveness for the next one.
436     LiveRegs.stepBackward(*MI);
437   }
438 
439   while (!MIReplacements.empty()) {
440     MachineInstr *MI = MIReplacements.back().first;
441     MachineInstr *NewMI = MIReplacements.back().second;
442     MIReplacements.pop_back();
443     MBB.insert(MI, NewMI);
444     MBB.erase(MI);
445   }
446 }
447