Home | History | Annotate | Line # | Download | only in X86
      1 //===------- X86ExpandPseudo.cpp - Expand pseudo 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 //
      9 // This file contains a pass that expands pseudo instructions into target
     10 // instructions to allow proper scheduling, if-conversion, other late
     11 // optimizations, or simply the encoding of the instructions.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "X86.h"
     16 #include "X86FrameLowering.h"
     17 #include "X86InstrBuilder.h"
     18 #include "X86InstrInfo.h"
     19 #include "X86MachineFunctionInfo.h"
     20 #include "X86Subtarget.h"
     21 #include "llvm/Analysis/EHPersonalities.h"
     22 #include "llvm/CodeGen/MachineFunctionPass.h"
     23 #include "llvm/CodeGen/MachineInstrBuilder.h"
     24 #include "llvm/CodeGen/Passes.h" // For IDs of passes that are preserved.
     25 #include "llvm/IR/GlobalValue.h"
     26 #include "llvm/Target/TargetMachine.h"
     27 using namespace llvm;
     28 
     29 #define DEBUG_TYPE "x86-pseudo"
     30 #define X86_EXPAND_PSEUDO_NAME "X86 pseudo instruction expansion pass"
     31 
     32 namespace {
     33 class X86ExpandPseudo : public MachineFunctionPass {
     34 public:
     35   static char ID;
     36   X86ExpandPseudo() : MachineFunctionPass(ID) {}
     37 
     38   void getAnalysisUsage(AnalysisUsage &AU) const override {
     39     AU.setPreservesCFG();
     40     AU.addPreservedID(MachineLoopInfoID);
     41     AU.addPreservedID(MachineDominatorsID);
     42     MachineFunctionPass::getAnalysisUsage(AU);
     43   }
     44 
     45   const X86Subtarget *STI = nullptr;
     46   const X86InstrInfo *TII = nullptr;
     47   const X86RegisterInfo *TRI = nullptr;
     48   const X86MachineFunctionInfo *X86FI = nullptr;
     49   const X86FrameLowering *X86FL = nullptr;
     50 
     51   bool runOnMachineFunction(MachineFunction &Fn) override;
     52 
     53   MachineFunctionProperties getRequiredProperties() const override {
     54     return MachineFunctionProperties().set(
     55         MachineFunctionProperties::Property::NoVRegs);
     56   }
     57 
     58   StringRef getPassName() const override {
     59     return "X86 pseudo instruction expansion pass";
     60   }
     61 
     62 private:
     63   void ExpandICallBranchFunnel(MachineBasicBlock *MBB,
     64                                MachineBasicBlock::iterator MBBI);
     65   void expandCALL_RVMARKER(MachineBasicBlock &MBB,
     66                            MachineBasicBlock::iterator MBBI);
     67   bool ExpandMI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI);
     68   bool ExpandMBB(MachineBasicBlock &MBB);
     69 
     70   /// This function expands pseudos which affects control flow.
     71   /// It is done in separate pass to simplify blocks navigation in main
     72   /// pass(calling ExpandMBB).
     73   bool ExpandPseudosWhichAffectControlFlow(MachineFunction &MF);
     74 
     75   /// Expand X86::VASTART_SAVE_XMM_REGS into set of xmm copying instructions,
     76   /// placed into separate block guarded by check for al register(for SystemV
     77   /// abi).
     78   void ExpandVastartSaveXmmRegs(
     79       MachineBasicBlock *MBB,
     80       MachineBasicBlock::iterator VAStartPseudoInstr) const;
     81 };
     82 char X86ExpandPseudo::ID = 0;
     83 
     84 } // End anonymous namespace.
     85 
     86 INITIALIZE_PASS(X86ExpandPseudo, DEBUG_TYPE, X86_EXPAND_PSEUDO_NAME, false,
     87                 false)
     88 
     89 void X86ExpandPseudo::ExpandICallBranchFunnel(
     90     MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI) {
     91   MachineBasicBlock *JTMBB = MBB;
     92   MachineInstr *JTInst = &*MBBI;
     93   MachineFunction *MF = MBB->getParent();
     94   const BasicBlock *BB = MBB->getBasicBlock();
     95   auto InsPt = MachineFunction::iterator(MBB);
     96   ++InsPt;
     97 
     98   std::vector<std::pair<MachineBasicBlock *, unsigned>> TargetMBBs;
     99   const DebugLoc &DL = JTInst->getDebugLoc();
    100   MachineOperand Selector = JTInst->getOperand(0);
    101   const GlobalValue *CombinedGlobal = JTInst->getOperand(1).getGlobal();
    102 
    103   auto CmpTarget = [&](unsigned Target) {
    104     if (Selector.isReg())
    105       MBB->addLiveIn(Selector.getReg());
    106     BuildMI(*MBB, MBBI, DL, TII->get(X86::LEA64r), X86::R11)
    107         .addReg(X86::RIP)
    108         .addImm(1)
    109         .addReg(0)
    110         .addGlobalAddress(CombinedGlobal,
    111                           JTInst->getOperand(2 + 2 * Target).getImm())
    112         .addReg(0);
    113     BuildMI(*MBB, MBBI, DL, TII->get(X86::CMP64rr))
    114         .add(Selector)
    115         .addReg(X86::R11);
    116   };
    117 
    118   auto CreateMBB = [&]() {
    119     auto *NewMBB = MF->CreateMachineBasicBlock(BB);
    120     MBB->addSuccessor(NewMBB);
    121     if (!MBB->isLiveIn(X86::EFLAGS))
    122       MBB->addLiveIn(X86::EFLAGS);
    123     return NewMBB;
    124   };
    125 
    126   auto EmitCondJump = [&](unsigned CC, MachineBasicBlock *ThenMBB) {
    127     BuildMI(*MBB, MBBI, DL, TII->get(X86::JCC_1)).addMBB(ThenMBB).addImm(CC);
    128 
    129     auto *ElseMBB = CreateMBB();
    130     MF->insert(InsPt, ElseMBB);
    131     MBB = ElseMBB;
    132     MBBI = MBB->end();
    133   };
    134 
    135   auto EmitCondJumpTarget = [&](unsigned CC, unsigned Target) {
    136     auto *ThenMBB = CreateMBB();
    137     TargetMBBs.push_back({ThenMBB, Target});
    138     EmitCondJump(CC, ThenMBB);
    139   };
    140 
    141   auto EmitTailCall = [&](unsigned Target) {
    142     BuildMI(*MBB, MBBI, DL, TII->get(X86::TAILJMPd64))
    143         .add(JTInst->getOperand(3 + 2 * Target));
    144   };
    145 
    146   std::function<void(unsigned, unsigned)> EmitBranchFunnel =
    147       [&](unsigned FirstTarget, unsigned NumTargets) {
    148     if (NumTargets == 1) {
    149       EmitTailCall(FirstTarget);
    150       return;
    151     }
    152 
    153     if (NumTargets == 2) {
    154       CmpTarget(FirstTarget + 1);
    155       EmitCondJumpTarget(X86::COND_B, FirstTarget);
    156       EmitTailCall(FirstTarget + 1);
    157       return;
    158     }
    159 
    160     if (NumTargets < 6) {
    161       CmpTarget(FirstTarget + 1);
    162       EmitCondJumpTarget(X86::COND_B, FirstTarget);
    163       EmitCondJumpTarget(X86::COND_E, FirstTarget + 1);
    164       EmitBranchFunnel(FirstTarget + 2, NumTargets - 2);
    165       return;
    166     }
    167 
    168     auto *ThenMBB = CreateMBB();
    169     CmpTarget(FirstTarget + (NumTargets / 2));
    170     EmitCondJump(X86::COND_B, ThenMBB);
    171     EmitCondJumpTarget(X86::COND_E, FirstTarget + (NumTargets / 2));
    172     EmitBranchFunnel(FirstTarget + (NumTargets / 2) + 1,
    173                   NumTargets - (NumTargets / 2) - 1);
    174 
    175     MF->insert(InsPt, ThenMBB);
    176     MBB = ThenMBB;
    177     MBBI = MBB->end();
    178     EmitBranchFunnel(FirstTarget, NumTargets / 2);
    179   };
    180 
    181   EmitBranchFunnel(0, (JTInst->getNumOperands() - 2) / 2);
    182   for (auto P : TargetMBBs) {
    183     MF->insert(InsPt, P.first);
    184     BuildMI(P.first, DL, TII->get(X86::TAILJMPd64))
    185         .add(JTInst->getOperand(3 + 2 * P.second));
    186   }
    187   JTMBB->erase(JTInst);
    188 }
    189 
    190 void X86ExpandPseudo::expandCALL_RVMARKER(MachineBasicBlock &MBB,
    191                                           MachineBasicBlock::iterator MBBI) {
    192   // Expand CALL_RVMARKER pseudo to call instruction, followed by the special
    193   //"movq %rax, %rdi" marker.
    194   // TODO: Mark the sequence as bundle, to avoid passes moving other code
    195   // in between.
    196   MachineInstr &MI = *MBBI;
    197 
    198   MachineInstr *OriginalCall;
    199   assert((MI.getOperand(1).isGlobal() || MI.getOperand(1).isReg()) &&
    200          "invalid operand for regular call");
    201   unsigned Opc = -1;
    202   if (MI.getOpcode() == X86::CALL64m_RVMARKER)
    203     Opc = X86::CALL64m;
    204   else if (MI.getOpcode() == X86::CALL64r_RVMARKER)
    205     Opc = X86::CALL64r;
    206   else if (MI.getOpcode() == X86::CALL64pcrel32_RVMARKER)
    207     Opc = X86::CALL64pcrel32;
    208   else
    209     llvm_unreachable("unexpected opcode");
    210 
    211   OriginalCall = BuildMI(MBB, MBBI, MI.getDebugLoc(), TII->get(Opc)).getInstr();
    212   unsigned OpStart = 1;
    213   bool RAXImplicitDead = false;
    214   for (; OpStart < MI.getNumOperands(); ++OpStart) {
    215     MachineOperand &Op = MI.getOperand(OpStart);
    216     // RAX may be 'implicit dead', if there are no other users of the return
    217     // value. We introduce a new use, so change it to 'implicit def'.
    218     if (Op.isReg() && Op.isImplicit() && Op.isDead() &&
    219         TRI->regsOverlap(Op.getReg(), X86::RAX)) {
    220       Op.setIsDead(false);
    221       Op.setIsDef(true);
    222       RAXImplicitDead = true;
    223     }
    224     OriginalCall->addOperand(Op);
    225   }
    226 
    227   // Emit marker "movq %rax, %rdi".  %rdi is not callee-saved, so it cannot be
    228   // live across the earlier call. The call to the ObjC runtime function returns
    229   // the first argument, so the value of %rax is unchanged after the ObjC
    230   // runtime call.
    231   auto *Marker = BuildMI(MBB, MBBI, MI.getDebugLoc(), TII->get(X86::MOV64rr))
    232                      .addReg(X86::RDI, RegState::Define)
    233                      .addReg(X86::RAX)
    234                      .getInstr();
    235   if (MI.shouldUpdateCallSiteInfo())
    236     MBB.getParent()->moveCallSiteInfo(&MI, Marker);
    237 
    238   // Emit call to ObjC runtime.
    239   unsigned RuntimeCallType = MI.getOperand(0).getImm();
    240   assert(RuntimeCallType <= 1 && "objc runtime call type must be 0 or 1");
    241   Module *M = MBB.getParent()->getFunction().getParent();
    242   auto &Context = M->getContext();
    243   auto *I8PtrTy = PointerType::get(IntegerType::get(Context, 8), 0);
    244   FunctionCallee Fn = M->getOrInsertFunction(
    245       RuntimeCallType == 0 ? "objc_retainAutoreleasedReturnValue"
    246                            : "objc_unsafeClaimAutoreleasedReturnValue",
    247       FunctionType::get(I8PtrTy, {I8PtrTy}, false));
    248   const uint32_t *RegMask =
    249       TRI->getCallPreservedMask(*MBB.getParent(), CallingConv::C);
    250   BuildMI(MBB, MBBI, MI.getDebugLoc(), TII->get(X86::CALL64pcrel32))
    251       .addGlobalAddress(cast<GlobalValue>(Fn.getCallee()), 0, 0)
    252       .addRegMask(RegMask)
    253       .addReg(X86::RAX,
    254               RegState::Implicit |
    255                   (RAXImplicitDead ? (RegState::Dead | RegState::Define)
    256                                    : RegState::Define))
    257       .getInstr();
    258   MI.eraseFromParent();
    259 }
    260 
    261 /// If \p MBBI is a pseudo instruction, this method expands
    262 /// it to the corresponding (sequence of) actual instruction(s).
    263 /// \returns true if \p MBBI has been expanded.
    264 bool X86ExpandPseudo::ExpandMI(MachineBasicBlock &MBB,
    265                                MachineBasicBlock::iterator MBBI) {
    266   MachineInstr &MI = *MBBI;
    267   unsigned Opcode = MI.getOpcode();
    268   const DebugLoc &DL = MBBI->getDebugLoc();
    269   switch (Opcode) {
    270   default:
    271     return false;
    272   case X86::TCRETURNdi:
    273   case X86::TCRETURNdicc:
    274   case X86::TCRETURNri:
    275   case X86::TCRETURNmi:
    276   case X86::TCRETURNdi64:
    277   case X86::TCRETURNdi64cc:
    278   case X86::TCRETURNri64:
    279   case X86::TCRETURNmi64: {
    280     bool isMem = Opcode == X86::TCRETURNmi || Opcode == X86::TCRETURNmi64;
    281     MachineOperand &JumpTarget = MBBI->getOperand(0);
    282     MachineOperand &StackAdjust = MBBI->getOperand(isMem ? X86::AddrNumOperands
    283                                                          : 1);
    284     assert(StackAdjust.isImm() && "Expecting immediate value.");
    285 
    286     // Adjust stack pointer.
    287     int StackAdj = StackAdjust.getImm();
    288     int MaxTCDelta = X86FI->getTCReturnAddrDelta();
    289     int Offset = 0;
    290     assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
    291 
    292     // Incoporate the retaddr area.
    293     Offset = StackAdj - MaxTCDelta;
    294     assert(Offset >= 0 && "Offset should never be negative");
    295 
    296     if (Opcode == X86::TCRETURNdicc || Opcode == X86::TCRETURNdi64cc) {
    297       assert(Offset == 0 && "Conditional tail call cannot adjust the stack.");
    298     }
    299 
    300     if (Offset) {
    301       // Check for possible merge with preceding ADD instruction.
    302       Offset += X86FL->mergeSPUpdates(MBB, MBBI, true);
    303       X86FL->emitSPUpdate(MBB, MBBI, DL, Offset, /*InEpilogue=*/true);
    304     }
    305 
    306     // Jump to label or value in register.
    307     bool IsWin64 = STI->isTargetWin64();
    308     if (Opcode == X86::TCRETURNdi || Opcode == X86::TCRETURNdicc ||
    309         Opcode == X86::TCRETURNdi64 || Opcode == X86::TCRETURNdi64cc) {
    310       unsigned Op;
    311       switch (Opcode) {
    312       case X86::TCRETURNdi:
    313         Op = X86::TAILJMPd;
    314         break;
    315       case X86::TCRETURNdicc:
    316         Op = X86::TAILJMPd_CC;
    317         break;
    318       case X86::TCRETURNdi64cc:
    319         assert(!MBB.getParent()->hasWinCFI() &&
    320                "Conditional tail calls confuse "
    321                "the Win64 unwinder.");
    322         Op = X86::TAILJMPd64_CC;
    323         break;
    324       default:
    325         // Note: Win64 uses REX prefixes indirect jumps out of functions, but
    326         // not direct ones.
    327         Op = X86::TAILJMPd64;
    328         break;
    329       }
    330       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(Op));
    331       if (JumpTarget.isGlobal()) {
    332         MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
    333                              JumpTarget.getTargetFlags());
    334       } else {
    335         assert(JumpTarget.isSymbol());
    336         MIB.addExternalSymbol(JumpTarget.getSymbolName(),
    337                               JumpTarget.getTargetFlags());
    338       }
    339       if (Op == X86::TAILJMPd_CC || Op == X86::TAILJMPd64_CC) {
    340         MIB.addImm(MBBI->getOperand(2).getImm());
    341       }
    342 
    343     } else if (Opcode == X86::TCRETURNmi || Opcode == X86::TCRETURNmi64) {
    344       unsigned Op = (Opcode == X86::TCRETURNmi)
    345                         ? X86::TAILJMPm
    346                         : (IsWin64 ? X86::TAILJMPm64_REX : X86::TAILJMPm64);
    347       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(Op));
    348       for (unsigned i = 0; i != X86::AddrNumOperands; ++i)
    349         MIB.add(MBBI->getOperand(i));
    350     } else if (Opcode == X86::TCRETURNri64) {
    351       JumpTarget.setIsKill();
    352       BuildMI(MBB, MBBI, DL,
    353               TII->get(IsWin64 ? X86::TAILJMPr64_REX : X86::TAILJMPr64))
    354           .add(JumpTarget);
    355     } else {
    356       JumpTarget.setIsKill();
    357       BuildMI(MBB, MBBI, DL, TII->get(X86::TAILJMPr))
    358           .add(JumpTarget);
    359     }
    360 
    361     MachineInstr &NewMI = *std::prev(MBBI);
    362     NewMI.copyImplicitOps(*MBBI->getParent()->getParent(), *MBBI);
    363 
    364     // Update the call site info.
    365     if (MBBI->isCandidateForCallSiteEntry())
    366       MBB.getParent()->moveCallSiteInfo(&*MBBI, &NewMI);
    367 
    368     // Delete the pseudo instruction TCRETURN.
    369     MBB.erase(MBBI);
    370 
    371     return true;
    372   }
    373   case X86::EH_RETURN:
    374   case X86::EH_RETURN64: {
    375     MachineOperand &DestAddr = MBBI->getOperand(0);
    376     assert(DestAddr.isReg() && "Offset should be in register!");
    377     const bool Uses64BitFramePtr =
    378         STI->isTarget64BitLP64() || STI->isTargetNaCl64();
    379     Register StackPtr = TRI->getStackRegister();
    380     BuildMI(MBB, MBBI, DL,
    381             TII->get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), StackPtr)
    382         .addReg(DestAddr.getReg());
    383     // The EH_RETURN pseudo is really removed during the MC Lowering.
    384     return true;
    385   }
    386   case X86::IRET: {
    387     // Adjust stack to erase error code
    388     int64_t StackAdj = MBBI->getOperand(0).getImm();
    389     X86FL->emitSPUpdate(MBB, MBBI, DL, StackAdj, true);
    390     // Replace pseudo with machine iret
    391     unsigned RetOp = STI->is64Bit() ? X86::IRET64 : X86::IRET32;
    392     // Use UIRET if UINTR is present (except for building kernel)
    393     if (STI->is64Bit() && STI->hasUINTR() &&
    394         MBB.getParent()->getTarget().getCodeModel() != CodeModel::Kernel)
    395       RetOp = X86::UIRET;
    396     BuildMI(MBB, MBBI, DL, TII->get(RetOp));
    397     MBB.erase(MBBI);
    398     return true;
    399   }
    400   case X86::RET: {
    401     // Adjust stack to erase error code
    402     int64_t StackAdj = MBBI->getOperand(0).getImm();
    403     MachineInstrBuilder MIB;
    404     if (StackAdj == 0) {
    405       MIB = BuildMI(MBB, MBBI, DL,
    406                     TII->get(STI->is64Bit() ? X86::RETQ : X86::RETL));
    407     } else if (isUInt<16>(StackAdj)) {
    408       MIB = BuildMI(MBB, MBBI, DL,
    409                     TII->get(STI->is64Bit() ? X86::RETIQ : X86::RETIL))
    410                 .addImm(StackAdj);
    411     } else {
    412       assert(!STI->is64Bit() &&
    413              "shouldn't need to do this for x86_64 targets!");
    414       // A ret can only handle immediates as big as 2**16-1.  If we need to pop
    415       // off bytes before the return address, we must do it manually.
    416       BuildMI(MBB, MBBI, DL, TII->get(X86::POP32r)).addReg(X86::ECX, RegState::Define);
    417       X86FL->emitSPUpdate(MBB, MBBI, DL, StackAdj, /*InEpilogue=*/true);
    418       BuildMI(MBB, MBBI, DL, TII->get(X86::PUSH32r)).addReg(X86::ECX);
    419       MIB = BuildMI(MBB, MBBI, DL, TII->get(X86::RETL));
    420     }
    421     for (unsigned I = 1, E = MBBI->getNumOperands(); I != E; ++I)
    422       MIB.add(MBBI->getOperand(I));
    423     MBB.erase(MBBI);
    424     return true;
    425   }
    426   case X86::LCMPXCHG16B_SAVE_RBX: {
    427     // Perform the following transformation.
    428     // SaveRbx = pseudocmpxchg Addr, <4 opds for the address>, InArg, SaveRbx
    429     // =>
    430     // RBX = InArg
    431     // actualcmpxchg Addr
    432     // RBX = SaveRbx
    433     const MachineOperand &InArg = MBBI->getOperand(6);
    434     Register SaveRbx = MBBI->getOperand(7).getReg();
    435 
    436     // Copy the input argument of the pseudo into the argument of the
    437     // actual instruction.
    438     // NOTE: We don't copy the kill flag since the input might be the same reg
    439     // as one of the other operands of LCMPXCHG16B.
    440     TII->copyPhysReg(MBB, MBBI, DL, X86::RBX, InArg.getReg(), false);
    441     // Create the actual instruction.
    442     MachineInstr *NewInstr = BuildMI(MBB, MBBI, DL, TII->get(X86::LCMPXCHG16B));
    443     // Copy the operands related to the address.
    444     for (unsigned Idx = 1; Idx < 6; ++Idx)
    445       NewInstr->addOperand(MBBI->getOperand(Idx));
    446     // Finally, restore the value of RBX.
    447     TII->copyPhysReg(MBB, MBBI, DL, X86::RBX, SaveRbx,
    448                      /*SrcIsKill*/ true);
    449 
    450     // Delete the pseudo.
    451     MBBI->eraseFromParent();
    452     return true;
    453   }
    454   // Loading/storing mask pairs requires two kmov operations. The second one of
    455   // these needs a 2 byte displacement relative to the specified address (with
    456   // 32 bit spill size). The pairs of 1bit masks up to 16 bit masks all use the
    457   // same spill size, they all are stored using MASKPAIR16STORE, loaded using
    458   // MASKPAIR16LOAD.
    459   //
    460   // The displacement value might wrap around in theory, thus the asserts in
    461   // both cases.
    462   case X86::MASKPAIR16LOAD: {
    463     int64_t Disp = MBBI->getOperand(1 + X86::AddrDisp).getImm();
    464     assert(Disp >= 0 && Disp <= INT32_MAX - 2 && "Unexpected displacement");
    465     Register Reg = MBBI->getOperand(0).getReg();
    466     bool DstIsDead = MBBI->getOperand(0).isDead();
    467     Register Reg0 = TRI->getSubReg(Reg, X86::sub_mask_0);
    468     Register Reg1 = TRI->getSubReg(Reg, X86::sub_mask_1);
    469 
    470     auto MIBLo = BuildMI(MBB, MBBI, DL, TII->get(X86::KMOVWkm))
    471       .addReg(Reg0, RegState::Define | getDeadRegState(DstIsDead));
    472     auto MIBHi = BuildMI(MBB, MBBI, DL, TII->get(X86::KMOVWkm))
    473       .addReg(Reg1, RegState::Define | getDeadRegState(DstIsDead));
    474 
    475     for (int i = 0; i < X86::AddrNumOperands; ++i) {
    476       MIBLo.add(MBBI->getOperand(1 + i));
    477       if (i == X86::AddrDisp)
    478         MIBHi.addImm(Disp + 2);
    479       else
    480         MIBHi.add(MBBI->getOperand(1 + i));
    481     }
    482 
    483     // Split the memory operand, adjusting the offset and size for the halves.
    484     MachineMemOperand *OldMMO = MBBI->memoperands().front();
    485     MachineFunction *MF = MBB.getParent();
    486     MachineMemOperand *MMOLo = MF->getMachineMemOperand(OldMMO, 0, 2);
    487     MachineMemOperand *MMOHi = MF->getMachineMemOperand(OldMMO, 2, 2);
    488 
    489     MIBLo.setMemRefs(MMOLo);
    490     MIBHi.setMemRefs(MMOHi);
    491 
    492     // Delete the pseudo.
    493     MBB.erase(MBBI);
    494     return true;
    495   }
    496   case X86::MASKPAIR16STORE: {
    497     int64_t Disp = MBBI->getOperand(X86::AddrDisp).getImm();
    498     assert(Disp >= 0 && Disp <= INT32_MAX - 2 && "Unexpected displacement");
    499     Register Reg = MBBI->getOperand(X86::AddrNumOperands).getReg();
    500     bool SrcIsKill = MBBI->getOperand(X86::AddrNumOperands).isKill();
    501     Register Reg0 = TRI->getSubReg(Reg, X86::sub_mask_0);
    502     Register Reg1 = TRI->getSubReg(Reg, X86::sub_mask_1);
    503 
    504     auto MIBLo = BuildMI(MBB, MBBI, DL, TII->get(X86::KMOVWmk));
    505     auto MIBHi = BuildMI(MBB, MBBI, DL, TII->get(X86::KMOVWmk));
    506 
    507     for (int i = 0; i < X86::AddrNumOperands; ++i) {
    508       MIBLo.add(MBBI->getOperand(i));
    509       if (i == X86::AddrDisp)
    510         MIBHi.addImm(Disp + 2);
    511       else
    512         MIBHi.add(MBBI->getOperand(i));
    513     }
    514     MIBLo.addReg(Reg0, getKillRegState(SrcIsKill));
    515     MIBHi.addReg(Reg1, getKillRegState(SrcIsKill));
    516 
    517     // Split the memory operand, adjusting the offset and size for the halves.
    518     MachineMemOperand *OldMMO = MBBI->memoperands().front();
    519     MachineFunction *MF = MBB.getParent();
    520     MachineMemOperand *MMOLo = MF->getMachineMemOperand(OldMMO, 0, 2);
    521     MachineMemOperand *MMOHi = MF->getMachineMemOperand(OldMMO, 2, 2);
    522 
    523     MIBLo.setMemRefs(MMOLo);
    524     MIBHi.setMemRefs(MMOHi);
    525 
    526     // Delete the pseudo.
    527     MBB.erase(MBBI);
    528     return true;
    529   }
    530   case X86::MWAITX_SAVE_RBX: {
    531     // Perform the following transformation.
    532     // SaveRbx = pseudomwaitx InArg, SaveRbx
    533     // =>
    534     // [E|R]BX = InArg
    535     // actualmwaitx
    536     // [E|R]BX = SaveRbx
    537     const MachineOperand &InArg = MBBI->getOperand(1);
    538     // Copy the input argument of the pseudo into the argument of the
    539     // actual instruction.
    540     TII->copyPhysReg(MBB, MBBI, DL, X86::EBX, InArg.getReg(), InArg.isKill());
    541     // Create the actual instruction.
    542     BuildMI(MBB, MBBI, DL, TII->get(X86::MWAITXrrr));
    543     // Finally, restore the value of RBX.
    544     Register SaveRbx = MBBI->getOperand(2).getReg();
    545     TII->copyPhysReg(MBB, MBBI, DL, X86::RBX, SaveRbx, /*SrcIsKill*/ true);
    546     // Delete the pseudo.
    547     MBBI->eraseFromParent();
    548     return true;
    549   }
    550   case TargetOpcode::ICALL_BRANCH_FUNNEL:
    551     ExpandICallBranchFunnel(&MBB, MBBI);
    552     return true;
    553   case X86::PLDTILECFGV: {
    554     MI.setDesc(TII->get(X86::LDTILECFG));
    555     return true;
    556   }
    557   case X86::PTILELOADDV: {
    558     for (unsigned i = 2; i > 0; --i)
    559       MI.RemoveOperand(i);
    560     MI.setDesc(TII->get(X86::TILELOADD));
    561     return true;
    562   }
    563   case X86::PTDPBSSDV:
    564   case X86::PTDPBSUDV:
    565   case X86::PTDPBUSDV:
    566   case X86::PTDPBUUDV:
    567   case X86::PTDPBF16PSV: {
    568     MI.untieRegOperand(4);
    569     for (unsigned i = 3; i > 0; --i)
    570       MI.RemoveOperand(i);
    571     unsigned Opc;
    572     switch (Opcode) {
    573     case X86::PTDPBSSDV:   Opc = X86::TDPBSSD; break;
    574     case X86::PTDPBSUDV:   Opc = X86::TDPBSUD; break;
    575     case X86::PTDPBUSDV:   Opc = X86::TDPBUSD; break;
    576     case X86::PTDPBUUDV:   Opc = X86::TDPBUUD; break;
    577     case X86::PTDPBF16PSV: Opc = X86::TDPBF16PS; break;
    578     default: llvm_unreachable("Impossible Opcode!");
    579     }
    580     MI.setDesc(TII->get(Opc));
    581     MI.tieOperands(0, 1);
    582     return true;
    583   }
    584   case X86::PTILESTOREDV: {
    585     for (int i = 1; i >= 0; --i)
    586       MI.RemoveOperand(i);
    587     MI.setDesc(TII->get(X86::TILESTORED));
    588     return true;
    589   }
    590   case X86::PTILEZEROV: {
    591     for (int i = 2; i > 0; --i) // Remove row, col
    592       MI.RemoveOperand(i);
    593     MI.setDesc(TII->get(X86::TILEZERO));
    594     return true;
    595   }
    596   case X86::CALL64pcrel32_RVMARKER:
    597   case X86::CALL64r_RVMARKER:
    598   case X86::CALL64m_RVMARKER:
    599     expandCALL_RVMARKER(MBB, MBBI);
    600     return true;
    601   }
    602   llvm_unreachable("Previous switch has a fallthrough?");
    603 }
    604 
    605 // This function creates additional block for storing varargs guarded
    606 // registers. It adds check for %al into entry block, to skip
    607 // GuardedRegsBlk if xmm registers should not be stored.
    608 //
    609 //     EntryBlk[VAStartPseudoInstr]     EntryBlk
    610 //        |                              |     .
    611 //        |                              |        .
    612 //        |                              |   GuardedRegsBlk
    613 //        |                      =>      |        .
    614 //        |                              |     .
    615 //        |                             TailBlk
    616 //        |                              |
    617 //        |                              |
    618 //
    619 void X86ExpandPseudo::ExpandVastartSaveXmmRegs(
    620     MachineBasicBlock *EntryBlk,
    621     MachineBasicBlock::iterator VAStartPseudoInstr) const {
    622   assert(VAStartPseudoInstr->getOpcode() == X86::VASTART_SAVE_XMM_REGS);
    623 
    624   MachineFunction *Func = EntryBlk->getParent();
    625   const TargetInstrInfo *TII = STI->getInstrInfo();
    626   const DebugLoc &DL = VAStartPseudoInstr->getDebugLoc();
    627   Register CountReg = VAStartPseudoInstr->getOperand(0).getReg();
    628 
    629   // Calculate liveins for newly created blocks.
    630   LivePhysRegs LiveRegs(*STI->getRegisterInfo());
    631   SmallVector<std::pair<MCPhysReg, const MachineOperand *>, 8> Clobbers;
    632 
    633   LiveRegs.addLiveIns(*EntryBlk);
    634   for (MachineInstr &MI : EntryBlk->instrs()) {
    635     if (MI.getOpcode() == VAStartPseudoInstr->getOpcode())
    636       break;
    637 
    638     LiveRegs.stepForward(MI, Clobbers);
    639   }
    640 
    641   // Create the new basic blocks. One block contains all the XMM stores,
    642   // and another block is the final destination regardless of whether any
    643   // stores were performed.
    644   const BasicBlock *LLVMBlk = EntryBlk->getBasicBlock();
    645   MachineFunction::iterator EntryBlkIter = ++EntryBlk->getIterator();
    646   MachineBasicBlock *GuardedRegsBlk = Func->CreateMachineBasicBlock(LLVMBlk);
    647   MachineBasicBlock *TailBlk = Func->CreateMachineBasicBlock(LLVMBlk);
    648   Func->insert(EntryBlkIter, GuardedRegsBlk);
    649   Func->insert(EntryBlkIter, TailBlk);
    650 
    651   // Transfer the remainder of EntryBlk and its successor edges to TailBlk.
    652   TailBlk->splice(TailBlk->begin(), EntryBlk,
    653                   std::next(MachineBasicBlock::iterator(VAStartPseudoInstr)),
    654                   EntryBlk->end());
    655   TailBlk->transferSuccessorsAndUpdatePHIs(EntryBlk);
    656 
    657   int64_t FrameIndex = VAStartPseudoInstr->getOperand(1).getImm();
    658   Register BaseReg;
    659   uint64_t FrameOffset =
    660       X86FL->getFrameIndexReference(*Func, FrameIndex, BaseReg).getFixed();
    661   uint64_t VarArgsRegsOffset = VAStartPseudoInstr->getOperand(2).getImm();
    662 
    663   // TODO: add support for YMM and ZMM here.
    664   unsigned MOVOpc = STI->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
    665 
    666   // In the XMM save block, save all the XMM argument registers.
    667   for (int64_t OpndIdx = 3, RegIdx = 0;
    668        OpndIdx < VAStartPseudoInstr->getNumOperands() - 1;
    669        OpndIdx++, RegIdx++) {
    670 
    671     int64_t Offset = FrameOffset + VarArgsRegsOffset + RegIdx * 16;
    672 
    673     MachineMemOperand *MMO = Func->getMachineMemOperand(
    674         MachinePointerInfo::getFixedStack(*Func, FrameIndex, Offset),
    675         MachineMemOperand::MOStore,
    676         /*Size=*/16, Align(16));
    677 
    678     BuildMI(GuardedRegsBlk, DL, TII->get(MOVOpc))
    679         .addReg(BaseReg)
    680         .addImm(/*Scale=*/1)
    681         .addReg(/*IndexReg=*/0)
    682         .addImm(/*Disp=*/Offset)
    683         .addReg(/*Segment=*/0)
    684         .addReg(VAStartPseudoInstr->getOperand(OpndIdx).getReg())
    685         .addMemOperand(MMO);
    686     assert(Register::isPhysicalRegister(
    687         VAStartPseudoInstr->getOperand(OpndIdx).getReg()));
    688   }
    689 
    690   // The original block will now fall through to the GuardedRegsBlk.
    691   EntryBlk->addSuccessor(GuardedRegsBlk);
    692   // The GuardedRegsBlk will fall through to the TailBlk.
    693   GuardedRegsBlk->addSuccessor(TailBlk);
    694 
    695   if (!STI->isCallingConvWin64(Func->getFunction().getCallingConv())) {
    696     // If %al is 0, branch around the XMM save block.
    697     BuildMI(EntryBlk, DL, TII->get(X86::TEST8rr))
    698         .addReg(CountReg)
    699         .addReg(CountReg);
    700     BuildMI(EntryBlk, DL, TII->get(X86::JCC_1))
    701         .addMBB(TailBlk)
    702         .addImm(X86::COND_E);
    703     EntryBlk->addSuccessor(TailBlk);
    704   }
    705 
    706   // Add liveins to the created block.
    707   addLiveIns(*GuardedRegsBlk, LiveRegs);
    708   addLiveIns(*TailBlk, LiveRegs);
    709 
    710   // Delete the pseudo.
    711   VAStartPseudoInstr->eraseFromParent();
    712 }
    713 
    714 /// Expand all pseudo instructions contained in \p MBB.
    715 /// \returns true if any expansion occurred for \p MBB.
    716 bool X86ExpandPseudo::ExpandMBB(MachineBasicBlock &MBB) {
    717   bool Modified = false;
    718 
    719   // MBBI may be invalidated by the expansion.
    720   MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
    721   while (MBBI != E) {
    722     MachineBasicBlock::iterator NMBBI = std::next(MBBI);
    723     Modified |= ExpandMI(MBB, MBBI);
    724     MBBI = NMBBI;
    725   }
    726 
    727   return Modified;
    728 }
    729 
    730 bool X86ExpandPseudo::ExpandPseudosWhichAffectControlFlow(MachineFunction &MF) {
    731   // Currently pseudo which affects control flow is only
    732   // X86::VASTART_SAVE_XMM_REGS which is located in Entry block.
    733   // So we do not need to evaluate other blocks.
    734   for (MachineInstr &Instr : MF.front().instrs()) {
    735     if (Instr.getOpcode() == X86::VASTART_SAVE_XMM_REGS) {
    736       ExpandVastartSaveXmmRegs(&(MF.front()), Instr);
    737       return true;
    738     }
    739   }
    740 
    741   return false;
    742 }
    743 
    744 bool X86ExpandPseudo::runOnMachineFunction(MachineFunction &MF) {
    745   STI = &static_cast<const X86Subtarget &>(MF.getSubtarget());
    746   TII = STI->getInstrInfo();
    747   TRI = STI->getRegisterInfo();
    748   X86FI = MF.getInfo<X86MachineFunctionInfo>();
    749   X86FL = STI->getFrameLowering();
    750 
    751   bool Modified = ExpandPseudosWhichAffectControlFlow(MF);
    752 
    753   for (MachineBasicBlock &MBB : MF)
    754     Modified |= ExpandMBB(MBB);
    755   return Modified;
    756 }
    757 
    758 /// Returns an instance of the pseudo instruction expansion pass.
    759 FunctionPass *llvm::createX86ExpandPseudoPass() {
    760   return new X86ExpandPseudo();
    761 }
    762