LLVM API Documentation

X86MCInstLower.cpp
Go to the documentation of this file.
00001 //===-- X86MCInstLower.cpp - Convert X86 MachineInstr to an MCInst --------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains code to lower X86 MachineInstrs to their corresponding
00011 // MCInst records.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "X86AsmPrinter.h"
00016 #include "X86RegisterInfo.h"
00017 #include "InstPrinter/X86ATTInstPrinter.h"
00018 #include "MCTargetDesc/X86BaseInfo.h"
00019 #include "Utils/X86ShuffleDecode.h"
00020 #include "llvm/ADT/SmallString.h"
00021 #include "llvm/CodeGen/MachineFunction.h"
00022 #include "llvm/CodeGen/MachineConstantPool.h"
00023 #include "llvm/CodeGen/MachineOperand.h"
00024 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
00025 #include "llvm/CodeGen/StackMaps.h"
00026 #include "llvm/IR/DataLayout.h"
00027 #include "llvm/IR/GlobalValue.h"
00028 #include "llvm/IR/Mangler.h"
00029 #include "llvm/MC/MCAsmInfo.h"
00030 #include "llvm/MC/MCCodeEmitter.h"
00031 #include "llvm/MC/MCContext.h"
00032 #include "llvm/MC/MCExpr.h"
00033 #include "llvm/MC/MCInst.h"
00034 #include "llvm/MC/MCInstBuilder.h"
00035 #include "llvm/MC/MCStreamer.h"
00036 #include "llvm/MC/MCSymbol.h"
00037 #include "llvm/Support/TargetRegistry.h"
00038 using namespace llvm;
00039 
00040 namespace {
00041 
00042 /// X86MCInstLower - This class is used to lower an MachineInstr into an MCInst.
00043 class X86MCInstLower {
00044   MCContext &Ctx;
00045   const MachineFunction &MF;
00046   const TargetMachine &TM;
00047   const MCAsmInfo &MAI;
00048   X86AsmPrinter &AsmPrinter;
00049 public:
00050   X86MCInstLower(const MachineFunction &MF, X86AsmPrinter &asmprinter);
00051 
00052   void Lower(const MachineInstr *MI, MCInst &OutMI) const;
00053 
00054   MCSymbol *GetSymbolFromOperand(const MachineOperand &MO) const;
00055   MCOperand LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const;
00056 
00057 private:
00058   MachineModuleInfoMachO &getMachOMMI() const;
00059   Mangler *getMang() const {
00060     return AsmPrinter.Mang;
00061   }
00062 };
00063 
00064 } // end anonymous namespace
00065 
00066 // Emit a minimal sequence of nops spanning NumBytes bytes.
00067 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
00068                      const MCSubtargetInfo &STI);
00069 
00070 namespace llvm {
00071    X86AsmPrinter::StackMapShadowTracker::StackMapShadowTracker(TargetMachine &TM)
00072      : TM(TM), InShadow(false), RequiredShadowSize(0), CurrentShadowSize(0) {}
00073 
00074   X86AsmPrinter::StackMapShadowTracker::~StackMapShadowTracker() {}
00075 
00076   void
00077   X86AsmPrinter::StackMapShadowTracker::startFunction(MachineFunction &MF) {
00078     CodeEmitter.reset(TM.getTarget().createMCCodeEmitter(
00079         *TM.getSubtargetImpl()->getInstrInfo(),
00080         *TM.getSubtargetImpl()->getRegisterInfo(), *TM.getSubtargetImpl(),
00081         MF.getContext()));
00082   }
00083 
00084   void X86AsmPrinter::StackMapShadowTracker::count(MCInst &Inst,
00085                                                    const MCSubtargetInfo &STI) {
00086     if (InShadow) {
00087       SmallString<256> Code;
00088       SmallVector<MCFixup, 4> Fixups;
00089       raw_svector_ostream VecOS(Code);
00090       CodeEmitter->EncodeInstruction(Inst, VecOS, Fixups, STI);
00091       VecOS.flush();
00092       CurrentShadowSize += Code.size();
00093       if (CurrentShadowSize >= RequiredShadowSize)
00094         InShadow = false; // The shadow is big enough. Stop counting.
00095     }
00096   }
00097 
00098   void X86AsmPrinter::StackMapShadowTracker::emitShadowPadding(
00099     MCStreamer &OutStreamer, const MCSubtargetInfo &STI) {
00100     if (InShadow && CurrentShadowSize < RequiredShadowSize) {
00101       InShadow = false;
00102       EmitNops(OutStreamer, RequiredShadowSize - CurrentShadowSize,
00103                TM.getSubtarget<X86Subtarget>().is64Bit(), STI);
00104     }
00105   }
00106 
00107   void X86AsmPrinter::EmitAndCountInstruction(MCInst &Inst) {
00108     OutStreamer.EmitInstruction(Inst, getSubtargetInfo());
00109     SMShadowTracker.count(Inst, getSubtargetInfo());
00110   }
00111 } // end llvm namespace
00112 
00113 X86MCInstLower::X86MCInstLower(const MachineFunction &mf,
00114                                X86AsmPrinter &asmprinter)
00115 : Ctx(mf.getContext()), MF(mf), TM(mf.getTarget()),
00116   MAI(*TM.getMCAsmInfo()), AsmPrinter(asmprinter) {}
00117 
00118 MachineModuleInfoMachO &X86MCInstLower::getMachOMMI() const {
00119   return MF.getMMI().getObjFileInfo<MachineModuleInfoMachO>();
00120 }
00121 
00122 
00123 /// GetSymbolFromOperand - Lower an MO_GlobalAddress or MO_ExternalSymbol
00124 /// operand to an MCSymbol.
00125 MCSymbol *X86MCInstLower::
00126 GetSymbolFromOperand(const MachineOperand &MO) const {
00127   const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
00128   assert((MO.isGlobal() || MO.isSymbol() || MO.isMBB()) && "Isn't a symbol reference");
00129 
00130   SmallString<128> Name;
00131   StringRef Suffix;
00132 
00133   switch (MO.getTargetFlags()) {
00134   case X86II::MO_DLLIMPORT:
00135     // Handle dllimport linkage.
00136     Name += "__imp_";
00137     break;
00138   case X86II::MO_DARWIN_STUB:
00139     Suffix = "$stub";
00140     break;
00141   case X86II::MO_DARWIN_NONLAZY:
00142   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
00143   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
00144     Suffix = "$non_lazy_ptr";
00145     break;
00146   }
00147 
00148   if (!Suffix.empty())
00149     Name += DL->getPrivateGlobalPrefix();
00150 
00151   unsigned PrefixLen = Name.size();
00152 
00153   if (MO.isGlobal()) {
00154     const GlobalValue *GV = MO.getGlobal();
00155     AsmPrinter.getNameWithPrefix(Name, GV);
00156   } else if (MO.isSymbol()) {
00157     getMang()->getNameWithPrefix(Name, MO.getSymbolName());
00158   } else if (MO.isMBB()) {
00159     Name += MO.getMBB()->getSymbol()->getName();
00160   }
00161   unsigned OrigLen = Name.size() - PrefixLen;
00162 
00163   Name += Suffix;
00164   MCSymbol *Sym = Ctx.GetOrCreateSymbol(Name);
00165 
00166   StringRef OrigName = StringRef(Name).substr(PrefixLen, OrigLen);
00167 
00168   // If the target flags on the operand changes the name of the symbol, do that
00169   // before we return the symbol.
00170   switch (MO.getTargetFlags()) {
00171   default: break;
00172   case X86II::MO_DARWIN_NONLAZY:
00173   case X86II::MO_DARWIN_NONLAZY_PIC_BASE: {
00174     MachineModuleInfoImpl::StubValueTy &StubSym =
00175       getMachOMMI().getGVStubEntry(Sym);
00176     if (!StubSym.getPointer()) {
00177       assert(MO.isGlobal() && "Extern symbol not handled yet");
00178       StubSym =
00179         MachineModuleInfoImpl::
00180         StubValueTy(AsmPrinter.getSymbol(MO.getGlobal()),
00181                     !MO.getGlobal()->hasInternalLinkage());
00182     }
00183     break;
00184   }
00185   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE: {
00186     MachineModuleInfoImpl::StubValueTy &StubSym =
00187       getMachOMMI().getHiddenGVStubEntry(Sym);
00188     if (!StubSym.getPointer()) {
00189       assert(MO.isGlobal() && "Extern symbol not handled yet");
00190       StubSym =
00191         MachineModuleInfoImpl::
00192         StubValueTy(AsmPrinter.getSymbol(MO.getGlobal()),
00193                     !MO.getGlobal()->hasInternalLinkage());
00194     }
00195     break;
00196   }
00197   case X86II::MO_DARWIN_STUB: {
00198     MachineModuleInfoImpl::StubValueTy &StubSym =
00199       getMachOMMI().getFnStubEntry(Sym);
00200     if (StubSym.getPointer())
00201       return Sym;
00202 
00203     if (MO.isGlobal()) {
00204       StubSym =
00205         MachineModuleInfoImpl::
00206         StubValueTy(AsmPrinter.getSymbol(MO.getGlobal()),
00207                     !MO.getGlobal()->hasInternalLinkage());
00208     } else {
00209       StubSym =
00210         MachineModuleInfoImpl::
00211         StubValueTy(Ctx.GetOrCreateSymbol(OrigName), false);
00212     }
00213     break;
00214   }
00215   }
00216 
00217   return Sym;
00218 }
00219 
00220 MCOperand X86MCInstLower::LowerSymbolOperand(const MachineOperand &MO,
00221                                              MCSymbol *Sym) const {
00222   // FIXME: We would like an efficient form for this, so we don't have to do a
00223   // lot of extra uniquing.
00224   const MCExpr *Expr = nullptr;
00225   MCSymbolRefExpr::VariantKind RefKind = MCSymbolRefExpr::VK_None;
00226 
00227   switch (MO.getTargetFlags()) {
00228   default: llvm_unreachable("Unknown target flag on GV operand");
00229   case X86II::MO_NO_FLAG:    // No flag.
00230   // These affect the name of the symbol, not any suffix.
00231   case X86II::MO_DARWIN_NONLAZY:
00232   case X86II::MO_DLLIMPORT:
00233   case X86II::MO_DARWIN_STUB:
00234     break;
00235 
00236   case X86II::MO_TLVP:      RefKind = MCSymbolRefExpr::VK_TLVP; break;
00237   case X86II::MO_TLVP_PIC_BASE:
00238     Expr = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_TLVP, Ctx);
00239     // Subtract the pic base.
00240     Expr = MCBinaryExpr::CreateSub(Expr,
00241                                   MCSymbolRefExpr::Create(MF.getPICBaseSymbol(),
00242                                                            Ctx),
00243                                    Ctx);
00244     break;
00245   case X86II::MO_SECREL:    RefKind = MCSymbolRefExpr::VK_SECREL; break;
00246   case X86II::MO_TLSGD:     RefKind = MCSymbolRefExpr::VK_TLSGD; break;
00247   case X86II::MO_TLSLD:     RefKind = MCSymbolRefExpr::VK_TLSLD; break;
00248   case X86II::MO_TLSLDM:    RefKind = MCSymbolRefExpr::VK_TLSLDM; break;
00249   case X86II::MO_GOTTPOFF:  RefKind = MCSymbolRefExpr::VK_GOTTPOFF; break;
00250   case X86II::MO_INDNTPOFF: RefKind = MCSymbolRefExpr::VK_INDNTPOFF; break;
00251   case X86II::MO_TPOFF:     RefKind = MCSymbolRefExpr::VK_TPOFF; break;
00252   case X86II::MO_DTPOFF:    RefKind = MCSymbolRefExpr::VK_DTPOFF; break;
00253   case X86II::MO_NTPOFF:    RefKind = MCSymbolRefExpr::VK_NTPOFF; break;
00254   case X86II::MO_GOTNTPOFF: RefKind = MCSymbolRefExpr::VK_GOTNTPOFF; break;
00255   case X86II::MO_GOTPCREL:  RefKind = MCSymbolRefExpr::VK_GOTPCREL; break;
00256   case X86II::MO_GOT:       RefKind = MCSymbolRefExpr::VK_GOT; break;
00257   case X86II::MO_GOTOFF:    RefKind = MCSymbolRefExpr::VK_GOTOFF; break;
00258   case X86II::MO_PLT:       RefKind = MCSymbolRefExpr::VK_PLT; break;
00259   case X86II::MO_PIC_BASE_OFFSET:
00260   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
00261   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
00262     Expr = MCSymbolRefExpr::Create(Sym, Ctx);
00263     // Subtract the pic base.
00264     Expr = MCBinaryExpr::CreateSub(Expr,
00265                             MCSymbolRefExpr::Create(MF.getPICBaseSymbol(), Ctx),
00266                                    Ctx);
00267     if (MO.isJTI()) {
00268       assert(MAI.doesSetDirectiveSuppressesReloc());
00269       // If .set directive is supported, use it to reduce the number of
00270       // relocations the assembler will generate for differences between
00271       // local labels. This is only safe when the symbols are in the same
00272       // section so we are restricting it to jumptable references.
00273       MCSymbol *Label = Ctx.CreateTempSymbol();
00274       AsmPrinter.OutStreamer.EmitAssignment(Label, Expr);
00275       Expr = MCSymbolRefExpr::Create(Label, Ctx);
00276     }
00277     break;
00278   }
00279 
00280   if (!Expr)
00281     Expr = MCSymbolRefExpr::Create(Sym, RefKind, Ctx);
00282 
00283   if (!MO.isJTI() && !MO.isMBB() && MO.getOffset())
00284     Expr = MCBinaryExpr::CreateAdd(Expr,
00285                                    MCConstantExpr::Create(MO.getOffset(), Ctx),
00286                                    Ctx);
00287   return MCOperand::CreateExpr(Expr);
00288 }
00289 
00290 
00291 /// \brief Simplify FOO $imm, %{al,ax,eax,rax} to FOO $imm, for instruction with
00292 /// a short fixed-register form.
00293 static void SimplifyShortImmForm(MCInst &Inst, unsigned Opcode) {
00294   unsigned ImmOp = Inst.getNumOperands() - 1;
00295   assert(Inst.getOperand(0).isReg() &&
00296          (Inst.getOperand(ImmOp).isImm() || Inst.getOperand(ImmOp).isExpr()) &&
00297          ((Inst.getNumOperands() == 3 && Inst.getOperand(1).isReg() &&
00298            Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) ||
00299           Inst.getNumOperands() == 2) && "Unexpected instruction!");
00300 
00301   // Check whether the destination register can be fixed.
00302   unsigned Reg = Inst.getOperand(0).getReg();
00303   if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
00304     return;
00305 
00306   // If so, rewrite the instruction.
00307   MCOperand Saved = Inst.getOperand(ImmOp);
00308   Inst = MCInst();
00309   Inst.setOpcode(Opcode);
00310   Inst.addOperand(Saved);
00311 }
00312 
00313 /// \brief If a movsx instruction has a shorter encoding for the used register
00314 /// simplify the instruction to use it instead.
00315 static void SimplifyMOVSX(MCInst &Inst) {
00316   unsigned NewOpcode = 0;
00317   unsigned Op0 = Inst.getOperand(0).getReg(), Op1 = Inst.getOperand(1).getReg();
00318   switch (Inst.getOpcode()) {
00319   default:
00320     llvm_unreachable("Unexpected instruction!");
00321   case X86::MOVSX16rr8:  // movsbw %al, %ax   --> cbtw
00322     if (Op0 == X86::AX && Op1 == X86::AL)
00323       NewOpcode = X86::CBW;
00324     break;
00325   case X86::MOVSX32rr16: // movswl %ax, %eax  --> cwtl
00326     if (Op0 == X86::EAX && Op1 == X86::AX)
00327       NewOpcode = X86::CWDE;
00328     break;
00329   case X86::MOVSX64rr32: // movslq %eax, %rax --> cltq
00330     if (Op0 == X86::RAX && Op1 == X86::EAX)
00331       NewOpcode = X86::CDQE;
00332     break;
00333   }
00334 
00335   if (NewOpcode != 0) {
00336     Inst = MCInst();
00337     Inst.setOpcode(NewOpcode);
00338   }
00339 }
00340 
00341 /// \brief Simplify things like MOV32rm to MOV32o32a.
00342 static void SimplifyShortMoveForm(X86AsmPrinter &Printer, MCInst &Inst,
00343                                   unsigned Opcode) {
00344   // Don't make these simplifications in 64-bit mode; other assemblers don't
00345   // perform them because they make the code larger.
00346   if (Printer.getSubtarget().is64Bit())
00347     return;
00348 
00349   bool IsStore = Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg();
00350   unsigned AddrBase = IsStore;
00351   unsigned RegOp = IsStore ? 0 : 5;
00352   unsigned AddrOp = AddrBase + 3;
00353   assert(Inst.getNumOperands() == 6 && Inst.getOperand(RegOp).isReg() &&
00354          Inst.getOperand(AddrBase + X86::AddrBaseReg).isReg() &&
00355          Inst.getOperand(AddrBase + X86::AddrScaleAmt).isImm() &&
00356          Inst.getOperand(AddrBase + X86::AddrIndexReg).isReg() &&
00357          Inst.getOperand(AddrBase + X86::AddrSegmentReg).isReg() &&
00358          (Inst.getOperand(AddrOp).isExpr() ||
00359           Inst.getOperand(AddrOp).isImm()) &&
00360          "Unexpected instruction!");
00361 
00362   // Check whether the destination register can be fixed.
00363   unsigned Reg = Inst.getOperand(RegOp).getReg();
00364   if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
00365     return;
00366 
00367   // Check whether this is an absolute address.
00368   // FIXME: We know TLVP symbol refs aren't, but there should be a better way
00369   // to do this here.
00370   bool Absolute = true;
00371   if (Inst.getOperand(AddrOp).isExpr()) {
00372     const MCExpr *MCE = Inst.getOperand(AddrOp).getExpr();
00373     if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(MCE))
00374       if (SRE->getKind() == MCSymbolRefExpr::VK_TLVP)
00375         Absolute = false;
00376   }
00377 
00378   if (Absolute &&
00379       (Inst.getOperand(AddrBase + X86::AddrBaseReg).getReg() != 0 ||
00380        Inst.getOperand(AddrBase + X86::AddrScaleAmt).getImm() != 1 ||
00381        Inst.getOperand(AddrBase + X86::AddrIndexReg).getReg() != 0))
00382     return;
00383 
00384   // If so, rewrite the instruction.
00385   MCOperand Saved = Inst.getOperand(AddrOp);
00386   MCOperand Seg = Inst.getOperand(AddrBase + X86::AddrSegmentReg);
00387   Inst = MCInst();
00388   Inst.setOpcode(Opcode);
00389   Inst.addOperand(Saved);
00390   Inst.addOperand(Seg);
00391 }
00392 
00393 static unsigned getRetOpcode(const X86Subtarget &Subtarget)
00394 {
00395   return Subtarget.is64Bit() ? X86::RETQ : X86::RETL;
00396 }
00397 
00398 void X86MCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const {
00399   OutMI.setOpcode(MI->getOpcode());
00400 
00401   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00402     const MachineOperand &MO = MI->getOperand(i);
00403 
00404     MCOperand MCOp;
00405     switch (MO.getType()) {
00406     default:
00407       MI->dump();
00408       llvm_unreachable("unknown operand type");
00409     case MachineOperand::MO_Register:
00410       // Ignore all implicit register operands.
00411       if (MO.isImplicit()) continue;
00412       MCOp = MCOperand::CreateReg(MO.getReg());
00413       break;
00414     case MachineOperand::MO_Immediate:
00415       MCOp = MCOperand::CreateImm(MO.getImm());
00416       break;
00417     case MachineOperand::MO_MachineBasicBlock:
00418     case MachineOperand::MO_GlobalAddress:
00419     case MachineOperand::MO_ExternalSymbol:
00420       MCOp = LowerSymbolOperand(MO, GetSymbolFromOperand(MO));
00421       break;
00422     case MachineOperand::MO_JumpTableIndex:
00423       MCOp = LowerSymbolOperand(MO, AsmPrinter.GetJTISymbol(MO.getIndex()));
00424       break;
00425     case MachineOperand::MO_ConstantPoolIndex:
00426       MCOp = LowerSymbolOperand(MO, AsmPrinter.GetCPISymbol(MO.getIndex()));
00427       break;
00428     case MachineOperand::MO_BlockAddress:
00429       MCOp = LowerSymbolOperand(MO,
00430                      AsmPrinter.GetBlockAddressSymbol(MO.getBlockAddress()));
00431       break;
00432     case MachineOperand::MO_RegisterMask:
00433       // Ignore call clobbers.
00434       continue;
00435     }
00436 
00437     OutMI.addOperand(MCOp);
00438   }
00439 
00440   // Handle a few special cases to eliminate operand modifiers.
00441 ReSimplify:
00442   switch (OutMI.getOpcode()) {
00443   case X86::LEA64_32r:
00444   case X86::LEA64r:
00445   case X86::LEA16r:
00446   case X86::LEA32r:
00447     // LEA should have a segment register, but it must be empty.
00448     assert(OutMI.getNumOperands() == 1+X86::AddrNumOperands &&
00449            "Unexpected # of LEA operands");
00450     assert(OutMI.getOperand(1+X86::AddrSegmentReg).getReg() == 0 &&
00451            "LEA has segment specified!");
00452     break;
00453 
00454   case X86::MOV32ri64:
00455     OutMI.setOpcode(X86::MOV32ri);
00456     break;
00457 
00458   // Commute operands to get a smaller encoding by using VEX.R instead of VEX.B
00459   // if one of the registers is extended, but other isn't.
00460   case X86::VMOVAPDrr:
00461   case X86::VMOVAPDYrr:
00462   case X86::VMOVAPSrr:
00463   case X86::VMOVAPSYrr:
00464   case X86::VMOVDQArr:
00465   case X86::VMOVDQAYrr:
00466   case X86::VMOVDQUrr:
00467   case X86::VMOVDQUYrr:
00468   case X86::VMOVUPDrr:
00469   case X86::VMOVUPDYrr:
00470   case X86::VMOVUPSrr:
00471   case X86::VMOVUPSYrr: {
00472     if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
00473         X86II::isX86_64ExtendedReg(OutMI.getOperand(1).getReg())) {
00474       unsigned NewOpc;
00475       switch (OutMI.getOpcode()) {
00476       default: llvm_unreachable("Invalid opcode");
00477       case X86::VMOVAPDrr:  NewOpc = X86::VMOVAPDrr_REV;  break;
00478       case X86::VMOVAPDYrr: NewOpc = X86::VMOVAPDYrr_REV; break;
00479       case X86::VMOVAPSrr:  NewOpc = X86::VMOVAPSrr_REV;  break;
00480       case X86::VMOVAPSYrr: NewOpc = X86::VMOVAPSYrr_REV; break;
00481       case X86::VMOVDQArr:  NewOpc = X86::VMOVDQArr_REV;  break;
00482       case X86::VMOVDQAYrr: NewOpc = X86::VMOVDQAYrr_REV; break;
00483       case X86::VMOVDQUrr:  NewOpc = X86::VMOVDQUrr_REV;  break;
00484       case X86::VMOVDQUYrr: NewOpc = X86::VMOVDQUYrr_REV; break;
00485       case X86::VMOVUPDrr:  NewOpc = X86::VMOVUPDrr_REV;  break;
00486       case X86::VMOVUPDYrr: NewOpc = X86::VMOVUPDYrr_REV; break;
00487       case X86::VMOVUPSrr:  NewOpc = X86::VMOVUPSrr_REV;  break;
00488       case X86::VMOVUPSYrr: NewOpc = X86::VMOVUPSYrr_REV; break;
00489       }
00490       OutMI.setOpcode(NewOpc);
00491     }
00492     break;
00493   }
00494   case X86::VMOVSDrr:
00495   case X86::VMOVSSrr: {
00496     if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
00497         X86II::isX86_64ExtendedReg(OutMI.getOperand(2).getReg())) {
00498       unsigned NewOpc;
00499       switch (OutMI.getOpcode()) {
00500       default: llvm_unreachable("Invalid opcode");
00501       case X86::VMOVSDrr:   NewOpc = X86::VMOVSDrr_REV;   break;
00502       case X86::VMOVSSrr:   NewOpc = X86::VMOVSSrr_REV;   break;
00503       }
00504       OutMI.setOpcode(NewOpc);
00505     }
00506     break;
00507   }
00508 
00509   // TAILJMPr64, CALL64r, CALL64pcrel32 - These instructions have register
00510   // inputs modeled as normal uses instead of implicit uses.  As such, truncate
00511   // off all but the first operand (the callee).  FIXME: Change isel.
00512   case X86::TAILJMPr64:
00513   case X86::CALL64r:
00514   case X86::CALL64pcrel32: {
00515     unsigned Opcode = OutMI.getOpcode();
00516     MCOperand Saved = OutMI.getOperand(0);
00517     OutMI = MCInst();
00518     OutMI.setOpcode(Opcode);
00519     OutMI.addOperand(Saved);
00520     break;
00521   }
00522 
00523   case X86::EH_RETURN:
00524   case X86::EH_RETURN64: {
00525     OutMI = MCInst();
00526     OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
00527     break;
00528   }
00529 
00530   // TAILJMPd, TAILJMPd64 - Lower to the correct jump instructions.
00531   case X86::TAILJMPr:
00532   case X86::TAILJMPd:
00533   case X86::TAILJMPd64: {
00534     unsigned Opcode;
00535     switch (OutMI.getOpcode()) {
00536     default: llvm_unreachable("Invalid opcode");
00537     case X86::TAILJMPr: Opcode = X86::JMP32r; break;
00538     case X86::TAILJMPd:
00539     case X86::TAILJMPd64: Opcode = X86::JMP_1; break;
00540     }
00541 
00542     MCOperand Saved = OutMI.getOperand(0);
00543     OutMI = MCInst();
00544     OutMI.setOpcode(Opcode);
00545     OutMI.addOperand(Saved);
00546     break;
00547   }
00548 
00549   // These are pseudo-ops for OR to help with the OR->ADD transformation.  We do
00550   // this with an ugly goto in case the resultant OR uses EAX and needs the
00551   // short form.
00552   case X86::ADD16rr_DB:   OutMI.setOpcode(X86::OR16rr); goto ReSimplify;
00553   case X86::ADD32rr_DB:   OutMI.setOpcode(X86::OR32rr); goto ReSimplify;
00554   case X86::ADD64rr_DB:   OutMI.setOpcode(X86::OR64rr); goto ReSimplify;
00555   case X86::ADD16ri_DB:   OutMI.setOpcode(X86::OR16ri); goto ReSimplify;
00556   case X86::ADD32ri_DB:   OutMI.setOpcode(X86::OR32ri); goto ReSimplify;
00557   case X86::ADD64ri32_DB: OutMI.setOpcode(X86::OR64ri32); goto ReSimplify;
00558   case X86::ADD16ri8_DB:  OutMI.setOpcode(X86::OR16ri8); goto ReSimplify;
00559   case X86::ADD32ri8_DB:  OutMI.setOpcode(X86::OR32ri8); goto ReSimplify;
00560   case X86::ADD64ri8_DB:  OutMI.setOpcode(X86::OR64ri8); goto ReSimplify;
00561 
00562   // The assembler backend wants to see branches in their small form and relax
00563   // them to their large form.  The JIT can only handle the large form because
00564   // it does not do relaxation.  For now, translate the large form to the
00565   // small one here.
00566   case X86::JMP_4: OutMI.setOpcode(X86::JMP_1); break;
00567   case X86::JO_4:  OutMI.setOpcode(X86::JO_1); break;
00568   case X86::JNO_4: OutMI.setOpcode(X86::JNO_1); break;
00569   case X86::JB_4:  OutMI.setOpcode(X86::JB_1); break;
00570   case X86::JAE_4: OutMI.setOpcode(X86::JAE_1); break;
00571   case X86::JE_4:  OutMI.setOpcode(X86::JE_1); break;
00572   case X86::JNE_4: OutMI.setOpcode(X86::JNE_1); break;
00573   case X86::JBE_4: OutMI.setOpcode(X86::JBE_1); break;
00574   case X86::JA_4:  OutMI.setOpcode(X86::JA_1); break;
00575   case X86::JS_4:  OutMI.setOpcode(X86::JS_1); break;
00576   case X86::JNS_4: OutMI.setOpcode(X86::JNS_1); break;
00577   case X86::JP_4:  OutMI.setOpcode(X86::JP_1); break;
00578   case X86::JNP_4: OutMI.setOpcode(X86::JNP_1); break;
00579   case X86::JL_4:  OutMI.setOpcode(X86::JL_1); break;
00580   case X86::JGE_4: OutMI.setOpcode(X86::JGE_1); break;
00581   case X86::JLE_4: OutMI.setOpcode(X86::JLE_1); break;
00582   case X86::JG_4:  OutMI.setOpcode(X86::JG_1); break;
00583 
00584   // Atomic load and store require a separate pseudo-inst because Acquire
00585   // implies mayStore and Release implies mayLoad; fix these to regular MOV
00586   // instructions here
00587   case X86::ACQUIRE_MOV8rm:    OutMI.setOpcode(X86::MOV8rm); goto ReSimplify;
00588   case X86::ACQUIRE_MOV16rm:   OutMI.setOpcode(X86::MOV16rm); goto ReSimplify;
00589   case X86::ACQUIRE_MOV32rm:   OutMI.setOpcode(X86::MOV32rm); goto ReSimplify;
00590   case X86::ACQUIRE_MOV64rm:   OutMI.setOpcode(X86::MOV64rm); goto ReSimplify;
00591   case X86::RELEASE_MOV8mr:    OutMI.setOpcode(X86::MOV8mr); goto ReSimplify;
00592   case X86::RELEASE_MOV16mr:   OutMI.setOpcode(X86::MOV16mr); goto ReSimplify;
00593   case X86::RELEASE_MOV32mr:   OutMI.setOpcode(X86::MOV32mr); goto ReSimplify;
00594   case X86::RELEASE_MOV64mr:   OutMI.setOpcode(X86::MOV64mr); goto ReSimplify;
00595   case X86::RELEASE_MOV8mi:    OutMI.setOpcode(X86::MOV8mi); goto ReSimplify;
00596   case X86::RELEASE_MOV16mi:   OutMI.setOpcode(X86::MOV16mi); goto ReSimplify;
00597   case X86::RELEASE_MOV32mi:   OutMI.setOpcode(X86::MOV32mi); goto ReSimplify;
00598   case X86::RELEASE_MOV64mi32: OutMI.setOpcode(X86::MOV64mi32); goto ReSimplify;
00599   case X86::RELEASE_ADD8mi:    OutMI.setOpcode(X86::ADD8mi); goto ReSimplify;
00600   case X86::RELEASE_ADD32mi:   OutMI.setOpcode(X86::ADD32mi); goto ReSimplify;
00601   case X86::RELEASE_ADD64mi32: OutMI.setOpcode(X86::ADD64mi32); goto ReSimplify;
00602   case X86::RELEASE_AND8mi:    OutMI.setOpcode(X86::AND8mi); goto ReSimplify;
00603   case X86::RELEASE_AND32mi:   OutMI.setOpcode(X86::AND32mi); goto ReSimplify;
00604   case X86::RELEASE_AND64mi32: OutMI.setOpcode(X86::AND64mi32); goto ReSimplify;
00605   case X86::RELEASE_OR8mi:     OutMI.setOpcode(X86::OR8mi); goto ReSimplify;
00606   case X86::RELEASE_OR32mi:    OutMI.setOpcode(X86::OR32mi); goto ReSimplify;
00607   case X86::RELEASE_OR64mi32:  OutMI.setOpcode(X86::OR64mi32); goto ReSimplify;
00608   case X86::RELEASE_XOR8mi:    OutMI.setOpcode(X86::XOR8mi); goto ReSimplify;
00609   case X86::RELEASE_XOR32mi:   OutMI.setOpcode(X86::XOR32mi); goto ReSimplify;
00610   case X86::RELEASE_XOR64mi32: OutMI.setOpcode(X86::XOR64mi32); goto ReSimplify;
00611   case X86::RELEASE_INC8m:     OutMI.setOpcode(X86::INC8m); goto ReSimplify;
00612   case X86::RELEASE_INC16m:    OutMI.setOpcode(X86::INC16m); goto ReSimplify;
00613   case X86::RELEASE_INC32m:    OutMI.setOpcode(X86::INC32m); goto ReSimplify;
00614   case X86::RELEASE_INC64m:    OutMI.setOpcode(X86::INC64m); goto ReSimplify;
00615   case X86::RELEASE_DEC8m:     OutMI.setOpcode(X86::DEC8m); goto ReSimplify;
00616   case X86::RELEASE_DEC16m:    OutMI.setOpcode(X86::DEC16m); goto ReSimplify;
00617   case X86::RELEASE_DEC32m:    OutMI.setOpcode(X86::DEC32m); goto ReSimplify;
00618   case X86::RELEASE_DEC64m:    OutMI.setOpcode(X86::DEC64m); goto ReSimplify;
00619 
00620   // We don't currently select the correct instruction form for instructions
00621   // which have a short %eax, etc. form. Handle this by custom lowering, for
00622   // now.
00623   //
00624   // Note, we are currently not handling the following instructions:
00625   // MOV64ao8, MOV64o8a
00626   // XCHG16ar, XCHG32ar, XCHG64ar
00627   case X86::MOV8mr_NOREX:
00628   case X86::MOV8mr:     SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV8ao8); break;
00629   case X86::MOV8rm_NOREX:
00630   case X86::MOV8rm:     SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV8o8a); break;
00631   case X86::MOV16mr:    SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV16ao16); break;
00632   case X86::MOV16rm:    SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV16o16a); break;
00633   case X86::MOV32mr:    SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV32ao32); break;
00634   case X86::MOV32rm:    SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV32o32a); break;
00635 
00636   case X86::ADC8ri:     SimplifyShortImmForm(OutMI, X86::ADC8i8);    break;
00637   case X86::ADC16ri:    SimplifyShortImmForm(OutMI, X86::ADC16i16);  break;
00638   case X86::ADC32ri:    SimplifyShortImmForm(OutMI, X86::ADC32i32);  break;
00639   case X86::ADC64ri32:  SimplifyShortImmForm(OutMI, X86::ADC64i32);  break;
00640   case X86::ADD8ri:     SimplifyShortImmForm(OutMI, X86::ADD8i8);    break;
00641   case X86::ADD16ri:    SimplifyShortImmForm(OutMI, X86::ADD16i16);  break;
00642   case X86::ADD32ri:    SimplifyShortImmForm(OutMI, X86::ADD32i32);  break;
00643   case X86::ADD64ri32:  SimplifyShortImmForm(OutMI, X86::ADD64i32);  break;
00644   case X86::AND8ri:     SimplifyShortImmForm(OutMI, X86::AND8i8);    break;
00645   case X86::AND16ri:    SimplifyShortImmForm(OutMI, X86::AND16i16);  break;
00646   case X86::AND32ri:    SimplifyShortImmForm(OutMI, X86::AND32i32);  break;
00647   case X86::AND64ri32:  SimplifyShortImmForm(OutMI, X86::AND64i32);  break;
00648   case X86::CMP8ri:     SimplifyShortImmForm(OutMI, X86::CMP8i8);    break;
00649   case X86::CMP16ri:    SimplifyShortImmForm(OutMI, X86::CMP16i16);  break;
00650   case X86::CMP32ri:    SimplifyShortImmForm(OutMI, X86::CMP32i32);  break;
00651   case X86::CMP64ri32:  SimplifyShortImmForm(OutMI, X86::CMP64i32);  break;
00652   case X86::OR8ri:      SimplifyShortImmForm(OutMI, X86::OR8i8);     break;
00653   case X86::OR16ri:     SimplifyShortImmForm(OutMI, X86::OR16i16);   break;
00654   case X86::OR32ri:     SimplifyShortImmForm(OutMI, X86::OR32i32);   break;
00655   case X86::OR64ri32:   SimplifyShortImmForm(OutMI, X86::OR64i32);   break;
00656   case X86::SBB8ri:     SimplifyShortImmForm(OutMI, X86::SBB8i8);    break;
00657   case X86::SBB16ri:    SimplifyShortImmForm(OutMI, X86::SBB16i16);  break;
00658   case X86::SBB32ri:    SimplifyShortImmForm(OutMI, X86::SBB32i32);  break;
00659   case X86::SBB64ri32:  SimplifyShortImmForm(OutMI, X86::SBB64i32);  break;
00660   case X86::SUB8ri:     SimplifyShortImmForm(OutMI, X86::SUB8i8);    break;
00661   case X86::SUB16ri:    SimplifyShortImmForm(OutMI, X86::SUB16i16);  break;
00662   case X86::SUB32ri:    SimplifyShortImmForm(OutMI, X86::SUB32i32);  break;
00663   case X86::SUB64ri32:  SimplifyShortImmForm(OutMI, X86::SUB64i32);  break;
00664   case X86::TEST8ri:    SimplifyShortImmForm(OutMI, X86::TEST8i8);   break;
00665   case X86::TEST16ri:   SimplifyShortImmForm(OutMI, X86::TEST16i16); break;
00666   case X86::TEST32ri:   SimplifyShortImmForm(OutMI, X86::TEST32i32); break;
00667   case X86::TEST64ri32: SimplifyShortImmForm(OutMI, X86::TEST64i32); break;
00668   case X86::XOR8ri:     SimplifyShortImmForm(OutMI, X86::XOR8i8);    break;
00669   case X86::XOR16ri:    SimplifyShortImmForm(OutMI, X86::XOR16i16);  break;
00670   case X86::XOR32ri:    SimplifyShortImmForm(OutMI, X86::XOR32i32);  break;
00671   case X86::XOR64ri32:  SimplifyShortImmForm(OutMI, X86::XOR64i32);  break;
00672 
00673   // Try to shrink some forms of movsx.
00674   case X86::MOVSX16rr8:
00675   case X86::MOVSX32rr16:
00676   case X86::MOVSX64rr32:
00677     SimplifyMOVSX(OutMI);
00678     break;
00679   }
00680 }
00681 
00682 void X86AsmPrinter::LowerTlsAddr(X86MCInstLower &MCInstLowering,
00683                                  const MachineInstr &MI) {
00684 
00685   bool is64Bits = MI.getOpcode() == X86::TLS_addr64 ||
00686                   MI.getOpcode() == X86::TLS_base_addr64;
00687 
00688   bool needsPadding = MI.getOpcode() == X86::TLS_addr64;
00689 
00690   MCContext &context = OutStreamer.getContext();
00691 
00692   if (needsPadding)
00693     EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
00694 
00695   MCSymbolRefExpr::VariantKind SRVK;
00696   switch (MI.getOpcode()) {
00697     case X86::TLS_addr32:
00698     case X86::TLS_addr64:
00699       SRVK = MCSymbolRefExpr::VK_TLSGD;
00700       break;
00701     case X86::TLS_base_addr32:
00702       SRVK = MCSymbolRefExpr::VK_TLSLDM;
00703       break;
00704     case X86::TLS_base_addr64:
00705       SRVK = MCSymbolRefExpr::VK_TLSLD;
00706       break;
00707     default:
00708       llvm_unreachable("unexpected opcode");
00709   }
00710 
00711   MCSymbol *sym = MCInstLowering.GetSymbolFromOperand(MI.getOperand(3));
00712   const MCSymbolRefExpr *symRef = MCSymbolRefExpr::Create(sym, SRVK, context);
00713 
00714   MCInst LEA;
00715   if (is64Bits) {
00716     LEA.setOpcode(X86::LEA64r);
00717     LEA.addOperand(MCOperand::CreateReg(X86::RDI)); // dest
00718     LEA.addOperand(MCOperand::CreateReg(X86::RIP)); // base
00719     LEA.addOperand(MCOperand::CreateImm(1));        // scale
00720     LEA.addOperand(MCOperand::CreateReg(0));        // index
00721     LEA.addOperand(MCOperand::CreateExpr(symRef));  // disp
00722     LEA.addOperand(MCOperand::CreateReg(0));        // seg
00723   } else if (SRVK == MCSymbolRefExpr::VK_TLSLDM) {
00724     LEA.setOpcode(X86::LEA32r);
00725     LEA.addOperand(MCOperand::CreateReg(X86::EAX)); // dest
00726     LEA.addOperand(MCOperand::CreateReg(X86::EBX)); // base
00727     LEA.addOperand(MCOperand::CreateImm(1));        // scale
00728     LEA.addOperand(MCOperand::CreateReg(0));        // index
00729     LEA.addOperand(MCOperand::CreateExpr(symRef));  // disp
00730     LEA.addOperand(MCOperand::CreateReg(0));        // seg
00731   } else {
00732     LEA.setOpcode(X86::LEA32r);
00733     LEA.addOperand(MCOperand::CreateReg(X86::EAX)); // dest
00734     LEA.addOperand(MCOperand::CreateReg(0));        // base
00735     LEA.addOperand(MCOperand::CreateImm(1));        // scale
00736     LEA.addOperand(MCOperand::CreateReg(X86::EBX)); // index
00737     LEA.addOperand(MCOperand::CreateExpr(symRef));  // disp
00738     LEA.addOperand(MCOperand::CreateReg(0));        // seg
00739   }
00740   EmitAndCountInstruction(LEA);
00741 
00742   if (needsPadding) {
00743     EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
00744     EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
00745     EmitAndCountInstruction(MCInstBuilder(X86::REX64_PREFIX));
00746   }
00747 
00748   StringRef name = is64Bits ? "__tls_get_addr" : "___tls_get_addr";
00749   MCSymbol *tlsGetAddr = context.GetOrCreateSymbol(name);
00750   const MCSymbolRefExpr *tlsRef =
00751     MCSymbolRefExpr::Create(tlsGetAddr,
00752                             MCSymbolRefExpr::VK_PLT,
00753                             context);
00754 
00755   EmitAndCountInstruction(MCInstBuilder(is64Bits ? X86::CALL64pcrel32
00756                                                  : X86::CALLpcrel32)
00757                             .addExpr(tlsRef));
00758 }
00759 
00760 /// \brief Emit the optimal amount of multi-byte nops on X86.
00761 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit, const MCSubtargetInfo &STI) {
00762   // This works only for 64bit. For 32bit we have to do additional checking if
00763   // the CPU supports multi-byte nops.
00764   assert(Is64Bit && "EmitNops only supports X86-64");
00765   while (NumBytes) {
00766     unsigned Opc, BaseReg, ScaleVal, IndexReg, Displacement, SegmentReg;
00767     Opc = IndexReg = Displacement = SegmentReg = 0;
00768     BaseReg = X86::RAX; ScaleVal = 1;
00769     switch (NumBytes) {
00770     case  0: llvm_unreachable("Zero nops?"); break;
00771     case  1: NumBytes -=  1; Opc = X86::NOOP; break;
00772     case  2: NumBytes -=  2; Opc = X86::XCHG16ar; break;
00773     case  3: NumBytes -=  3; Opc = X86::NOOPL; break;
00774     case  4: NumBytes -=  4; Opc = X86::NOOPL; Displacement = 8; break;
00775     case  5: NumBytes -=  5; Opc = X86::NOOPL; Displacement = 8;
00776              IndexReg = X86::RAX; break;
00777     case  6: NumBytes -=  6; Opc = X86::NOOPW; Displacement = 8;
00778              IndexReg = X86::RAX; break;
00779     case  7: NumBytes -=  7; Opc = X86::NOOPL; Displacement = 512; break;
00780     case  8: NumBytes -=  8; Opc = X86::NOOPL; Displacement = 512;
00781              IndexReg = X86::RAX; break;
00782     case  9: NumBytes -=  9; Opc = X86::NOOPW; Displacement = 512;
00783              IndexReg = X86::RAX; break;
00784     default: NumBytes -= 10; Opc = X86::NOOPW; Displacement = 512;
00785              IndexReg = X86::RAX; SegmentReg = X86::CS; break;
00786     }
00787 
00788     unsigned NumPrefixes = std::min(NumBytes, 5U);
00789     NumBytes -= NumPrefixes;
00790     for (unsigned i = 0; i != NumPrefixes; ++i)
00791       OS.EmitBytes("\x66");
00792 
00793     switch (Opc) {
00794     default: llvm_unreachable("Unexpected opcode"); break;
00795     case X86::NOOP:
00796       OS.EmitInstruction(MCInstBuilder(Opc), STI);
00797       break;
00798     case X86::XCHG16ar:
00799       OS.EmitInstruction(MCInstBuilder(Opc).addReg(X86::AX), STI);
00800       break;
00801     case X86::NOOPL:
00802     case X86::NOOPW:
00803       OS.EmitInstruction(MCInstBuilder(Opc).addReg(BaseReg)
00804                          .addImm(ScaleVal).addReg(IndexReg)
00805                          .addImm(Displacement).addReg(SegmentReg), STI);
00806       break;
00807     }
00808   } // while (NumBytes)
00809 }
00810 
00811 // Lower a stackmap of the form:
00812 // <id>, <shadowBytes>, ...
00813 void X86AsmPrinter::LowerSTACKMAP(const MachineInstr &MI) {
00814   SMShadowTracker.emitShadowPadding(OutStreamer, getSubtargetInfo());
00815   SM.recordStackMap(MI);
00816   unsigned NumShadowBytes = MI.getOperand(1).getImm();
00817   SMShadowTracker.reset(NumShadowBytes);
00818 }
00819 
00820 // Lower a patchpoint of the form:
00821 // [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
00822 void X86AsmPrinter::LowerPATCHPOINT(const MachineInstr &MI) {
00823   assert(Subtarget->is64Bit() && "Patchpoint currently only supports X86-64");
00824 
00825   SMShadowTracker.emitShadowPadding(OutStreamer, getSubtargetInfo());
00826 
00827   SM.recordPatchPoint(MI);
00828 
00829   PatchPointOpers opers(&MI);
00830   unsigned ScratchIdx = opers.getNextScratchIdx();
00831   unsigned EncodedBytes = 0;
00832   int64_t CallTarget = opers.getMetaOper(PatchPointOpers::TargetPos).getImm();
00833   if (CallTarget) {
00834     // Emit MOV to materialize the target address and the CALL to target.
00835     // This is encoded with 12-13 bytes, depending on which register is used.
00836     unsigned ScratchReg = MI.getOperand(ScratchIdx).getReg();
00837     if (X86II::isX86_64ExtendedReg(ScratchReg))
00838       EncodedBytes = 13;
00839     else
00840       EncodedBytes = 12;
00841     EmitAndCountInstruction(MCInstBuilder(X86::MOV64ri).addReg(ScratchReg)
00842                                                        .addImm(CallTarget));
00843     EmitAndCountInstruction(MCInstBuilder(X86::CALL64r).addReg(ScratchReg));
00844   }
00845   // Emit padding.
00846   unsigned NumBytes = opers.getMetaOper(PatchPointOpers::NBytesPos).getImm();
00847   assert(NumBytes >= EncodedBytes &&
00848          "Patchpoint can't request size less than the length of a call.");
00849 
00850   EmitNops(OutStreamer, NumBytes - EncodedBytes, Subtarget->is64Bit(),
00851            getSubtargetInfo());
00852 }
00853 
00854 // Returns instruction preceding MBBI in MachineFunction.
00855 // If MBBI is the first instruction of the first basic block, returns null.
00856 static MachineBasicBlock::const_iterator
00857 PrevCrossBBInst(MachineBasicBlock::const_iterator MBBI) {
00858   const MachineBasicBlock *MBB = MBBI->getParent();
00859   while (MBBI == MBB->begin()) {
00860     if (MBB == MBB->getParent()->begin())
00861       return nullptr;
00862     MBB = MBB->getPrevNode();
00863     MBBI = MBB->end();
00864   }
00865   return --MBBI;
00866 }
00867 
00868 static const Constant *getConstantFromPool(const MachineInstr &MI,
00869                                            const MachineOperand &Op) {
00870   if (!Op.isCPI())
00871     return nullptr;
00872 
00873   ArrayRef<MachineConstantPoolEntry> Constants =
00874       MI.getParent()->getParent()->getConstantPool()->getConstants();
00875   const MachineConstantPoolEntry &ConstantEntry =
00876       Constants[Op.getIndex()];
00877 
00878   // Bail if this is a machine constant pool entry, we won't be able to dig out
00879   // anything useful.
00880   if (ConstantEntry.isMachineConstantPoolEntry())
00881     return nullptr;
00882 
00883   auto *C = dyn_cast<Constant>(ConstantEntry.Val.ConstVal);
00884   assert((!C || ConstantEntry.getType() == C->getType()) &&
00885          "Expected a constant of the same type!");
00886   return C;
00887 }
00888 
00889 static std::string getShuffleComment(const MachineOperand &DstOp,
00890                                      const MachineOperand &SrcOp,
00891                                      ArrayRef<int> Mask) {
00892   std::string Comment;
00893 
00894   // Compute the name for a register. This is really goofy because we have
00895   // multiple instruction printers that could (in theory) use different
00896   // names. Fortunately most people use the ATT style (outside of Windows)
00897   // and they actually agree on register naming here. Ultimately, this is
00898   // a comment, and so its OK if it isn't perfect.
00899   auto GetRegisterName = [](unsigned RegNum) -> StringRef {
00900     return X86ATTInstPrinter::getRegisterName(RegNum);
00901   };
00902 
00903   StringRef DstName = DstOp.isReg() ? GetRegisterName(DstOp.getReg()) : "mem";
00904   StringRef SrcName = SrcOp.isReg() ? GetRegisterName(SrcOp.getReg()) : "mem";
00905 
00906   raw_string_ostream CS(Comment);
00907   CS << DstName << " = ";
00908   bool NeedComma = false;
00909   bool InSrc = false;
00910   for (int M : Mask) {
00911     // Wrap up any prior entry...
00912     if (M == SM_SentinelZero && InSrc) {
00913       InSrc = false;
00914       CS << "]";
00915     }
00916     if (NeedComma)
00917       CS << ",";
00918     else
00919       NeedComma = true;
00920 
00921     // Print this shuffle...
00922     if (M == SM_SentinelZero) {
00923       CS << "zero";
00924     } else {
00925       if (!InSrc) {
00926         InSrc = true;
00927         CS << SrcName << "[";
00928       }
00929       if (M == SM_SentinelUndef)
00930         CS << "u";
00931       else
00932         CS << M;
00933     }
00934   }
00935   if (InSrc)
00936     CS << "]";
00937   CS.flush();
00938 
00939   return Comment;
00940 }
00941 
00942 void X86AsmPrinter::EmitInstruction(const MachineInstr *MI) {
00943   X86MCInstLower MCInstLowering(*MF, *this);
00944   const X86RegisterInfo *RI = static_cast<const X86RegisterInfo *>(
00945       TM.getSubtargetImpl()->getRegisterInfo());
00946 
00947   switch (MI->getOpcode()) {
00948   case TargetOpcode::DBG_VALUE:
00949     llvm_unreachable("Should be handled target independently");
00950 
00951   // Emit nothing here but a comment if we can.
00952   case X86::Int_MemBarrier:
00953     OutStreamer.emitRawComment("MEMBARRIER");
00954     return;
00955 
00956 
00957   case X86::EH_RETURN:
00958   case X86::EH_RETURN64: {
00959     // Lower these as normal, but add some comments.
00960     unsigned Reg = MI->getOperand(0).getReg();
00961     OutStreamer.AddComment(StringRef("eh_return, addr: %") +
00962                            X86ATTInstPrinter::getRegisterName(Reg));
00963     break;
00964   }
00965   case X86::TAILJMPr:
00966   case X86::TAILJMPd:
00967   case X86::TAILJMPd64:
00968     // Lower these as normal, but add some comments.
00969     OutStreamer.AddComment("TAILCALL");
00970     break;
00971 
00972   case X86::TLS_addr32:
00973   case X86::TLS_addr64:
00974   case X86::TLS_base_addr32:
00975   case X86::TLS_base_addr64:
00976     return LowerTlsAddr(MCInstLowering, *MI);
00977 
00978   case X86::MOVPC32r: {
00979     // This is a pseudo op for a two instruction sequence with a label, which
00980     // looks like:
00981     //     call "L1$pb"
00982     // "L1$pb":
00983     //     popl %esi
00984 
00985     // Emit the call.
00986     MCSymbol *PICBase = MF->getPICBaseSymbol();
00987     // FIXME: We would like an efficient form for this, so we don't have to do a
00988     // lot of extra uniquing.
00989     EmitAndCountInstruction(MCInstBuilder(X86::CALLpcrel32)
00990       .addExpr(MCSymbolRefExpr::Create(PICBase, OutContext)));
00991 
00992     // Emit the label.
00993     OutStreamer.EmitLabel(PICBase);
00994 
00995     // popl $reg
00996     EmitAndCountInstruction(MCInstBuilder(X86::POP32r)
00997                             .addReg(MI->getOperand(0).getReg()));
00998     return;
00999   }
01000 
01001   case X86::ADD32ri: {
01002     // Lower the MO_GOT_ABSOLUTE_ADDRESS form of ADD32ri.
01003     if (MI->getOperand(2).getTargetFlags() != X86II::MO_GOT_ABSOLUTE_ADDRESS)
01004       break;
01005 
01006     // Okay, we have something like:
01007     //  EAX = ADD32ri EAX, MO_GOT_ABSOLUTE_ADDRESS(@MYGLOBAL)
01008 
01009     // For this, we want to print something like:
01010     //   MYGLOBAL + (. - PICBASE)
01011     // However, we can't generate a ".", so just emit a new label here and refer
01012     // to it.
01013     MCSymbol *DotSym = OutContext.CreateTempSymbol();
01014     OutStreamer.EmitLabel(DotSym);
01015 
01016     // Now that we have emitted the label, lower the complex operand expression.
01017     MCSymbol *OpSym = MCInstLowering.GetSymbolFromOperand(MI->getOperand(2));
01018 
01019     const MCExpr *DotExpr = MCSymbolRefExpr::Create(DotSym, OutContext);
01020     const MCExpr *PICBase =
01021       MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), OutContext);
01022     DotExpr = MCBinaryExpr::CreateSub(DotExpr, PICBase, OutContext);
01023 
01024     DotExpr = MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(OpSym,OutContext),
01025                                       DotExpr, OutContext);
01026 
01027     EmitAndCountInstruction(MCInstBuilder(X86::ADD32ri)
01028       .addReg(MI->getOperand(0).getReg())
01029       .addReg(MI->getOperand(1).getReg())
01030       .addExpr(DotExpr));
01031     return;
01032   }
01033 
01034   case TargetOpcode::STACKMAP:
01035     return LowerSTACKMAP(*MI);
01036 
01037   case TargetOpcode::PATCHPOINT:
01038     return LowerPATCHPOINT(*MI);
01039 
01040   case X86::MORESTACK_RET:
01041     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
01042     return;
01043 
01044   case X86::MORESTACK_RET_RESTORE_R10:
01045     // Return, then restore R10.
01046     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
01047     EmitAndCountInstruction(MCInstBuilder(X86::MOV64rr)
01048                             .addReg(X86::R10)
01049                             .addReg(X86::RAX));
01050     return;
01051 
01052   case X86::SEH_PushReg:
01053     OutStreamer.EmitWinCFIPushReg(RI->getSEHRegNum(MI->getOperand(0).getImm()));
01054     return;
01055 
01056   case X86::SEH_SaveReg:
01057     OutStreamer.EmitWinCFISaveReg(RI->getSEHRegNum(MI->getOperand(0).getImm()),
01058                                   MI->getOperand(1).getImm());
01059     return;
01060 
01061   case X86::SEH_SaveXMM:
01062     OutStreamer.EmitWinCFISaveXMM(RI->getSEHRegNum(MI->getOperand(0).getImm()),
01063                                   MI->getOperand(1).getImm());
01064     return;
01065 
01066   case X86::SEH_StackAlloc:
01067     OutStreamer.EmitWinCFIAllocStack(MI->getOperand(0).getImm());
01068     return;
01069 
01070   case X86::SEH_SetFrame:
01071     OutStreamer.EmitWinCFISetFrame(RI->getSEHRegNum(MI->getOperand(0).getImm()),
01072                                    MI->getOperand(1).getImm());
01073     return;
01074 
01075   case X86::SEH_PushFrame:
01076     OutStreamer.EmitWinCFIPushFrame(MI->getOperand(0).getImm());
01077     return;
01078 
01079   case X86::SEH_EndPrologue:
01080     OutStreamer.EmitWinCFIEndProlog();
01081     return;
01082 
01083   case X86::SEH_Epilogue: {
01084     MachineBasicBlock::const_iterator MBBI(MI);
01085     // Check if preceded by a call and emit nop if so.
01086     for (MBBI = PrevCrossBBInst(MBBI); MBBI; MBBI = PrevCrossBBInst(MBBI)) {
01087       // Conservatively assume that pseudo instructions don't emit code and keep
01088       // looking for a call. We may emit an unnecessary nop in some cases.
01089       if (!MBBI->isPseudo()) {
01090         if (MBBI->isCall())
01091           EmitAndCountInstruction(MCInstBuilder(X86::NOOP));
01092         break;
01093       }
01094     }
01095     return;
01096   }
01097 
01098     // Lower PSHUFB and VPERMILP normally but add a comment if we can find
01099     // a constant shuffle mask. We won't be able to do this at the MC layer
01100     // because the mask isn't an immediate.
01101   case X86::PSHUFBrm:
01102   case X86::VPSHUFBrm:
01103   case X86::VPSHUFBYrm: {
01104     if (!OutStreamer.isVerboseAsm())
01105       break;
01106     assert(MI->getNumOperands() > 5 &&
01107            "We should always have at least 5 operands!");
01108     const MachineOperand &DstOp = MI->getOperand(0);
01109     const MachineOperand &SrcOp = MI->getOperand(1);
01110     const MachineOperand &MaskOp = MI->getOperand(5);
01111 
01112     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
01113       SmallVector<int, 16> Mask;
01114       DecodePSHUFBMask(C, Mask);
01115       if (!Mask.empty())
01116         OutStreamer.AddComment(getShuffleComment(DstOp, SrcOp, Mask));
01117     }
01118     break;
01119   }
01120   case X86::VPERMILPSrm:
01121   case X86::VPERMILPDrm:
01122   case X86::VPERMILPSYrm:
01123   case X86::VPERMILPDYrm: {
01124     if (!OutStreamer.isVerboseAsm())
01125       break;
01126     assert(MI->getNumOperands() > 5 &&
01127            "We should always have at least 5 operands!");
01128     const MachineOperand &DstOp = MI->getOperand(0);
01129     const MachineOperand &SrcOp = MI->getOperand(1);
01130     const MachineOperand &MaskOp = MI->getOperand(5);
01131 
01132     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
01133       SmallVector<int, 16> Mask;
01134       DecodeVPERMILPMask(C, Mask);
01135       if (!Mask.empty())
01136         OutStreamer.AddComment(getShuffleComment(DstOp, SrcOp, Mask));
01137     }
01138     break;
01139   }
01140 
01141     // For loads from a constant pool to a vector register, print the constant
01142     // loaded.
01143   case X86::MOVAPDrm:
01144   case X86::VMOVAPDrm:
01145   case X86::VMOVAPDYrm:
01146   case X86::MOVUPDrm:
01147   case X86::VMOVUPDrm:
01148   case X86::VMOVUPDYrm:
01149   case X86::MOVAPSrm:
01150   case X86::VMOVAPSrm:
01151   case X86::VMOVAPSYrm:
01152   case X86::MOVUPSrm:
01153   case X86::VMOVUPSrm:
01154   case X86::VMOVUPSYrm:
01155   case X86::MOVDQArm:
01156   case X86::VMOVDQArm:
01157   case X86::VMOVDQAYrm:
01158   case X86::MOVDQUrm:
01159   case X86::VMOVDQUrm:
01160   case X86::VMOVDQUYrm:
01161     if (!OutStreamer.isVerboseAsm())
01162       break;
01163     if (MI->getNumOperands() > 4)
01164     if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
01165       std::string Comment;
01166       raw_string_ostream CS(Comment);
01167       const MachineOperand &DstOp = MI->getOperand(0);
01168       CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
01169       if (auto *CDS = dyn_cast<ConstantDataSequential>(C)) {
01170         CS << "[";
01171         for (int i = 0, NumElements = CDS->getNumElements(); i < NumElements; ++i) {
01172           if (i != 0)
01173             CS << ",";
01174           if (CDS->getElementType()->isIntegerTy())
01175             CS << CDS->getElementAsInteger(i);
01176           else if (CDS->getElementType()->isFloatTy())
01177             CS << CDS->getElementAsFloat(i);
01178           else if (CDS->getElementType()->isDoubleTy())
01179             CS << CDS->getElementAsDouble(i);
01180           else
01181             CS << "?";
01182         }
01183         CS << "]";
01184         OutStreamer.AddComment(CS.str());
01185       } else if (auto *CV = dyn_cast<ConstantVector>(C)) {
01186         CS << "<";
01187         for (int i = 0, NumOperands = CV->getNumOperands(); i < NumOperands; ++i) {
01188           if (i != 0)
01189             CS << ",";
01190           Constant *COp = CV->getOperand(i);
01191           if (isa<UndefValue>(COp)) {
01192             CS << "u";
01193           } else if (auto *CI = dyn_cast<ConstantInt>(COp)) {
01194             CS << CI->getZExtValue();
01195           } else if (auto *CF = dyn_cast<ConstantFP>(COp)) {
01196             SmallString<32> Str;
01197             CF->getValueAPF().toString(Str);
01198             CS << Str;
01199           } else {
01200             CS << "?";
01201           }
01202         }
01203         CS << ">";
01204         OutStreamer.AddComment(CS.str());
01205       }
01206     }
01207     break;
01208   }
01209 
01210   MCInst TmpInst;
01211   MCInstLowering.Lower(MI, TmpInst);
01212 
01213   // Stackmap shadows cannot include branch targets, so we can count the bytes
01214   // in a call towards the shadow, but must ensure that the no thread returns
01215   // in to the stackmap shadow.  The only way to achieve this is if the call
01216   // is at the end of the shadow.
01217   if (MI->isCall()) {
01218     // Count then size of the call towards the shadow
01219     SMShadowTracker.count(TmpInst, getSubtargetInfo());
01220     // Then flush the shadow so that we fill with nops before the call, not
01221     // after it.
01222     SMShadowTracker.emitShadowPadding(OutStreamer, getSubtargetInfo());
01223     // Then emit the call
01224     OutStreamer.EmitInstruction(TmpInst, getSubtargetInfo());
01225     return;
01226   }
01227 
01228   EmitAndCountInstruction(TmpInst);
01229 }