xref: /freebsd/contrib/llvm-project/llvm/lib/Target/X86/X86FixupBWInsts.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===-- X86FixupBWInsts.cpp - Fixup Byte or Word instructions -----------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric /// \file
90b57cec5SDimitry Andric /// This file defines the pass that looks through the machine instructions
100b57cec5SDimitry Andric /// late in the compilation, and finds byte or word instructions that
110b57cec5SDimitry Andric /// can be profitably replaced with 32 bit instructions that give equivalent
120b57cec5SDimitry Andric /// results for the bits of the results that are used. There are two possible
130b57cec5SDimitry Andric /// reasons to do this.
140b57cec5SDimitry Andric ///
150b57cec5SDimitry Andric /// One reason is to avoid false-dependences on the upper portions
160b57cec5SDimitry Andric /// of the registers.  Only instructions that have a destination register
170b57cec5SDimitry Andric /// which is not in any of the source registers can be affected by this.
180b57cec5SDimitry Andric /// Any instruction where one of the source registers is also the destination
190b57cec5SDimitry Andric /// register is unaffected, because it has a true dependence on the source
200b57cec5SDimitry Andric /// register already.  So, this consideration primarily affects load
210b57cec5SDimitry Andric /// instructions and register-to-register moves.  It would
220b57cec5SDimitry Andric /// seem like cmov(s) would also be affected, but because of the way cmov is
230b57cec5SDimitry Andric /// really implemented by most machines as reading both the destination and
240b57cec5SDimitry Andric /// and source registers, and then "merging" the two based on a condition,
250b57cec5SDimitry Andric /// it really already should be considered as having a true dependence on the
260b57cec5SDimitry Andric /// destination register as well.
270b57cec5SDimitry Andric ///
280b57cec5SDimitry Andric /// The other reason to do this is for potential code size savings.  Word
290b57cec5SDimitry Andric /// operations need an extra override byte compared to their 32 bit
300b57cec5SDimitry Andric /// versions. So this can convert many word operations to their larger
310b57cec5SDimitry Andric /// size, saving a byte in encoding. This could introduce partial register
320b57cec5SDimitry Andric /// dependences where none existed however.  As an example take:
330b57cec5SDimitry Andric ///   orw  ax, $0x1000
340b57cec5SDimitry Andric ///   addw ax, $3
350b57cec5SDimitry Andric /// now if this were to get transformed into
360b57cec5SDimitry Andric ///   orw  ax, $1000
370b57cec5SDimitry Andric ///   addl eax, $3
380b57cec5SDimitry Andric /// because the addl encodes shorter than the addw, this would introduce
390b57cec5SDimitry Andric /// a use of a register that was only partially written earlier.  On older
400b57cec5SDimitry Andric /// Intel processors this can be quite a performance penalty, so this should
410b57cec5SDimitry Andric /// probably only be done when it can be proven that a new partial dependence
420b57cec5SDimitry Andric /// wouldn't be created, or when your know a newer processor is being
430b57cec5SDimitry Andric /// targeted, or when optimizing for minimum code size.
440b57cec5SDimitry Andric ///
450b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
460b57cec5SDimitry Andric 
470b57cec5SDimitry Andric #include "X86.h"
480b57cec5SDimitry Andric #include "X86InstrInfo.h"
490b57cec5SDimitry Andric #include "X86Subtarget.h"
500b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
51480093f4SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
52480093f4SDimitry Andric #include "llvm/CodeGen/LazyMachineBlockFrequencyInfo.h"
535f757f3fSDimitry Andric #include "llvm/CodeGen/LiveRegUnits.h"
540b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
550b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
560b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
57480093f4SDimitry Andric #include "llvm/CodeGen/MachineSizeOpts.h"
580b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h"
590b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
600b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
610b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
620b57cec5SDimitry Andric using namespace llvm;
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric #define FIXUPBW_DESC "X86 Byte/Word Instruction Fixup"
650b57cec5SDimitry Andric #define FIXUPBW_NAME "x86-fixup-bw-insts"
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric #define DEBUG_TYPE FIXUPBW_NAME
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric // Option to allow this optimization pass to have fine-grained control.
700b57cec5SDimitry Andric static cl::opt<bool>
710b57cec5SDimitry Andric     FixupBWInsts("fixup-byte-word-insts",
720b57cec5SDimitry Andric                  cl::desc("Change byte and word instructions to larger sizes"),
730b57cec5SDimitry Andric                  cl::init(true), cl::Hidden);
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric namespace {
760b57cec5SDimitry Andric class FixupBWInstPass : public MachineFunctionPass {
770b57cec5SDimitry Andric   /// Loop over all of the instructions in the basic block replacing applicable
780b57cec5SDimitry Andric   /// byte or word instructions with better alternatives.
790b57cec5SDimitry Andric   void processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
800b57cec5SDimitry Andric 
815f757f3fSDimitry Andric   /// This returns the 32 bit super reg of the original destination register of
825f757f3fSDimitry Andric   /// the MachineInstr passed in, if that super register is dead just prior to
835f757f3fSDimitry Andric   /// \p OrigMI. Otherwise it returns Register().
845f757f3fSDimitry Andric   Register getSuperRegDestIfDead(MachineInstr *OrigMI) const;
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric   /// Change the MachineInstr \p MI into the equivalent extending load to 32 bit
870b57cec5SDimitry Andric   /// register if it is safe to do so.  Return the replacement instruction if
880b57cec5SDimitry Andric   /// OK, otherwise return nullptr.
890b57cec5SDimitry Andric   MachineInstr *tryReplaceLoad(unsigned New32BitOpcode, MachineInstr *MI) const;
900b57cec5SDimitry Andric 
910b57cec5SDimitry Andric   /// Change the MachineInstr \p MI into the equivalent 32-bit copy if it is
920b57cec5SDimitry Andric   /// safe to do so.  Return the replacement instruction if OK, otherwise return
930b57cec5SDimitry Andric   /// nullptr.
940b57cec5SDimitry Andric   MachineInstr *tryReplaceCopy(MachineInstr *MI) const;
950b57cec5SDimitry Andric 
968bcb0991SDimitry Andric   /// Change the MachineInstr \p MI into the equivalent extend to 32 bit
978bcb0991SDimitry Andric   /// register if it is safe to do so.  Return the replacement instruction if
988bcb0991SDimitry Andric   /// OK, otherwise return nullptr.
998bcb0991SDimitry Andric   MachineInstr *tryReplaceExtend(unsigned New32BitOpcode,
1008bcb0991SDimitry Andric                                  MachineInstr *MI) const;
1018bcb0991SDimitry Andric 
1020b57cec5SDimitry Andric   // Change the MachineInstr \p MI into an eqivalent 32 bit instruction if
1030b57cec5SDimitry Andric   // possible.  Return the replacement instruction if OK, return nullptr
1040b57cec5SDimitry Andric   // otherwise.
1050b57cec5SDimitry Andric   MachineInstr *tryReplaceInstr(MachineInstr *MI, MachineBasicBlock &MBB) const;
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric public:
1080b57cec5SDimitry Andric   static char ID;
1090b57cec5SDimitry Andric 
getPassName() const1100b57cec5SDimitry Andric   StringRef getPassName() const override { return FIXUPBW_DESC; }
1110b57cec5SDimitry Andric 
FixupBWInstPass()1120b57cec5SDimitry Andric   FixupBWInstPass() : MachineFunctionPass(ID) { }
1130b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const1140b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
115480093f4SDimitry Andric     AU.addRequired<ProfileSummaryInfoWrapperPass>();
116480093f4SDimitry Andric     AU.addRequired<LazyMachineBlockFrequencyInfoPass>();
1170b57cec5SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
1180b57cec5SDimitry Andric   }
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric   /// Loop over all of the basic blocks, replacing byte and word instructions by
1210b57cec5SDimitry Andric   /// equivalent 32 bit instructions where performance or code size can be
1220b57cec5SDimitry Andric   /// improved.
1230b57cec5SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
1240b57cec5SDimitry Andric 
getRequiredProperties() const1250b57cec5SDimitry Andric   MachineFunctionProperties getRequiredProperties() const override {
1260b57cec5SDimitry Andric     return MachineFunctionProperties().set(
1270b57cec5SDimitry Andric         MachineFunctionProperties::Property::NoVRegs);
1280b57cec5SDimitry Andric   }
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric private:
131480093f4SDimitry Andric   MachineFunction *MF = nullptr;
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   /// Machine instruction info used throughout the class.
134480093f4SDimitry Andric   const X86InstrInfo *TII = nullptr;
1350b57cec5SDimitry Andric 
136fe6060f1SDimitry Andric   const TargetRegisterInfo *TRI = nullptr;
137fe6060f1SDimitry Andric 
1380b57cec5SDimitry Andric   /// Local member for function's OptForSize attribute.
139480093f4SDimitry Andric   bool OptForSize = false;
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric   /// Register Liveness information after the current instruction.
1425f757f3fSDimitry Andric   LiveRegUnits LiveUnits;
143480093f4SDimitry Andric 
14406c3fb27SDimitry Andric   ProfileSummaryInfo *PSI = nullptr;
14506c3fb27SDimitry Andric   MachineBlockFrequencyInfo *MBFI = nullptr;
1460b57cec5SDimitry Andric };
1470b57cec5SDimitry Andric char FixupBWInstPass::ID = 0;
1480b57cec5SDimitry Andric }
1490b57cec5SDimitry Andric 
INITIALIZE_PASS(FixupBWInstPass,FIXUPBW_NAME,FIXUPBW_DESC,false,false)1500b57cec5SDimitry Andric INITIALIZE_PASS(FixupBWInstPass, FIXUPBW_NAME, FIXUPBW_DESC, false, false)
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric FunctionPass *llvm::createX86FixupBWInsts() { return new FixupBWInstPass(); }
1530b57cec5SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)1540b57cec5SDimitry Andric bool FixupBWInstPass::runOnMachineFunction(MachineFunction &MF) {
1550b57cec5SDimitry Andric   if (!FixupBWInsts || skipFunction(MF.getFunction()))
1560b57cec5SDimitry Andric     return false;
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric   this->MF = &MF;
1590b57cec5SDimitry Andric   TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
160fe6060f1SDimitry Andric   TRI = MF.getRegInfo().getTargetRegisterInfo();
161480093f4SDimitry Andric   PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
162480093f4SDimitry Andric   MBFI = (PSI && PSI->hasProfileSummary()) ?
163480093f4SDimitry Andric          &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI() :
164480093f4SDimitry Andric          nullptr;
1655f757f3fSDimitry Andric   LiveUnits.init(TII->getRegisterInfo());
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Start X86FixupBWInsts\n";);
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric   // Process all basic blocks.
1700b57cec5SDimitry Andric   for (auto &MBB : MF)
1710b57cec5SDimitry Andric     processBasicBlock(MF, MBB);
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "End X86FixupBWInsts\n";);
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   return true;
1760b57cec5SDimitry Andric }
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric /// Check if after \p OrigMI the only portion of super register
1790b57cec5SDimitry Andric /// of the destination register of \p OrigMI that is alive is that
1800b57cec5SDimitry Andric /// destination register.
1810b57cec5SDimitry Andric ///
1820b57cec5SDimitry Andric /// If so, return that super register in \p SuperDestReg.
getSuperRegDestIfDead(MachineInstr * OrigMI) const1835f757f3fSDimitry Andric Register FixupBWInstPass::getSuperRegDestIfDead(MachineInstr *OrigMI) const {
184e8d8bef9SDimitry Andric   const X86RegisterInfo *TRI = &TII->getRegisterInfo();
1858bcb0991SDimitry Andric   Register OrigDestReg = OrigMI->getOperand(0).getReg();
1865f757f3fSDimitry Andric   Register SuperDestReg = getX86SubSuperRegister(OrigDestReg, 32);
18706c3fb27SDimitry Andric   assert(SuperDestReg.isValid() && "Invalid Operand");
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric   const auto SubRegIdx = TRI->getSubRegIndex(SuperDestReg, OrigDestReg);
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric   // Make sure that the sub-register that this instruction has as its
1920b57cec5SDimitry Andric   // destination is the lowest order sub-register of the super-register.
1930b57cec5SDimitry Andric   // If it isn't, then the register isn't really dead even if the
1940b57cec5SDimitry Andric   // super-register is considered dead.
1950b57cec5SDimitry Andric   if (SubRegIdx == X86::sub_8bit_hi)
1965f757f3fSDimitry Andric     return Register();
1970b57cec5SDimitry Andric 
1985f757f3fSDimitry Andric   // Test all regunits of the super register that are not part of the
1995f757f3fSDimitry Andric   // sub register. If none of them are live then the super register is safe to
2005f757f3fSDimitry Andric   // use.
2015f757f3fSDimitry Andric   bool SuperIsLive = false;
2025f757f3fSDimitry Andric   auto Range = TRI->regunits(OrigDestReg);
2035f757f3fSDimitry Andric   MCRegUnitIterator I = Range.begin(), E = Range.end();
2045f757f3fSDimitry Andric   for (MCRegUnit S : TRI->regunits(SuperDestReg)) {
2055f757f3fSDimitry Andric     I = std::lower_bound(I, E, S);
2065f757f3fSDimitry Andric     if ((I == E || *I > S) && LiveUnits.getBitVector().test(S)) {
2075f757f3fSDimitry Andric       SuperIsLive = true;
2085f757f3fSDimitry Andric       break;
2090b57cec5SDimitry Andric     }
2105f757f3fSDimitry Andric   }
2115f757f3fSDimitry Andric   if (!SuperIsLive)
2125f757f3fSDimitry Andric     return SuperDestReg;
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric   // If we get here, the super-register destination (or some part of it) is
2150b57cec5SDimitry Andric   // marked as live after the original instruction.
2160b57cec5SDimitry Andric   //
2170b57cec5SDimitry Andric   // The X86 backend does not have subregister liveness tracking enabled,
2180b57cec5SDimitry Andric   // so liveness information might be overly conservative. Specifically, the
2190b57cec5SDimitry Andric   // super register might be marked as live because it is implicitly defined
2200b57cec5SDimitry Andric   // by the instruction we are examining.
2210b57cec5SDimitry Andric   //
2220b57cec5SDimitry Andric   // However, for some specific instructions (this pass only cares about MOVs)
2230b57cec5SDimitry Andric   // we can produce more precise results by analysing that MOV's operands.
2240b57cec5SDimitry Andric   //
2250b57cec5SDimitry Andric   // Indeed, if super-register is not live before the mov it means that it
2260b57cec5SDimitry Andric   // was originally <read-undef> and so we are free to modify these
2270b57cec5SDimitry Andric   // undef upper bits. That may happen in case where the use is in another MBB
2280b57cec5SDimitry Andric   // and the vreg/physreg corresponding to the move has higher width than
2290b57cec5SDimitry Andric   // necessary (e.g. due to register coalescing with a "truncate" copy).
2300b57cec5SDimitry Andric   // So, we would like to handle patterns like this:
2310b57cec5SDimitry Andric   //
2320b57cec5SDimitry Andric   //   %bb.2: derived from LLVM BB %if.then
2330b57cec5SDimitry Andric   //   Live Ins: %rdi
2340b57cec5SDimitry Andric   //   Predecessors according to CFG: %bb.0
2350b57cec5SDimitry Andric   //   %ax<def> = MOV16rm killed %rdi, 1, %noreg, 0, %noreg, implicit-def %eax
2360b57cec5SDimitry Andric   //                                 ; No implicit %eax
2370b57cec5SDimitry Andric   //   Successors according to CFG: %bb.3(?%)
2380b57cec5SDimitry Andric   //
2390b57cec5SDimitry Andric   //   %bb.3: derived from LLVM BB %if.end
2400b57cec5SDimitry Andric   //   Live Ins: %eax                            Only %ax is actually live
2410b57cec5SDimitry Andric   //   Predecessors according to CFG: %bb.2 %bb.1
2420b57cec5SDimitry Andric   //   %ax = KILL %ax, implicit killed %eax
2430b57cec5SDimitry Andric   //   RET 0, %ax
244*0fca6ea1SDimitry Andric   unsigned Opc = OrigMI->getOpcode();
2458bcb0991SDimitry Andric   // These are the opcodes currently known to work with the code below, if
2468bcb0991SDimitry Andric   // something // else will be added we need to ensure that new opcode has the
2478bcb0991SDimitry Andric   // same properties.
2488bcb0991SDimitry Andric   if (Opc != X86::MOV8rm && Opc != X86::MOV16rm && Opc != X86::MOV8rr &&
2498bcb0991SDimitry Andric       Opc != X86::MOV16rr)
2505f757f3fSDimitry Andric     return Register();
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric   bool IsDefined = false;
2530b57cec5SDimitry Andric   for (auto &MO: OrigMI->implicit_operands()) {
2540b57cec5SDimitry Andric     if (!MO.isReg())
2550b57cec5SDimitry Andric       continue;
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric     if (MO.isDef() && TRI->isSuperRegisterEq(OrigDestReg, MO.getReg()))
2580b57cec5SDimitry Andric       IsDefined = true;
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric     // If MO is a use of any part of the destination register but is not equal
2610b57cec5SDimitry Andric     // to OrigDestReg or one of its subregisters, we cannot use SuperDestReg.
2620b57cec5SDimitry Andric     // For example, if OrigDestReg is %al then an implicit use of %ah, %ax,
2630b57cec5SDimitry Andric     // %eax, or %rax will prevent us from using the %eax register.
2640b57cec5SDimitry Andric     if (MO.isUse() && !TRI->isSubRegisterEq(OrigDestReg, MO.getReg()) &&
2650b57cec5SDimitry Andric         TRI->regsOverlap(SuperDestReg, MO.getReg()))
2665f757f3fSDimitry Andric       return Register();
2670b57cec5SDimitry Andric   }
2680b57cec5SDimitry Andric   // Reg is not Imp-def'ed -> it's live both before/after the instruction.
2690b57cec5SDimitry Andric   if (!IsDefined)
2705f757f3fSDimitry Andric     return Register();
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric   // Otherwise, the Reg is not live before the MI and the MOV can't
2730b57cec5SDimitry Andric   // make it really live, so it's in fact dead even after the MI.
2745f757f3fSDimitry Andric   return SuperDestReg;
2750b57cec5SDimitry Andric }
2760b57cec5SDimitry Andric 
tryReplaceLoad(unsigned New32BitOpcode,MachineInstr * MI) const2770b57cec5SDimitry Andric MachineInstr *FixupBWInstPass::tryReplaceLoad(unsigned New32BitOpcode,
2780b57cec5SDimitry Andric                                               MachineInstr *MI) const {
2790b57cec5SDimitry Andric   // We are going to try to rewrite this load to a larger zero-extending
2800b57cec5SDimitry Andric   // load.  This is safe if all portions of the 32 bit super-register
2810b57cec5SDimitry Andric   // of the original destination register, except for the original destination
2820b57cec5SDimitry Andric   // register are dead. getSuperRegDestIfDead checks that.
2835f757f3fSDimitry Andric   Register NewDestReg = getSuperRegDestIfDead(MI);
2845f757f3fSDimitry Andric   if (!NewDestReg)
2850b57cec5SDimitry Andric     return nullptr;
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric   // Safe to change the instruction.
2880b57cec5SDimitry Andric   MachineInstrBuilder MIB =
28906c3fb27SDimitry Andric       BuildMI(*MF, MIMetadata(*MI), TII->get(New32BitOpcode), NewDestReg);
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric   unsigned NumArgs = MI->getNumOperands();
2920b57cec5SDimitry Andric   for (unsigned i = 1; i < NumArgs; ++i)
2930b57cec5SDimitry Andric     MIB.add(MI->getOperand(i));
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric   MIB.setMemRefs(MI->memoperands());
2960b57cec5SDimitry Andric 
297fe6060f1SDimitry Andric   // If it was debug tracked, record a substitution.
298fe6060f1SDimitry Andric   if (unsigned OldInstrNum = MI->peekDebugInstrNum()) {
299fe6060f1SDimitry Andric     unsigned Subreg = TRI->getSubRegIndex(MIB->getOperand(0).getReg(),
300fe6060f1SDimitry Andric                                           MI->getOperand(0).getReg());
301fe6060f1SDimitry Andric     unsigned NewInstrNum = MIB->getDebugInstrNum(*MF);
302fe6060f1SDimitry Andric     MF->makeDebugValueSubstitution({OldInstrNum, 0}, {NewInstrNum, 0}, Subreg);
303fe6060f1SDimitry Andric   }
304fe6060f1SDimitry Andric 
3050b57cec5SDimitry Andric   return MIB;
3060b57cec5SDimitry Andric }
3070b57cec5SDimitry Andric 
tryReplaceCopy(MachineInstr * MI) const3080b57cec5SDimitry Andric MachineInstr *FixupBWInstPass::tryReplaceCopy(MachineInstr *MI) const {
3090b57cec5SDimitry Andric   assert(MI->getNumExplicitOperands() == 2);
3100b57cec5SDimitry Andric   auto &OldDest = MI->getOperand(0);
3110b57cec5SDimitry Andric   auto &OldSrc = MI->getOperand(1);
3120b57cec5SDimitry Andric 
3135f757f3fSDimitry Andric   Register NewDestReg = getSuperRegDestIfDead(MI);
3145f757f3fSDimitry Andric   if (!NewDestReg)
3150b57cec5SDimitry Andric     return nullptr;
3160b57cec5SDimitry Andric 
3178bcb0991SDimitry Andric   Register NewSrcReg = getX86SubSuperRegister(OldSrc.getReg(), 32);
31806c3fb27SDimitry Andric   assert(NewSrcReg.isValid() && "Invalid Operand");
3190b57cec5SDimitry Andric 
3200b57cec5SDimitry Andric   // This is only correct if we access the same subregister index: otherwise,
3210b57cec5SDimitry Andric   // we could try to replace "movb %ah, %al" with "movl %eax, %eax".
322e8d8bef9SDimitry Andric   const X86RegisterInfo *TRI = &TII->getRegisterInfo();
3230b57cec5SDimitry Andric   if (TRI->getSubRegIndex(NewSrcReg, OldSrc.getReg()) !=
3240b57cec5SDimitry Andric       TRI->getSubRegIndex(NewDestReg, OldDest.getReg()))
3250b57cec5SDimitry Andric     return nullptr;
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric   // Safe to change the instruction.
3280b57cec5SDimitry Andric   // Don't set src flags, as we don't know if we're also killing the superreg.
3290b57cec5SDimitry Andric   // However, the superregister might not be defined; make it explicit that
3300b57cec5SDimitry Andric   // we don't care about the higher bits by reading it as Undef, and adding
3310b57cec5SDimitry Andric   // an imp-use on the original subregister.
3320b57cec5SDimitry Andric   MachineInstrBuilder MIB =
33306c3fb27SDimitry Andric       BuildMI(*MF, MIMetadata(*MI), TII->get(X86::MOV32rr), NewDestReg)
3340b57cec5SDimitry Andric           .addReg(NewSrcReg, RegState::Undef)
3350b57cec5SDimitry Andric           .addReg(OldSrc.getReg(), RegState::Implicit);
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric   // Drop imp-defs/uses that would be redundant with the new def/use.
3380b57cec5SDimitry Andric   for (auto &Op : MI->implicit_operands())
3390b57cec5SDimitry Andric     if (Op.getReg() != (Op.isDef() ? NewDestReg : NewSrcReg))
3400b57cec5SDimitry Andric       MIB.add(Op);
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric   return MIB;
3430b57cec5SDimitry Andric }
3440b57cec5SDimitry Andric 
tryReplaceExtend(unsigned New32BitOpcode,MachineInstr * MI) const3458bcb0991SDimitry Andric MachineInstr *FixupBWInstPass::tryReplaceExtend(unsigned New32BitOpcode,
3468bcb0991SDimitry Andric                                                 MachineInstr *MI) const {
3475f757f3fSDimitry Andric   Register NewDestReg = getSuperRegDestIfDead(MI);
3485f757f3fSDimitry Andric   if (!NewDestReg)
3498bcb0991SDimitry Andric     return nullptr;
3508bcb0991SDimitry Andric 
3518bcb0991SDimitry Andric   // Don't interfere with formation of CBW instructions which should be a
3525ffd83dbSDimitry Andric   // shorter encoding than even the MOVSX32rr8. It's also immune to partial
3538bcb0991SDimitry Andric   // merge issues on Intel CPUs.
3548bcb0991SDimitry Andric   if (MI->getOpcode() == X86::MOVSX16rr8 &&
3558bcb0991SDimitry Andric       MI->getOperand(0).getReg() == X86::AX &&
3568bcb0991SDimitry Andric       MI->getOperand(1).getReg() == X86::AL)
3578bcb0991SDimitry Andric     return nullptr;
3588bcb0991SDimitry Andric 
3598bcb0991SDimitry Andric   // Safe to change the instruction.
3608bcb0991SDimitry Andric   MachineInstrBuilder MIB =
36106c3fb27SDimitry Andric       BuildMI(*MF, MIMetadata(*MI), TII->get(New32BitOpcode), NewDestReg);
3628bcb0991SDimitry Andric 
3638bcb0991SDimitry Andric   unsigned NumArgs = MI->getNumOperands();
3648bcb0991SDimitry Andric   for (unsigned i = 1; i < NumArgs; ++i)
3658bcb0991SDimitry Andric     MIB.add(MI->getOperand(i));
3668bcb0991SDimitry Andric 
3678bcb0991SDimitry Andric   MIB.setMemRefs(MI->memoperands());
3688bcb0991SDimitry Andric 
369fe6060f1SDimitry Andric   if (unsigned OldInstrNum = MI->peekDebugInstrNum()) {
370fe6060f1SDimitry Andric     unsigned Subreg = TRI->getSubRegIndex(MIB->getOperand(0).getReg(),
371fe6060f1SDimitry Andric                                           MI->getOperand(0).getReg());
372fe6060f1SDimitry Andric     unsigned NewInstrNum = MIB->getDebugInstrNum(*MF);
373fe6060f1SDimitry Andric     MF->makeDebugValueSubstitution({OldInstrNum, 0}, {NewInstrNum, 0}, Subreg);
374fe6060f1SDimitry Andric   }
375fe6060f1SDimitry Andric 
3768bcb0991SDimitry Andric   return MIB;
3778bcb0991SDimitry Andric }
3788bcb0991SDimitry Andric 
tryReplaceInstr(MachineInstr * MI,MachineBasicBlock & MBB) const3790b57cec5SDimitry Andric MachineInstr *FixupBWInstPass::tryReplaceInstr(MachineInstr *MI,
3800b57cec5SDimitry Andric                                                MachineBasicBlock &MBB) const {
3810b57cec5SDimitry Andric   // See if this is an instruction of the type we are currently looking for.
3820b57cec5SDimitry Andric   switch (MI->getOpcode()) {
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric   case X86::MOV8rm:
385fcaf7f86SDimitry Andric     // Replace 8-bit loads with the zero-extending version if not optimizing
386fcaf7f86SDimitry Andric     // for size. The extending op is cheaper across a wide range of uarch and
387fcaf7f86SDimitry Andric     // it avoids a potentially expensive partial register stall. It takes an
388fcaf7f86SDimitry Andric     // extra byte to encode, however, so don't do this when optimizing for size.
389fcaf7f86SDimitry Andric     if (!OptForSize)
3900b57cec5SDimitry Andric       return tryReplaceLoad(X86::MOVZX32rm8, MI);
3910b57cec5SDimitry Andric     break;
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric   case X86::MOV16rm:
3940b57cec5SDimitry Andric     // Always try to replace 16 bit load with 32 bit zero extending.
3950b57cec5SDimitry Andric     // Code size is the same, and there is sometimes a perf advantage
3960b57cec5SDimitry Andric     // from eliminating a false dependence on the upper portion of
3970b57cec5SDimitry Andric     // the register.
3980b57cec5SDimitry Andric     return tryReplaceLoad(X86::MOVZX32rm16, MI);
3990b57cec5SDimitry Andric 
4000b57cec5SDimitry Andric   case X86::MOV8rr:
4010b57cec5SDimitry Andric   case X86::MOV16rr:
4020b57cec5SDimitry Andric     // Always try to replace 8/16 bit copies with a 32 bit copy.
4030b57cec5SDimitry Andric     // Code size is either less (16) or equal (8), and there is sometimes a
4040b57cec5SDimitry Andric     // perf advantage from eliminating a false dependence on the upper portion
4050b57cec5SDimitry Andric     // of the register.
4060b57cec5SDimitry Andric     return tryReplaceCopy(MI);
4070b57cec5SDimitry Andric 
4088bcb0991SDimitry Andric   case X86::MOVSX16rr8:
4098bcb0991SDimitry Andric     return tryReplaceExtend(X86::MOVSX32rr8, MI);
4108bcb0991SDimitry Andric   case X86::MOVSX16rm8:
4118bcb0991SDimitry Andric     return tryReplaceExtend(X86::MOVSX32rm8, MI);
4128bcb0991SDimitry Andric   case X86::MOVZX16rr8:
4138bcb0991SDimitry Andric     return tryReplaceExtend(X86::MOVZX32rr8, MI);
4148bcb0991SDimitry Andric   case X86::MOVZX16rm8:
4158bcb0991SDimitry Andric     return tryReplaceExtend(X86::MOVZX32rm8, MI);
4168bcb0991SDimitry Andric 
4170b57cec5SDimitry Andric   default:
4180b57cec5SDimitry Andric     // nothing to do here.
4190b57cec5SDimitry Andric     break;
4200b57cec5SDimitry Andric   }
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric   return nullptr;
4230b57cec5SDimitry Andric }
4240b57cec5SDimitry Andric 
processBasicBlock(MachineFunction & MF,MachineBasicBlock & MBB)4250b57cec5SDimitry Andric void FixupBWInstPass::processBasicBlock(MachineFunction &MF,
4260b57cec5SDimitry Andric                                         MachineBasicBlock &MBB) {
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   // This algorithm doesn't delete the instructions it is replacing
4290b57cec5SDimitry Andric   // right away.  By leaving the existing instructions in place, the
4300b57cec5SDimitry Andric   // register liveness information doesn't change, and this makes the
4310b57cec5SDimitry Andric   // analysis that goes on be better than if the replaced instructions
4320b57cec5SDimitry Andric   // were immediately removed.
4330b57cec5SDimitry Andric   //
4340b57cec5SDimitry Andric   // This algorithm always creates a replacement instruction
4350b57cec5SDimitry Andric   // and notes that and the original in a data structure, until the
4360b57cec5SDimitry Andric   // whole BB has been analyzed.  This keeps the replacement instructions
4370b57cec5SDimitry Andric   // from making it seem as if the larger register might be live.
4380b57cec5SDimitry Andric   SmallVector<std::pair<MachineInstr *, MachineInstr *>, 8> MIReplacements;
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric   // Start computing liveness for this block. We iterate from the end to be able
4410b57cec5SDimitry Andric   // to update this for each instruction.
4425f757f3fSDimitry Andric   LiveUnits.clear();
4430b57cec5SDimitry Andric   // We run after PEI, so we need to AddPristinesAndCSRs.
4445f757f3fSDimitry Andric   LiveUnits.addLiveOuts(MBB);
4450b57cec5SDimitry Andric 
446480093f4SDimitry Andric   OptForSize = MF.getFunction().hasOptSize() ||
447480093f4SDimitry Andric                llvm::shouldOptimizeForSize(&MBB, PSI, MBFI);
448480093f4SDimitry Andric 
4490eae32dcSDimitry Andric   for (MachineInstr &MI : llvm::reverse(MBB)) {
4500eae32dcSDimitry Andric     if (MachineInstr *NewMI = tryReplaceInstr(&MI, MBB))
4510eae32dcSDimitry Andric       MIReplacements.push_back(std::make_pair(&MI, NewMI));
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric     // We're done with this instruction, update liveness for the next one.
4545f757f3fSDimitry Andric     LiveUnits.stepBackward(MI);
4550b57cec5SDimitry Andric   }
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric   while (!MIReplacements.empty()) {
4580b57cec5SDimitry Andric     MachineInstr *MI = MIReplacements.back().first;
4590b57cec5SDimitry Andric     MachineInstr *NewMI = MIReplacements.back().second;
4600b57cec5SDimitry Andric     MIReplacements.pop_back();
4610b57cec5SDimitry Andric     MBB.insert(MI, NewMI);
4620b57cec5SDimitry Andric     MBB.erase(MI);
4630b57cec5SDimitry Andric   }
4640b57cec5SDimitry Andric }
465