1 //===-- X86MCInstLower.cpp - Convert X86 MachineInstr to an MCInst --------===//
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 code to lower X86 MachineInstrs to their corresponding
10 // MCInst records.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "MCTargetDesc/X86ATTInstPrinter.h"
15 #include "MCTargetDesc/X86BaseInfo.h"
16 #include "MCTargetDesc/X86InstComments.h"
17 #include "MCTargetDesc/X86TargetStreamer.h"
18 #include "Utils/X86ShuffleDecode.h"
19 #include "X86AsmPrinter.h"
20 #include "X86RegisterInfo.h"
21 #include "X86ShuffleDecodeConstantPool.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/iterator_range.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
28 #include "llvm/CodeGen/MachineOperand.h"
29 #include "llvm/CodeGen/StackMaps.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/GlobalValue.h"
32 #include "llvm/IR/Mangler.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCCodeEmitter.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCExpr.h"
37 #include "llvm/MC/MCFixup.h"
38 #include "llvm/MC/MCInst.h"
39 #include "llvm/MC/MCInstBuilder.h"
40 #include "llvm/MC/MCSection.h"
41 #include "llvm/MC/MCSectionELF.h"
42 #include "llvm/MC/MCStreamer.h"
43 #include "llvm/MC/MCSymbol.h"
44 #include "llvm/MC/MCSymbolELF.h"
45 #include "llvm/Target/TargetLoweringObjectFile.h"
46 
47 using namespace llvm;
48 
49 namespace {
50 
51 /// X86MCInstLower - This class is used to lower an MachineInstr into an MCInst.
52 class X86MCInstLower {
53   MCContext &Ctx;
54   const MachineFunction &MF;
55   const TargetMachine &TM;
56   const MCAsmInfo &MAI;
57   X86AsmPrinter &AsmPrinter;
58 
59 public:
60   X86MCInstLower(const MachineFunction &MF, X86AsmPrinter &asmprinter);
61 
62   Optional<MCOperand> LowerMachineOperand(const MachineInstr *MI,
63                                           const MachineOperand &MO) const;
64   void Lower(const MachineInstr *MI, MCInst &OutMI) const;
65 
66   MCSymbol *GetSymbolFromOperand(const MachineOperand &MO) const;
67   MCOperand LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const;
68 
69 private:
70   MachineModuleInfoMachO &getMachOMMI() const;
71 };
72 
73 } // end anonymous namespace
74 
75 /// A RAII helper which defines a region of instructions which can't have
76 /// padding added between them for correctness.
77 struct NoAutoPaddingScope {
78   MCStreamer &OS;
79   const bool OldAllowAutoPadding;
80   NoAutoPaddingScope(MCStreamer &OS)
81       : OS(OS), OldAllowAutoPadding(OS.getAllowAutoPadding()) {
82     changeAndComment(false);
83   }
84   ~NoAutoPaddingScope() { changeAndComment(OldAllowAutoPadding); }
85   void changeAndComment(bool b) {
86     if (b == OS.getAllowAutoPadding())
87       return;
88     OS.setAllowAutoPadding(b);
89     if (b)
90       OS.emitRawComment("autopadding");
91     else
92       OS.emitRawComment("noautopadding");
93   }
94 };
95 
96 // Emit a minimal sequence of nops spanning NumBytes bytes.
97 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
98                      const MCSubtargetInfo &STI);
99 
100 void X86AsmPrinter::StackMapShadowTracker::count(MCInst &Inst,
101                                                  const MCSubtargetInfo &STI,
102                                                  MCCodeEmitter *CodeEmitter) {
103   if (InShadow) {
104     SmallString<256> Code;
105     SmallVector<MCFixup, 4> Fixups;
106     raw_svector_ostream VecOS(Code);
107     CodeEmitter->encodeInstruction(Inst, VecOS, Fixups, STI);
108     CurrentShadowSize += Code.size();
109     if (CurrentShadowSize >= RequiredShadowSize)
110       InShadow = false; // The shadow is big enough. Stop counting.
111   }
112 }
113 
114 void X86AsmPrinter::StackMapShadowTracker::emitShadowPadding(
115     MCStreamer &OutStreamer, const MCSubtargetInfo &STI) {
116   if (InShadow && CurrentShadowSize < RequiredShadowSize) {
117     InShadow = false;
118     EmitNops(OutStreamer, RequiredShadowSize - CurrentShadowSize,
119              MF->getSubtarget<X86Subtarget>().is64Bit(), STI);
120   }
121 }
122 
123 void X86AsmPrinter::EmitAndCountInstruction(MCInst &Inst) {
124   OutStreamer->emitInstruction(Inst, getSubtargetInfo());
125   SMShadowTracker.count(Inst, getSubtargetInfo(), CodeEmitter.get());
126 }
127 
128 X86MCInstLower::X86MCInstLower(const MachineFunction &mf,
129                                X86AsmPrinter &asmprinter)
130     : Ctx(mf.getContext()), MF(mf), TM(mf.getTarget()), MAI(*TM.getMCAsmInfo()),
131       AsmPrinter(asmprinter) {}
132 
133 MachineModuleInfoMachO &X86MCInstLower::getMachOMMI() const {
134   return MF.getMMI().getObjFileInfo<MachineModuleInfoMachO>();
135 }
136 
137 /// GetSymbolFromOperand - Lower an MO_GlobalAddress or MO_ExternalSymbol
138 /// operand to an MCSymbol.
139 MCSymbol *X86MCInstLower::GetSymbolFromOperand(const MachineOperand &MO) const {
140   const Triple &TT = TM.getTargetTriple();
141   if (MO.isGlobal() && TT.isOSBinFormatELF())
142     return AsmPrinter.getSymbolPreferLocal(*MO.getGlobal());
143 
144   const DataLayout &DL = MF.getDataLayout();
145   assert((MO.isGlobal() || MO.isSymbol() || MO.isMBB()) &&
146          "Isn't a symbol reference");
147 
148   MCSymbol *Sym = nullptr;
149   SmallString<128> Name;
150   StringRef Suffix;
151 
152   switch (MO.getTargetFlags()) {
153   case X86II::MO_DLLIMPORT:
154     // Handle dllimport linkage.
155     Name += "__imp_";
156     break;
157   case X86II::MO_COFFSTUB:
158     Name += ".refptr.";
159     break;
160   case X86II::MO_DARWIN_NONLAZY:
161   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
162     Suffix = "$non_lazy_ptr";
163     break;
164   }
165 
166   if (!Suffix.empty())
167     Name += DL.getPrivateGlobalPrefix();
168 
169   if (MO.isGlobal()) {
170     const GlobalValue *GV = MO.getGlobal();
171     AsmPrinter.getNameWithPrefix(Name, GV);
172   } else if (MO.isSymbol()) {
173     Mangler::getNameWithPrefix(Name, MO.getSymbolName(), DL);
174   } else if (MO.isMBB()) {
175     assert(Suffix.empty());
176     Sym = MO.getMBB()->getSymbol();
177   }
178 
179   Name += Suffix;
180   if (!Sym)
181     Sym = Ctx.getOrCreateSymbol(Name);
182 
183   // If the target flags on the operand changes the name of the symbol, do that
184   // before we return the symbol.
185   switch (MO.getTargetFlags()) {
186   default:
187     break;
188   case X86II::MO_COFFSTUB: {
189     MachineModuleInfoCOFF &MMICOFF =
190         MF.getMMI().getObjFileInfo<MachineModuleInfoCOFF>();
191     MachineModuleInfoImpl::StubValueTy &StubSym = MMICOFF.getGVStubEntry(Sym);
192     if (!StubSym.getPointer()) {
193       assert(MO.isGlobal() && "Extern symbol not handled yet");
194       StubSym = MachineModuleInfoImpl::StubValueTy(
195           AsmPrinter.getSymbol(MO.getGlobal()), true);
196     }
197     break;
198   }
199   case X86II::MO_DARWIN_NONLAZY:
200   case X86II::MO_DARWIN_NONLAZY_PIC_BASE: {
201     MachineModuleInfoImpl::StubValueTy &StubSym =
202         getMachOMMI().getGVStubEntry(Sym);
203     if (!StubSym.getPointer()) {
204       assert(MO.isGlobal() && "Extern symbol not handled yet");
205       StubSym = MachineModuleInfoImpl::StubValueTy(
206           AsmPrinter.getSymbol(MO.getGlobal()),
207           !MO.getGlobal()->hasInternalLinkage());
208     }
209     break;
210   }
211   }
212 
213   return Sym;
214 }
215 
216 MCOperand X86MCInstLower::LowerSymbolOperand(const MachineOperand &MO,
217                                              MCSymbol *Sym) const {
218   // FIXME: We would like an efficient form for this, so we don't have to do a
219   // lot of extra uniquing.
220   const MCExpr *Expr = nullptr;
221   MCSymbolRefExpr::VariantKind RefKind = MCSymbolRefExpr::VK_None;
222 
223   switch (MO.getTargetFlags()) {
224   default:
225     llvm_unreachable("Unknown target flag on GV operand");
226   case X86II::MO_NO_FLAG: // No flag.
227   // These affect the name of the symbol, not any suffix.
228   case X86II::MO_DARWIN_NONLAZY:
229   case X86II::MO_DLLIMPORT:
230   case X86II::MO_COFFSTUB:
231     break;
232 
233   case X86II::MO_TLVP:
234     RefKind = MCSymbolRefExpr::VK_TLVP;
235     break;
236   case X86II::MO_TLVP_PIC_BASE:
237     Expr = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_TLVP, Ctx);
238     // Subtract the pic base.
239     Expr = MCBinaryExpr::createSub(
240         Expr, MCSymbolRefExpr::create(MF.getPICBaseSymbol(), Ctx), Ctx);
241     break;
242   case X86II::MO_SECREL:
243     RefKind = MCSymbolRefExpr::VK_SECREL;
244     break;
245   case X86II::MO_TLSGD:
246     RefKind = MCSymbolRefExpr::VK_TLSGD;
247     break;
248   case X86II::MO_TLSLD:
249     RefKind = MCSymbolRefExpr::VK_TLSLD;
250     break;
251   case X86II::MO_TLSLDM:
252     RefKind = MCSymbolRefExpr::VK_TLSLDM;
253     break;
254   case X86II::MO_GOTTPOFF:
255     RefKind = MCSymbolRefExpr::VK_GOTTPOFF;
256     break;
257   case X86II::MO_INDNTPOFF:
258     RefKind = MCSymbolRefExpr::VK_INDNTPOFF;
259     break;
260   case X86II::MO_TPOFF:
261     RefKind = MCSymbolRefExpr::VK_TPOFF;
262     break;
263   case X86II::MO_DTPOFF:
264     RefKind = MCSymbolRefExpr::VK_DTPOFF;
265     break;
266   case X86II::MO_NTPOFF:
267     RefKind = MCSymbolRefExpr::VK_NTPOFF;
268     break;
269   case X86II::MO_GOTNTPOFF:
270     RefKind = MCSymbolRefExpr::VK_GOTNTPOFF;
271     break;
272   case X86II::MO_GOTPCREL:
273     RefKind = MCSymbolRefExpr::VK_GOTPCREL;
274     break;
275   case X86II::MO_GOT:
276     RefKind = MCSymbolRefExpr::VK_GOT;
277     break;
278   case X86II::MO_GOTOFF:
279     RefKind = MCSymbolRefExpr::VK_GOTOFF;
280     break;
281   case X86II::MO_PLT:
282     RefKind = MCSymbolRefExpr::VK_PLT;
283     break;
284   case X86II::MO_ABS8:
285     RefKind = MCSymbolRefExpr::VK_X86_ABS8;
286     break;
287   case X86II::MO_PIC_BASE_OFFSET:
288   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
289     Expr = MCSymbolRefExpr::create(Sym, Ctx);
290     // Subtract the pic base.
291     Expr = MCBinaryExpr::createSub(
292         Expr, MCSymbolRefExpr::create(MF.getPICBaseSymbol(), Ctx), Ctx);
293     if (MO.isJTI()) {
294       assert(MAI.doesSetDirectiveSuppressReloc());
295       // If .set directive is supported, use it to reduce the number of
296       // relocations the assembler will generate for differences between
297       // local labels. This is only safe when the symbols are in the same
298       // section so we are restricting it to jumptable references.
299       MCSymbol *Label = Ctx.createTempSymbol();
300       AsmPrinter.OutStreamer->emitAssignment(Label, Expr);
301       Expr = MCSymbolRefExpr::create(Label, Ctx);
302     }
303     break;
304   }
305 
306   if (!Expr)
307     Expr = MCSymbolRefExpr::create(Sym, RefKind, Ctx);
308 
309   if (!MO.isJTI() && !MO.isMBB() && MO.getOffset())
310     Expr = MCBinaryExpr::createAdd(
311         Expr, MCConstantExpr::create(MO.getOffset(), Ctx), Ctx);
312   return MCOperand::createExpr(Expr);
313 }
314 
315 /// Simplify FOO $imm, %{al,ax,eax,rax} to FOO $imm, for instruction with
316 /// a short fixed-register form.
317 static void SimplifyShortImmForm(MCInst &Inst, unsigned Opcode) {
318   unsigned ImmOp = Inst.getNumOperands() - 1;
319   assert(Inst.getOperand(0).isReg() &&
320          (Inst.getOperand(ImmOp).isImm() || Inst.getOperand(ImmOp).isExpr()) &&
321          ((Inst.getNumOperands() == 3 && Inst.getOperand(1).isReg() &&
322            Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) ||
323           Inst.getNumOperands() == 2) &&
324          "Unexpected instruction!");
325 
326   // Check whether the destination register can be fixed.
327   unsigned Reg = Inst.getOperand(0).getReg();
328   if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
329     return;
330 
331   // If so, rewrite the instruction.
332   MCOperand Saved = Inst.getOperand(ImmOp);
333   Inst = MCInst();
334   Inst.setOpcode(Opcode);
335   Inst.addOperand(Saved);
336 }
337 
338 /// If a movsx instruction has a shorter encoding for the used register
339 /// simplify the instruction to use it instead.
340 static void SimplifyMOVSX(MCInst &Inst) {
341   unsigned NewOpcode = 0;
342   unsigned Op0 = Inst.getOperand(0).getReg(), Op1 = Inst.getOperand(1).getReg();
343   switch (Inst.getOpcode()) {
344   default:
345     llvm_unreachable("Unexpected instruction!");
346   case X86::MOVSX16rr8: // movsbw %al, %ax   --> cbtw
347     if (Op0 == X86::AX && Op1 == X86::AL)
348       NewOpcode = X86::CBW;
349     break;
350   case X86::MOVSX32rr16: // movswl %ax, %eax  --> cwtl
351     if (Op0 == X86::EAX && Op1 == X86::AX)
352       NewOpcode = X86::CWDE;
353     break;
354   case X86::MOVSX64rr32: // movslq %eax, %rax --> cltq
355     if (Op0 == X86::RAX && Op1 == X86::EAX)
356       NewOpcode = X86::CDQE;
357     break;
358   }
359 
360   if (NewOpcode != 0) {
361     Inst = MCInst();
362     Inst.setOpcode(NewOpcode);
363   }
364 }
365 
366 /// Simplify things like MOV32rm to MOV32o32a.
367 static void SimplifyShortMoveForm(X86AsmPrinter &Printer, MCInst &Inst,
368                                   unsigned Opcode) {
369   // Don't make these simplifications in 64-bit mode; other assemblers don't
370   // perform them because they make the code larger.
371   if (Printer.getSubtarget().is64Bit())
372     return;
373 
374   bool IsStore = Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg();
375   unsigned AddrBase = IsStore;
376   unsigned RegOp = IsStore ? 0 : 5;
377   unsigned AddrOp = AddrBase + 3;
378   assert(
379       Inst.getNumOperands() == 6 && Inst.getOperand(RegOp).isReg() &&
380       Inst.getOperand(AddrBase + X86::AddrBaseReg).isReg() &&
381       Inst.getOperand(AddrBase + X86::AddrScaleAmt).isImm() &&
382       Inst.getOperand(AddrBase + X86::AddrIndexReg).isReg() &&
383       Inst.getOperand(AddrBase + X86::AddrSegmentReg).isReg() &&
384       (Inst.getOperand(AddrOp).isExpr() || Inst.getOperand(AddrOp).isImm()) &&
385       "Unexpected instruction!");
386 
387   // Check whether the destination register can be fixed.
388   unsigned Reg = Inst.getOperand(RegOp).getReg();
389   if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
390     return;
391 
392   // Check whether this is an absolute address.
393   // FIXME: We know TLVP symbol refs aren't, but there should be a better way
394   // to do this here.
395   bool Absolute = true;
396   if (Inst.getOperand(AddrOp).isExpr()) {
397     const MCExpr *MCE = Inst.getOperand(AddrOp).getExpr();
398     if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(MCE))
399       if (SRE->getKind() == MCSymbolRefExpr::VK_TLVP)
400         Absolute = false;
401   }
402 
403   if (Absolute &&
404       (Inst.getOperand(AddrBase + X86::AddrBaseReg).getReg() != 0 ||
405        Inst.getOperand(AddrBase + X86::AddrScaleAmt).getImm() != 1 ||
406        Inst.getOperand(AddrBase + X86::AddrIndexReg).getReg() != 0))
407     return;
408 
409   // If so, rewrite the instruction.
410   MCOperand Saved = Inst.getOperand(AddrOp);
411   MCOperand Seg = Inst.getOperand(AddrBase + X86::AddrSegmentReg);
412   Inst = MCInst();
413   Inst.setOpcode(Opcode);
414   Inst.addOperand(Saved);
415   Inst.addOperand(Seg);
416 }
417 
418 static unsigned getRetOpcode(const X86Subtarget &Subtarget) {
419   return Subtarget.is64Bit() ? X86::RETQ : X86::RETL;
420 }
421 
422 Optional<MCOperand>
423 X86MCInstLower::LowerMachineOperand(const MachineInstr *MI,
424                                     const MachineOperand &MO) const {
425   switch (MO.getType()) {
426   default:
427     MI->print(errs());
428     llvm_unreachable("unknown operand type");
429   case MachineOperand::MO_Register:
430     // Ignore all implicit register operands.
431     if (MO.isImplicit())
432       return None;
433     return MCOperand::createReg(MO.getReg());
434   case MachineOperand::MO_Immediate:
435     return MCOperand::createImm(MO.getImm());
436   case MachineOperand::MO_MachineBasicBlock:
437   case MachineOperand::MO_GlobalAddress:
438   case MachineOperand::MO_ExternalSymbol:
439     return LowerSymbolOperand(MO, GetSymbolFromOperand(MO));
440   case MachineOperand::MO_MCSymbol:
441     return LowerSymbolOperand(MO, MO.getMCSymbol());
442   case MachineOperand::MO_JumpTableIndex:
443     return LowerSymbolOperand(MO, AsmPrinter.GetJTISymbol(MO.getIndex()));
444   case MachineOperand::MO_ConstantPoolIndex:
445     return LowerSymbolOperand(MO, AsmPrinter.GetCPISymbol(MO.getIndex()));
446   case MachineOperand::MO_BlockAddress:
447     return LowerSymbolOperand(
448         MO, AsmPrinter.GetBlockAddressSymbol(MO.getBlockAddress()));
449   case MachineOperand::MO_RegisterMask:
450     // Ignore call clobbers.
451     return None;
452   }
453 }
454 
455 // Replace TAILJMP opcodes with their equivalent opcodes that have encoding
456 // information.
457 static unsigned convertTailJumpOpcode(unsigned Opcode) {
458   switch (Opcode) {
459   case X86::TAILJMPr:
460     Opcode = X86::JMP32r;
461     break;
462   case X86::TAILJMPm:
463     Opcode = X86::JMP32m;
464     break;
465   case X86::TAILJMPr64:
466     Opcode = X86::JMP64r;
467     break;
468   case X86::TAILJMPm64:
469     Opcode = X86::JMP64m;
470     break;
471   case X86::TAILJMPr64_REX:
472     Opcode = X86::JMP64r_REX;
473     break;
474   case X86::TAILJMPm64_REX:
475     Opcode = X86::JMP64m_REX;
476     break;
477   case X86::TAILJMPd:
478   case X86::TAILJMPd64:
479     Opcode = X86::JMP_1;
480     break;
481   case X86::TAILJMPd_CC:
482   case X86::TAILJMPd64_CC:
483     Opcode = X86::JCC_1;
484     break;
485   }
486 
487   return Opcode;
488 }
489 
490 void X86MCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const {
491   OutMI.setOpcode(MI->getOpcode());
492 
493   for (const MachineOperand &MO : MI->operands())
494     if (auto MaybeMCOp = LowerMachineOperand(MI, MO))
495       OutMI.addOperand(MaybeMCOp.getValue());
496 
497   // Handle a few special cases to eliminate operand modifiers.
498   switch (OutMI.getOpcode()) {
499   case X86::LEA64_32r:
500   case X86::LEA64r:
501   case X86::LEA16r:
502   case X86::LEA32r:
503     // LEA should have a segment register, but it must be empty.
504     assert(OutMI.getNumOperands() == 1 + X86::AddrNumOperands &&
505            "Unexpected # of LEA operands");
506     assert(OutMI.getOperand(1 + X86::AddrSegmentReg).getReg() == 0 &&
507            "LEA has segment specified!");
508     break;
509 
510   // Commute operands to get a smaller encoding by using VEX.R instead of VEX.B
511   // if one of the registers is extended, but other isn't.
512   case X86::VMOVZPQILo2PQIrr:
513   case X86::VMOVAPDrr:
514   case X86::VMOVAPDYrr:
515   case X86::VMOVAPSrr:
516   case X86::VMOVAPSYrr:
517   case X86::VMOVDQArr:
518   case X86::VMOVDQAYrr:
519   case X86::VMOVDQUrr:
520   case X86::VMOVDQUYrr:
521   case X86::VMOVUPDrr:
522   case X86::VMOVUPDYrr:
523   case X86::VMOVUPSrr:
524   case X86::VMOVUPSYrr: {
525     if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
526         X86II::isX86_64ExtendedReg(OutMI.getOperand(1).getReg())) {
527       unsigned NewOpc;
528       switch (OutMI.getOpcode()) {
529       default: llvm_unreachable("Invalid opcode");
530       case X86::VMOVZPQILo2PQIrr: NewOpc = X86::VMOVPQI2QIrr;   break;
531       case X86::VMOVAPDrr:        NewOpc = X86::VMOVAPDrr_REV;  break;
532       case X86::VMOVAPDYrr:       NewOpc = X86::VMOVAPDYrr_REV; break;
533       case X86::VMOVAPSrr:        NewOpc = X86::VMOVAPSrr_REV;  break;
534       case X86::VMOVAPSYrr:       NewOpc = X86::VMOVAPSYrr_REV; break;
535       case X86::VMOVDQArr:        NewOpc = X86::VMOVDQArr_REV;  break;
536       case X86::VMOVDQAYrr:       NewOpc = X86::VMOVDQAYrr_REV; break;
537       case X86::VMOVDQUrr:        NewOpc = X86::VMOVDQUrr_REV;  break;
538       case X86::VMOVDQUYrr:       NewOpc = X86::VMOVDQUYrr_REV; break;
539       case X86::VMOVUPDrr:        NewOpc = X86::VMOVUPDrr_REV;  break;
540       case X86::VMOVUPDYrr:       NewOpc = X86::VMOVUPDYrr_REV; break;
541       case X86::VMOVUPSrr:        NewOpc = X86::VMOVUPSrr_REV;  break;
542       case X86::VMOVUPSYrr:       NewOpc = X86::VMOVUPSYrr_REV; break;
543       }
544       OutMI.setOpcode(NewOpc);
545     }
546     break;
547   }
548   case X86::VMOVSDrr:
549   case X86::VMOVSSrr: {
550     if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
551         X86II::isX86_64ExtendedReg(OutMI.getOperand(2).getReg())) {
552       unsigned NewOpc;
553       switch (OutMI.getOpcode()) {
554       default: llvm_unreachable("Invalid opcode");
555       case X86::VMOVSDrr: NewOpc = X86::VMOVSDrr_REV; break;
556       case X86::VMOVSSrr: NewOpc = X86::VMOVSSrr_REV; break;
557       }
558       OutMI.setOpcode(NewOpc);
559     }
560     break;
561   }
562 
563   case X86::VPCMPBZ128rmi:  case X86::VPCMPBZ128rmik:
564   case X86::VPCMPBZ128rri:  case X86::VPCMPBZ128rrik:
565   case X86::VPCMPBZ256rmi:  case X86::VPCMPBZ256rmik:
566   case X86::VPCMPBZ256rri:  case X86::VPCMPBZ256rrik:
567   case X86::VPCMPBZrmi:     case X86::VPCMPBZrmik:
568   case X86::VPCMPBZrri:     case X86::VPCMPBZrrik:
569   case X86::VPCMPDZ128rmi:  case X86::VPCMPDZ128rmik:
570   case X86::VPCMPDZ128rmib: case X86::VPCMPDZ128rmibk:
571   case X86::VPCMPDZ128rri:  case X86::VPCMPDZ128rrik:
572   case X86::VPCMPDZ256rmi:  case X86::VPCMPDZ256rmik:
573   case X86::VPCMPDZ256rmib: case X86::VPCMPDZ256rmibk:
574   case X86::VPCMPDZ256rri:  case X86::VPCMPDZ256rrik:
575   case X86::VPCMPDZrmi:     case X86::VPCMPDZrmik:
576   case X86::VPCMPDZrmib:    case X86::VPCMPDZrmibk:
577   case X86::VPCMPDZrri:     case X86::VPCMPDZrrik:
578   case X86::VPCMPQZ128rmi:  case X86::VPCMPQZ128rmik:
579   case X86::VPCMPQZ128rmib: case X86::VPCMPQZ128rmibk:
580   case X86::VPCMPQZ128rri:  case X86::VPCMPQZ128rrik:
581   case X86::VPCMPQZ256rmi:  case X86::VPCMPQZ256rmik:
582   case X86::VPCMPQZ256rmib: case X86::VPCMPQZ256rmibk:
583   case X86::VPCMPQZ256rri:  case X86::VPCMPQZ256rrik:
584   case X86::VPCMPQZrmi:     case X86::VPCMPQZrmik:
585   case X86::VPCMPQZrmib:    case X86::VPCMPQZrmibk:
586   case X86::VPCMPQZrri:     case X86::VPCMPQZrrik:
587   case X86::VPCMPWZ128rmi:  case X86::VPCMPWZ128rmik:
588   case X86::VPCMPWZ128rri:  case X86::VPCMPWZ128rrik:
589   case X86::VPCMPWZ256rmi:  case X86::VPCMPWZ256rmik:
590   case X86::VPCMPWZ256rri:  case X86::VPCMPWZ256rrik:
591   case X86::VPCMPWZrmi:     case X86::VPCMPWZrmik:
592   case X86::VPCMPWZrri:     case X86::VPCMPWZrrik: {
593     // Turn immediate 0 into the VPCMPEQ instruction.
594     if (OutMI.getOperand(OutMI.getNumOperands() - 1).getImm() == 0) {
595       unsigned NewOpc;
596       switch (OutMI.getOpcode()) {
597       default: llvm_unreachable("Invalid opcode");
598       case X86::VPCMPBZ128rmi:   NewOpc = X86::VPCMPEQBZ128rm;   break;
599       case X86::VPCMPBZ128rmik:  NewOpc = X86::VPCMPEQBZ128rmk;  break;
600       case X86::VPCMPBZ128rri:   NewOpc = X86::VPCMPEQBZ128rr;   break;
601       case X86::VPCMPBZ128rrik:  NewOpc = X86::VPCMPEQBZ128rrk;  break;
602       case X86::VPCMPBZ256rmi:   NewOpc = X86::VPCMPEQBZ256rm;   break;
603       case X86::VPCMPBZ256rmik:  NewOpc = X86::VPCMPEQBZ256rmk;  break;
604       case X86::VPCMPBZ256rri:   NewOpc = X86::VPCMPEQBZ256rr;   break;
605       case X86::VPCMPBZ256rrik:  NewOpc = X86::VPCMPEQBZ256rrk;  break;
606       case X86::VPCMPBZrmi:      NewOpc = X86::VPCMPEQBZrm;      break;
607       case X86::VPCMPBZrmik:     NewOpc = X86::VPCMPEQBZrmk;     break;
608       case X86::VPCMPBZrri:      NewOpc = X86::VPCMPEQBZrr;      break;
609       case X86::VPCMPBZrrik:     NewOpc = X86::VPCMPEQBZrrk;     break;
610       case X86::VPCMPDZ128rmi:   NewOpc = X86::VPCMPEQDZ128rm;   break;
611       case X86::VPCMPDZ128rmib:  NewOpc = X86::VPCMPEQDZ128rmb;  break;
612       case X86::VPCMPDZ128rmibk: NewOpc = X86::VPCMPEQDZ128rmbk; break;
613       case X86::VPCMPDZ128rmik:  NewOpc = X86::VPCMPEQDZ128rmk;  break;
614       case X86::VPCMPDZ128rri:   NewOpc = X86::VPCMPEQDZ128rr;   break;
615       case X86::VPCMPDZ128rrik:  NewOpc = X86::VPCMPEQDZ128rrk;  break;
616       case X86::VPCMPDZ256rmi:   NewOpc = X86::VPCMPEQDZ256rm;   break;
617       case X86::VPCMPDZ256rmib:  NewOpc = X86::VPCMPEQDZ256rmb;  break;
618       case X86::VPCMPDZ256rmibk: NewOpc = X86::VPCMPEQDZ256rmbk; break;
619       case X86::VPCMPDZ256rmik:  NewOpc = X86::VPCMPEQDZ256rmk;  break;
620       case X86::VPCMPDZ256rri:   NewOpc = X86::VPCMPEQDZ256rr;   break;
621       case X86::VPCMPDZ256rrik:  NewOpc = X86::VPCMPEQDZ256rrk;  break;
622       case X86::VPCMPDZrmi:      NewOpc = X86::VPCMPEQDZrm;      break;
623       case X86::VPCMPDZrmib:     NewOpc = X86::VPCMPEQDZrmb;     break;
624       case X86::VPCMPDZrmibk:    NewOpc = X86::VPCMPEQDZrmbk;    break;
625       case X86::VPCMPDZrmik:     NewOpc = X86::VPCMPEQDZrmk;     break;
626       case X86::VPCMPDZrri:      NewOpc = X86::VPCMPEQDZrr;      break;
627       case X86::VPCMPDZrrik:     NewOpc = X86::VPCMPEQDZrrk;     break;
628       case X86::VPCMPQZ128rmi:   NewOpc = X86::VPCMPEQQZ128rm;   break;
629       case X86::VPCMPQZ128rmib:  NewOpc = X86::VPCMPEQQZ128rmb;  break;
630       case X86::VPCMPQZ128rmibk: NewOpc = X86::VPCMPEQQZ128rmbk; break;
631       case X86::VPCMPQZ128rmik:  NewOpc = X86::VPCMPEQQZ128rmk;  break;
632       case X86::VPCMPQZ128rri:   NewOpc = X86::VPCMPEQQZ128rr;   break;
633       case X86::VPCMPQZ128rrik:  NewOpc = X86::VPCMPEQQZ128rrk;  break;
634       case X86::VPCMPQZ256rmi:   NewOpc = X86::VPCMPEQQZ256rm;   break;
635       case X86::VPCMPQZ256rmib:  NewOpc = X86::VPCMPEQQZ256rmb;  break;
636       case X86::VPCMPQZ256rmibk: NewOpc = X86::VPCMPEQQZ256rmbk; break;
637       case X86::VPCMPQZ256rmik:  NewOpc = X86::VPCMPEQQZ256rmk;  break;
638       case X86::VPCMPQZ256rri:   NewOpc = X86::VPCMPEQQZ256rr;   break;
639       case X86::VPCMPQZ256rrik:  NewOpc = X86::VPCMPEQQZ256rrk;  break;
640       case X86::VPCMPQZrmi:      NewOpc = X86::VPCMPEQQZrm;      break;
641       case X86::VPCMPQZrmib:     NewOpc = X86::VPCMPEQQZrmb;     break;
642       case X86::VPCMPQZrmibk:    NewOpc = X86::VPCMPEQQZrmbk;    break;
643       case X86::VPCMPQZrmik:     NewOpc = X86::VPCMPEQQZrmk;     break;
644       case X86::VPCMPQZrri:      NewOpc = X86::VPCMPEQQZrr;      break;
645       case X86::VPCMPQZrrik:     NewOpc = X86::VPCMPEQQZrrk;     break;
646       case X86::VPCMPWZ128rmi:   NewOpc = X86::VPCMPEQWZ128rm;   break;
647       case X86::VPCMPWZ128rmik:  NewOpc = X86::VPCMPEQWZ128rmk;  break;
648       case X86::VPCMPWZ128rri:   NewOpc = X86::VPCMPEQWZ128rr;   break;
649       case X86::VPCMPWZ128rrik:  NewOpc = X86::VPCMPEQWZ128rrk;  break;
650       case X86::VPCMPWZ256rmi:   NewOpc = X86::VPCMPEQWZ256rm;   break;
651       case X86::VPCMPWZ256rmik:  NewOpc = X86::VPCMPEQWZ256rmk;  break;
652       case X86::VPCMPWZ256rri:   NewOpc = X86::VPCMPEQWZ256rr;   break;
653       case X86::VPCMPWZ256rrik:  NewOpc = X86::VPCMPEQWZ256rrk;  break;
654       case X86::VPCMPWZrmi:      NewOpc = X86::VPCMPEQWZrm;      break;
655       case X86::VPCMPWZrmik:     NewOpc = X86::VPCMPEQWZrmk;     break;
656       case X86::VPCMPWZrri:      NewOpc = X86::VPCMPEQWZrr;      break;
657       case X86::VPCMPWZrrik:     NewOpc = X86::VPCMPEQWZrrk;     break;
658       }
659 
660       OutMI.setOpcode(NewOpc);
661       OutMI.erase(&OutMI.getOperand(OutMI.getNumOperands() - 1));
662       break;
663     }
664 
665     // Turn immediate 6 into the VPCMPGT instruction.
666     if (OutMI.getOperand(OutMI.getNumOperands() - 1).getImm() == 6) {
667       unsigned NewOpc;
668       switch (OutMI.getOpcode()) {
669       default: llvm_unreachable("Invalid opcode");
670       case X86::VPCMPBZ128rmi:   NewOpc = X86::VPCMPGTBZ128rm;   break;
671       case X86::VPCMPBZ128rmik:  NewOpc = X86::VPCMPGTBZ128rmk;  break;
672       case X86::VPCMPBZ128rri:   NewOpc = X86::VPCMPGTBZ128rr;   break;
673       case X86::VPCMPBZ128rrik:  NewOpc = X86::VPCMPGTBZ128rrk;  break;
674       case X86::VPCMPBZ256rmi:   NewOpc = X86::VPCMPGTBZ256rm;   break;
675       case X86::VPCMPBZ256rmik:  NewOpc = X86::VPCMPGTBZ256rmk;  break;
676       case X86::VPCMPBZ256rri:   NewOpc = X86::VPCMPGTBZ256rr;   break;
677       case X86::VPCMPBZ256rrik:  NewOpc = X86::VPCMPGTBZ256rrk;  break;
678       case X86::VPCMPBZrmi:      NewOpc = X86::VPCMPGTBZrm;      break;
679       case X86::VPCMPBZrmik:     NewOpc = X86::VPCMPGTBZrmk;     break;
680       case X86::VPCMPBZrri:      NewOpc = X86::VPCMPGTBZrr;      break;
681       case X86::VPCMPBZrrik:     NewOpc = X86::VPCMPGTBZrrk;     break;
682       case X86::VPCMPDZ128rmi:   NewOpc = X86::VPCMPGTDZ128rm;   break;
683       case X86::VPCMPDZ128rmib:  NewOpc = X86::VPCMPGTDZ128rmb;  break;
684       case X86::VPCMPDZ128rmibk: NewOpc = X86::VPCMPGTDZ128rmbk; break;
685       case X86::VPCMPDZ128rmik:  NewOpc = X86::VPCMPGTDZ128rmk;  break;
686       case X86::VPCMPDZ128rri:   NewOpc = X86::VPCMPGTDZ128rr;   break;
687       case X86::VPCMPDZ128rrik:  NewOpc = X86::VPCMPGTDZ128rrk;  break;
688       case X86::VPCMPDZ256rmi:   NewOpc = X86::VPCMPGTDZ256rm;   break;
689       case X86::VPCMPDZ256rmib:  NewOpc = X86::VPCMPGTDZ256rmb;  break;
690       case X86::VPCMPDZ256rmibk: NewOpc = X86::VPCMPGTDZ256rmbk; break;
691       case X86::VPCMPDZ256rmik:  NewOpc = X86::VPCMPGTDZ256rmk;  break;
692       case X86::VPCMPDZ256rri:   NewOpc = X86::VPCMPGTDZ256rr;   break;
693       case X86::VPCMPDZ256rrik:  NewOpc = X86::VPCMPGTDZ256rrk;  break;
694       case X86::VPCMPDZrmi:      NewOpc = X86::VPCMPGTDZrm;      break;
695       case X86::VPCMPDZrmib:     NewOpc = X86::VPCMPGTDZrmb;     break;
696       case X86::VPCMPDZrmibk:    NewOpc = X86::VPCMPGTDZrmbk;    break;
697       case X86::VPCMPDZrmik:     NewOpc = X86::VPCMPGTDZrmk;     break;
698       case X86::VPCMPDZrri:      NewOpc = X86::VPCMPGTDZrr;      break;
699       case X86::VPCMPDZrrik:     NewOpc = X86::VPCMPGTDZrrk;     break;
700       case X86::VPCMPQZ128rmi:   NewOpc = X86::VPCMPGTQZ128rm;   break;
701       case X86::VPCMPQZ128rmib:  NewOpc = X86::VPCMPGTQZ128rmb;  break;
702       case X86::VPCMPQZ128rmibk: NewOpc = X86::VPCMPGTQZ128rmbk; break;
703       case X86::VPCMPQZ128rmik:  NewOpc = X86::VPCMPGTQZ128rmk;  break;
704       case X86::VPCMPQZ128rri:   NewOpc = X86::VPCMPGTQZ128rr;   break;
705       case X86::VPCMPQZ128rrik:  NewOpc = X86::VPCMPGTQZ128rrk;  break;
706       case X86::VPCMPQZ256rmi:   NewOpc = X86::VPCMPGTQZ256rm;   break;
707       case X86::VPCMPQZ256rmib:  NewOpc = X86::VPCMPGTQZ256rmb;  break;
708       case X86::VPCMPQZ256rmibk: NewOpc = X86::VPCMPGTQZ256rmbk; break;
709       case X86::VPCMPQZ256rmik:  NewOpc = X86::VPCMPGTQZ256rmk;  break;
710       case X86::VPCMPQZ256rri:   NewOpc = X86::VPCMPGTQZ256rr;   break;
711       case X86::VPCMPQZ256rrik:  NewOpc = X86::VPCMPGTQZ256rrk;  break;
712       case X86::VPCMPQZrmi:      NewOpc = X86::VPCMPGTQZrm;      break;
713       case X86::VPCMPQZrmib:     NewOpc = X86::VPCMPGTQZrmb;     break;
714       case X86::VPCMPQZrmibk:    NewOpc = X86::VPCMPGTQZrmbk;    break;
715       case X86::VPCMPQZrmik:     NewOpc = X86::VPCMPGTQZrmk;     break;
716       case X86::VPCMPQZrri:      NewOpc = X86::VPCMPGTQZrr;      break;
717       case X86::VPCMPQZrrik:     NewOpc = X86::VPCMPGTQZrrk;     break;
718       case X86::VPCMPWZ128rmi:   NewOpc = X86::VPCMPGTWZ128rm;   break;
719       case X86::VPCMPWZ128rmik:  NewOpc = X86::VPCMPGTWZ128rmk;  break;
720       case X86::VPCMPWZ128rri:   NewOpc = X86::VPCMPGTWZ128rr;   break;
721       case X86::VPCMPWZ128rrik:  NewOpc = X86::VPCMPGTWZ128rrk;  break;
722       case X86::VPCMPWZ256rmi:   NewOpc = X86::VPCMPGTWZ256rm;   break;
723       case X86::VPCMPWZ256rmik:  NewOpc = X86::VPCMPGTWZ256rmk;  break;
724       case X86::VPCMPWZ256rri:   NewOpc = X86::VPCMPGTWZ256rr;   break;
725       case X86::VPCMPWZ256rrik:  NewOpc = X86::VPCMPGTWZ256rrk;  break;
726       case X86::VPCMPWZrmi:      NewOpc = X86::VPCMPGTWZrm;      break;
727       case X86::VPCMPWZrmik:     NewOpc = X86::VPCMPGTWZrmk;     break;
728       case X86::VPCMPWZrri:      NewOpc = X86::VPCMPGTWZrr;      break;
729       case X86::VPCMPWZrrik:     NewOpc = X86::VPCMPGTWZrrk;     break;
730       }
731 
732       OutMI.setOpcode(NewOpc);
733       OutMI.erase(&OutMI.getOperand(OutMI.getNumOperands() - 1));
734       break;
735     }
736 
737     break;
738   }
739 
740   // CALL64r, CALL64pcrel32 - These instructions used to have
741   // register inputs modeled as normal uses instead of implicit uses.  As such,
742   // they we used to truncate off all but the first operand (the callee). This
743   // issue seems to have been fixed at some point. This assert verifies that.
744   case X86::CALL64r:
745   case X86::CALL64pcrel32:
746     assert(OutMI.getNumOperands() == 1 && "Unexpected number of operands!");
747     break;
748 
749   case X86::EH_RETURN:
750   case X86::EH_RETURN64: {
751     OutMI = MCInst();
752     OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
753     break;
754   }
755 
756   case X86::CLEANUPRET: {
757     // Replace CLEANUPRET with the appropriate RET.
758     OutMI = MCInst();
759     OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
760     break;
761   }
762 
763   case X86::CATCHRET: {
764     // Replace CATCHRET with the appropriate RET.
765     const X86Subtarget &Subtarget = AsmPrinter.getSubtarget();
766     unsigned ReturnReg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
767     OutMI = MCInst();
768     OutMI.setOpcode(getRetOpcode(Subtarget));
769     OutMI.addOperand(MCOperand::createReg(ReturnReg));
770     break;
771   }
772 
773   // TAILJMPd, TAILJMPd64, TailJMPd_cc - Lower to the correct jump
774   // instruction.
775   case X86::TAILJMPr:
776   case X86::TAILJMPr64:
777   case X86::TAILJMPr64_REX:
778   case X86::TAILJMPd:
779   case X86::TAILJMPd64:
780     assert(OutMI.getNumOperands() == 1 && "Unexpected number of operands!");
781     OutMI.setOpcode(convertTailJumpOpcode(OutMI.getOpcode()));
782     break;
783 
784   case X86::TAILJMPd_CC:
785   case X86::TAILJMPd64_CC:
786     assert(OutMI.getNumOperands() == 2 && "Unexpected number of operands!");
787     OutMI.setOpcode(convertTailJumpOpcode(OutMI.getOpcode()));
788     break;
789 
790   case X86::TAILJMPm:
791   case X86::TAILJMPm64:
792   case X86::TAILJMPm64_REX:
793     assert(OutMI.getNumOperands() == X86::AddrNumOperands &&
794            "Unexpected number of operands!");
795     OutMI.setOpcode(convertTailJumpOpcode(OutMI.getOpcode()));
796     break;
797 
798   case X86::DEC16r:
799   case X86::DEC32r:
800   case X86::INC16r:
801   case X86::INC32r:
802     // If we aren't in 64-bit mode we can use the 1-byte inc/dec instructions.
803     if (!AsmPrinter.getSubtarget().is64Bit()) {
804       unsigned Opcode;
805       switch (OutMI.getOpcode()) {
806       default: llvm_unreachable("Invalid opcode");
807       case X86::DEC16r: Opcode = X86::DEC16r_alt; break;
808       case X86::DEC32r: Opcode = X86::DEC32r_alt; break;
809       case X86::INC16r: Opcode = X86::INC16r_alt; break;
810       case X86::INC32r: Opcode = X86::INC32r_alt; break;
811       }
812       OutMI.setOpcode(Opcode);
813     }
814     break;
815 
816   // We don't currently select the correct instruction form for instructions
817   // which have a short %eax, etc. form. Handle this by custom lowering, for
818   // now.
819   //
820   // Note, we are currently not handling the following instructions:
821   // MOV64ao8, MOV64o8a
822   // XCHG16ar, XCHG32ar, XCHG64ar
823   case X86::MOV8mr_NOREX:
824   case X86::MOV8mr:
825   case X86::MOV8rm_NOREX:
826   case X86::MOV8rm:
827   case X86::MOV16mr:
828   case X86::MOV16rm:
829   case X86::MOV32mr:
830   case X86::MOV32rm: {
831     unsigned NewOpc;
832     switch (OutMI.getOpcode()) {
833     default: llvm_unreachable("Invalid opcode");
834     case X86::MOV8mr_NOREX:
835     case X86::MOV8mr:  NewOpc = X86::MOV8o32a; break;
836     case X86::MOV8rm_NOREX:
837     case X86::MOV8rm:  NewOpc = X86::MOV8ao32; break;
838     case X86::MOV16mr: NewOpc = X86::MOV16o32a; break;
839     case X86::MOV16rm: NewOpc = X86::MOV16ao32; break;
840     case X86::MOV32mr: NewOpc = X86::MOV32o32a; break;
841     case X86::MOV32rm: NewOpc = X86::MOV32ao32; break;
842     }
843     SimplifyShortMoveForm(AsmPrinter, OutMI, NewOpc);
844     break;
845   }
846 
847   case X86::ADC8ri: case X86::ADC16ri: case X86::ADC32ri: case X86::ADC64ri32:
848   case X86::ADD8ri: case X86::ADD16ri: case X86::ADD32ri: case X86::ADD64ri32:
849   case X86::AND8ri: case X86::AND16ri: case X86::AND32ri: case X86::AND64ri32:
850   case X86::CMP8ri: case X86::CMP16ri: case X86::CMP32ri: case X86::CMP64ri32:
851   case X86::OR8ri:  case X86::OR16ri:  case X86::OR32ri:  case X86::OR64ri32:
852   case X86::SBB8ri: case X86::SBB16ri: case X86::SBB32ri: case X86::SBB64ri32:
853   case X86::SUB8ri: case X86::SUB16ri: case X86::SUB32ri: case X86::SUB64ri32:
854   case X86::TEST8ri:case X86::TEST16ri:case X86::TEST32ri:case X86::TEST64ri32:
855   case X86::XOR8ri: case X86::XOR16ri: case X86::XOR32ri: case X86::XOR64ri32: {
856     unsigned NewOpc;
857     switch (OutMI.getOpcode()) {
858     default: llvm_unreachable("Invalid opcode");
859     case X86::ADC8ri:     NewOpc = X86::ADC8i8;    break;
860     case X86::ADC16ri:    NewOpc = X86::ADC16i16;  break;
861     case X86::ADC32ri:    NewOpc = X86::ADC32i32;  break;
862     case X86::ADC64ri32:  NewOpc = X86::ADC64i32;  break;
863     case X86::ADD8ri:     NewOpc = X86::ADD8i8;    break;
864     case X86::ADD16ri:    NewOpc = X86::ADD16i16;  break;
865     case X86::ADD32ri:    NewOpc = X86::ADD32i32;  break;
866     case X86::ADD64ri32:  NewOpc = X86::ADD64i32;  break;
867     case X86::AND8ri:     NewOpc = X86::AND8i8;    break;
868     case X86::AND16ri:    NewOpc = X86::AND16i16;  break;
869     case X86::AND32ri:    NewOpc = X86::AND32i32;  break;
870     case X86::AND64ri32:  NewOpc = X86::AND64i32;  break;
871     case X86::CMP8ri:     NewOpc = X86::CMP8i8;    break;
872     case X86::CMP16ri:    NewOpc = X86::CMP16i16;  break;
873     case X86::CMP32ri:    NewOpc = X86::CMP32i32;  break;
874     case X86::CMP64ri32:  NewOpc = X86::CMP64i32;  break;
875     case X86::OR8ri:      NewOpc = X86::OR8i8;     break;
876     case X86::OR16ri:     NewOpc = X86::OR16i16;   break;
877     case X86::OR32ri:     NewOpc = X86::OR32i32;   break;
878     case X86::OR64ri32:   NewOpc = X86::OR64i32;   break;
879     case X86::SBB8ri:     NewOpc = X86::SBB8i8;    break;
880     case X86::SBB16ri:    NewOpc = X86::SBB16i16;  break;
881     case X86::SBB32ri:    NewOpc = X86::SBB32i32;  break;
882     case X86::SBB64ri32:  NewOpc = X86::SBB64i32;  break;
883     case X86::SUB8ri:     NewOpc = X86::SUB8i8;    break;
884     case X86::SUB16ri:    NewOpc = X86::SUB16i16;  break;
885     case X86::SUB32ri:    NewOpc = X86::SUB32i32;  break;
886     case X86::SUB64ri32:  NewOpc = X86::SUB64i32;  break;
887     case X86::TEST8ri:    NewOpc = X86::TEST8i8;   break;
888     case X86::TEST16ri:   NewOpc = X86::TEST16i16; break;
889     case X86::TEST32ri:   NewOpc = X86::TEST32i32; break;
890     case X86::TEST64ri32: NewOpc = X86::TEST64i32; break;
891     case X86::XOR8ri:     NewOpc = X86::XOR8i8;    break;
892     case X86::XOR16ri:    NewOpc = X86::XOR16i16;  break;
893     case X86::XOR32ri:    NewOpc = X86::XOR32i32;  break;
894     case X86::XOR64ri32:  NewOpc = X86::XOR64i32;  break;
895     }
896     SimplifyShortImmForm(OutMI, NewOpc);
897     break;
898   }
899 
900   // Try to shrink some forms of movsx.
901   case X86::MOVSX16rr8:
902   case X86::MOVSX32rr16:
903   case X86::MOVSX64rr32:
904     SimplifyMOVSX(OutMI);
905     break;
906 
907   case X86::VCMPPDrri:
908   case X86::VCMPPDYrri:
909   case X86::VCMPPSrri:
910   case X86::VCMPPSYrri:
911   case X86::VCMPSDrr:
912   case X86::VCMPSSrr: {
913     // Swap the operands if it will enable a 2 byte VEX encoding.
914     // FIXME: Change the immediate to improve opportunities?
915     if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(1).getReg()) &&
916         X86II::isX86_64ExtendedReg(OutMI.getOperand(2).getReg())) {
917       unsigned Imm = MI->getOperand(3).getImm() & 0x7;
918       switch (Imm) {
919       default: break;
920       case 0x00: // EQUAL
921       case 0x03: // UNORDERED
922       case 0x04: // NOT EQUAL
923       case 0x07: // ORDERED
924         std::swap(OutMI.getOperand(1), OutMI.getOperand(2));
925         break;
926       }
927     }
928     break;
929   }
930 
931   case X86::VMOVHLPSrr:
932   case X86::VUNPCKHPDrr:
933     // These are not truly commutable so hide them from the default case.
934     break;
935 
936   default: {
937     // If the instruction is a commutable arithmetic instruction we might be
938     // able to commute the operands to get a 2 byte VEX prefix.
939     uint64_t TSFlags = MI->getDesc().TSFlags;
940     if (MI->getDesc().isCommutable() &&
941         (TSFlags & X86II::EncodingMask) == X86II::VEX &&
942         (TSFlags & X86II::OpMapMask) == X86II::TB &&
943         (TSFlags & X86II::FormMask) == X86II::MRMSrcReg &&
944         !(TSFlags & X86II::VEX_W) && (TSFlags & X86II::VEX_4V) &&
945         OutMI.getNumOperands() == 3) {
946       if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(1).getReg()) &&
947           X86II::isX86_64ExtendedReg(OutMI.getOperand(2).getReg()))
948         std::swap(OutMI.getOperand(1), OutMI.getOperand(2));
949     }
950     break;
951   }
952   }
953 }
954 
955 void X86AsmPrinter::LowerTlsAddr(X86MCInstLower &MCInstLowering,
956                                  const MachineInstr &MI) {
957   NoAutoPaddingScope NoPadScope(*OutStreamer);
958   bool Is64Bits = MI.getOpcode() == X86::TLS_addr64 ||
959                   MI.getOpcode() == X86::TLS_base_addr64;
960   MCContext &Ctx = OutStreamer->getContext();
961 
962   MCSymbolRefExpr::VariantKind SRVK;
963   switch (MI.getOpcode()) {
964   case X86::TLS_addr32:
965   case X86::TLS_addr64:
966     SRVK = MCSymbolRefExpr::VK_TLSGD;
967     break;
968   case X86::TLS_base_addr32:
969     SRVK = MCSymbolRefExpr::VK_TLSLDM;
970     break;
971   case X86::TLS_base_addr64:
972     SRVK = MCSymbolRefExpr::VK_TLSLD;
973     break;
974   default:
975     llvm_unreachable("unexpected opcode");
976   }
977 
978   const MCSymbolRefExpr *Sym = MCSymbolRefExpr::create(
979       MCInstLowering.GetSymbolFromOperand(MI.getOperand(3)), SRVK, Ctx);
980 
981   // As of binutils 2.32, ld has a bogus TLS relaxation error when the GD/LD
982   // code sequence using R_X86_64_GOTPCREL (instead of R_X86_64_GOTPCRELX) is
983   // attempted to be relaxed to IE/LE (binutils PR24784). Work around the bug by
984   // only using GOT when GOTPCRELX is enabled.
985   // TODO Delete the workaround when GOTPCRELX becomes commonplace.
986   bool UseGot = MMI->getModule()->getRtLibUseGOT() &&
987                 Ctx.getAsmInfo()->canRelaxRelocations();
988 
989   if (Is64Bits) {
990     bool NeedsPadding = SRVK == MCSymbolRefExpr::VK_TLSGD;
991     if (NeedsPadding)
992       EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
993     EmitAndCountInstruction(MCInstBuilder(X86::LEA64r)
994                                 .addReg(X86::RDI)
995                                 .addReg(X86::RIP)
996                                 .addImm(1)
997                                 .addReg(0)
998                                 .addExpr(Sym)
999                                 .addReg(0));
1000     const MCSymbol *TlsGetAddr = Ctx.getOrCreateSymbol("__tls_get_addr");
1001     if (NeedsPadding) {
1002       if (!UseGot)
1003         EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
1004       EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
1005       EmitAndCountInstruction(MCInstBuilder(X86::REX64_PREFIX));
1006     }
1007     if (UseGot) {
1008       const MCExpr *Expr = MCSymbolRefExpr::create(
1009           TlsGetAddr, MCSymbolRefExpr::VK_GOTPCREL, Ctx);
1010       EmitAndCountInstruction(MCInstBuilder(X86::CALL64m)
1011                                   .addReg(X86::RIP)
1012                                   .addImm(1)
1013                                   .addReg(0)
1014                                   .addExpr(Expr)
1015                                   .addReg(0));
1016     } else {
1017       EmitAndCountInstruction(
1018           MCInstBuilder(X86::CALL64pcrel32)
1019               .addExpr(MCSymbolRefExpr::create(TlsGetAddr,
1020                                                MCSymbolRefExpr::VK_PLT, Ctx)));
1021     }
1022   } else {
1023     if (SRVK == MCSymbolRefExpr::VK_TLSGD && !UseGot) {
1024       EmitAndCountInstruction(MCInstBuilder(X86::LEA32r)
1025                                   .addReg(X86::EAX)
1026                                   .addReg(0)
1027                                   .addImm(1)
1028                                   .addReg(X86::EBX)
1029                                   .addExpr(Sym)
1030                                   .addReg(0));
1031     } else {
1032       EmitAndCountInstruction(MCInstBuilder(X86::LEA32r)
1033                                   .addReg(X86::EAX)
1034                                   .addReg(X86::EBX)
1035                                   .addImm(1)
1036                                   .addReg(0)
1037                                   .addExpr(Sym)
1038                                   .addReg(0));
1039     }
1040 
1041     const MCSymbol *TlsGetAddr = Ctx.getOrCreateSymbol("___tls_get_addr");
1042     if (UseGot) {
1043       const MCExpr *Expr =
1044           MCSymbolRefExpr::create(TlsGetAddr, MCSymbolRefExpr::VK_GOT, Ctx);
1045       EmitAndCountInstruction(MCInstBuilder(X86::CALL32m)
1046                                   .addReg(X86::EBX)
1047                                   .addImm(1)
1048                                   .addReg(0)
1049                                   .addExpr(Expr)
1050                                   .addReg(0));
1051     } else {
1052       EmitAndCountInstruction(
1053           MCInstBuilder(X86::CALLpcrel32)
1054               .addExpr(MCSymbolRefExpr::create(TlsGetAddr,
1055                                                MCSymbolRefExpr::VK_PLT, Ctx)));
1056     }
1057   }
1058 }
1059 
1060 /// Return the longest nop which can be efficiently decoded for the given
1061 /// target cpu.  15-bytes is the longest single NOP instruction, but some
1062 /// platforms can't decode the longest forms efficiently.
1063 static unsigned MaxLongNopLength(const MCSubtargetInfo &STI) {
1064   uint64_t MaxNopLength = 10;
1065   if (STI.getFeatureBits()[X86::ProcIntelSLM])
1066     MaxNopLength = 7;
1067   else if (STI.getFeatureBits()[X86::FeatureFast15ByteNOP])
1068     MaxNopLength = 15;
1069   else if (STI.getFeatureBits()[X86::FeatureFast11ByteNOP])
1070     MaxNopLength = 11;
1071   return MaxNopLength;
1072 }
1073 
1074 /// Emit the largest nop instruction smaller than or equal to \p NumBytes
1075 /// bytes.  Return the size of nop emitted.
1076 static unsigned EmitNop(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
1077                         const MCSubtargetInfo &STI) {
1078   if (!Is64Bit) {
1079     // TODO Do additional checking if the CPU supports multi-byte nops.
1080     OS.emitInstruction(MCInstBuilder(X86::NOOP), STI);
1081     return 1;
1082   }
1083 
1084   // Cap a single nop emission at the profitable value for the target
1085   NumBytes = std::min(NumBytes, MaxLongNopLength(STI));
1086 
1087   unsigned NopSize;
1088   unsigned Opc, BaseReg, ScaleVal, IndexReg, Displacement, SegmentReg;
1089   IndexReg = Displacement = SegmentReg = 0;
1090   BaseReg = X86::RAX;
1091   ScaleVal = 1;
1092   switch (NumBytes) {
1093   case 0:
1094     llvm_unreachable("Zero nops?");
1095     break;
1096   case 1:
1097     NopSize = 1;
1098     Opc = X86::NOOP;
1099     break;
1100   case 2:
1101     NopSize = 2;
1102     Opc = X86::XCHG16ar;
1103     break;
1104   case 3:
1105     NopSize = 3;
1106     Opc = X86::NOOPL;
1107     break;
1108   case 4:
1109     NopSize = 4;
1110     Opc = X86::NOOPL;
1111     Displacement = 8;
1112     break;
1113   case 5:
1114     NopSize = 5;
1115     Opc = X86::NOOPL;
1116     Displacement = 8;
1117     IndexReg = X86::RAX;
1118     break;
1119   case 6:
1120     NopSize = 6;
1121     Opc = X86::NOOPW;
1122     Displacement = 8;
1123     IndexReg = X86::RAX;
1124     break;
1125   case 7:
1126     NopSize = 7;
1127     Opc = X86::NOOPL;
1128     Displacement = 512;
1129     break;
1130   case 8:
1131     NopSize = 8;
1132     Opc = X86::NOOPL;
1133     Displacement = 512;
1134     IndexReg = X86::RAX;
1135     break;
1136   case 9:
1137     NopSize = 9;
1138     Opc = X86::NOOPW;
1139     Displacement = 512;
1140     IndexReg = X86::RAX;
1141     break;
1142   default:
1143     NopSize = 10;
1144     Opc = X86::NOOPW;
1145     Displacement = 512;
1146     IndexReg = X86::RAX;
1147     SegmentReg = X86::CS;
1148     break;
1149   }
1150 
1151   unsigned NumPrefixes = std::min(NumBytes - NopSize, 5U);
1152   NopSize += NumPrefixes;
1153   for (unsigned i = 0; i != NumPrefixes; ++i)
1154     OS.emitBytes("\x66");
1155 
1156   switch (Opc) {
1157   default: llvm_unreachable("Unexpected opcode");
1158   case X86::NOOP:
1159     OS.emitInstruction(MCInstBuilder(Opc), STI);
1160     break;
1161   case X86::XCHG16ar:
1162     OS.emitInstruction(MCInstBuilder(Opc).addReg(X86::AX).addReg(X86::AX), STI);
1163     break;
1164   case X86::NOOPL:
1165   case X86::NOOPW:
1166     OS.emitInstruction(MCInstBuilder(Opc)
1167                            .addReg(BaseReg)
1168                            .addImm(ScaleVal)
1169                            .addReg(IndexReg)
1170                            .addImm(Displacement)
1171                            .addReg(SegmentReg),
1172                        STI);
1173     break;
1174   }
1175   assert(NopSize <= NumBytes && "We overemitted?");
1176   return NopSize;
1177 }
1178 
1179 /// Emit the optimal amount of multi-byte nops on X86.
1180 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
1181                      const MCSubtargetInfo &STI) {
1182   unsigned NopsToEmit = NumBytes;
1183   (void)NopsToEmit;
1184   while (NumBytes) {
1185     NumBytes -= EmitNop(OS, NumBytes, Is64Bit, STI);
1186     assert(NopsToEmit >= NumBytes && "Emitted more than I asked for!");
1187   }
1188 }
1189 
1190 void X86AsmPrinter::LowerSTATEPOINT(const MachineInstr &MI,
1191                                     X86MCInstLower &MCIL) {
1192   assert(Subtarget->is64Bit() && "Statepoint currently only supports X86-64");
1193 
1194   NoAutoPaddingScope NoPadScope(*OutStreamer);
1195 
1196   StatepointOpers SOpers(&MI);
1197   if (unsigned PatchBytes = SOpers.getNumPatchBytes()) {
1198     EmitNops(*OutStreamer, PatchBytes, Subtarget->is64Bit(),
1199              getSubtargetInfo());
1200   } else {
1201     // Lower call target and choose correct opcode
1202     const MachineOperand &CallTarget = SOpers.getCallTarget();
1203     MCOperand CallTargetMCOp;
1204     unsigned CallOpcode;
1205     switch (CallTarget.getType()) {
1206     case MachineOperand::MO_GlobalAddress:
1207     case MachineOperand::MO_ExternalSymbol:
1208       CallTargetMCOp = MCIL.LowerSymbolOperand(
1209           CallTarget, MCIL.GetSymbolFromOperand(CallTarget));
1210       CallOpcode = X86::CALL64pcrel32;
1211       // Currently, we only support relative addressing with statepoints.
1212       // Otherwise, we'll need a scratch register to hold the target
1213       // address.  You'll fail asserts during load & relocation if this
1214       // symbol is to far away. (TODO: support non-relative addressing)
1215       break;
1216     case MachineOperand::MO_Immediate:
1217       CallTargetMCOp = MCOperand::createImm(CallTarget.getImm());
1218       CallOpcode = X86::CALL64pcrel32;
1219       // Currently, we only support relative addressing with statepoints.
1220       // Otherwise, we'll need a scratch register to hold the target
1221       // immediate.  You'll fail asserts during load & relocation if this
1222       // address is to far away. (TODO: support non-relative addressing)
1223       break;
1224     case MachineOperand::MO_Register:
1225       // FIXME: Add retpoline support and remove this.
1226       if (Subtarget->useIndirectThunkCalls())
1227         report_fatal_error("Lowering register statepoints with thunks not "
1228                            "yet implemented.");
1229       CallTargetMCOp = MCOperand::createReg(CallTarget.getReg());
1230       CallOpcode = X86::CALL64r;
1231       break;
1232     default:
1233       llvm_unreachable("Unsupported operand type in statepoint call target");
1234       break;
1235     }
1236 
1237     // Emit call
1238     MCInst CallInst;
1239     CallInst.setOpcode(CallOpcode);
1240     CallInst.addOperand(CallTargetMCOp);
1241     OutStreamer->emitInstruction(CallInst, getSubtargetInfo());
1242   }
1243 
1244   // Record our statepoint node in the same section used by STACKMAP
1245   // and PATCHPOINT
1246   auto &Ctx = OutStreamer->getContext();
1247   MCSymbol *MILabel = Ctx.createTempSymbol();
1248   OutStreamer->emitLabel(MILabel);
1249   SM.recordStatepoint(*MILabel, MI);
1250 }
1251 
1252 void X86AsmPrinter::LowerFAULTING_OP(const MachineInstr &FaultingMI,
1253                                      X86MCInstLower &MCIL) {
1254   // FAULTING_LOAD_OP <def>, <faltinf type>, <MBB handler>,
1255   //                  <opcode>, <operands>
1256 
1257   NoAutoPaddingScope NoPadScope(*OutStreamer);
1258 
1259   Register DefRegister = FaultingMI.getOperand(0).getReg();
1260   FaultMaps::FaultKind FK =
1261       static_cast<FaultMaps::FaultKind>(FaultingMI.getOperand(1).getImm());
1262   MCSymbol *HandlerLabel = FaultingMI.getOperand(2).getMBB()->getSymbol();
1263   unsigned Opcode = FaultingMI.getOperand(3).getImm();
1264   unsigned OperandsBeginIdx = 4;
1265 
1266   auto &Ctx = OutStreamer->getContext();
1267   MCSymbol *FaultingLabel = Ctx.createTempSymbol();
1268   OutStreamer->emitLabel(FaultingLabel);
1269 
1270   assert(FK < FaultMaps::FaultKindMax && "Invalid Faulting Kind!");
1271   FM.recordFaultingOp(FK, FaultingLabel, HandlerLabel);
1272 
1273   MCInst MI;
1274   MI.setOpcode(Opcode);
1275 
1276   if (DefRegister != X86::NoRegister)
1277     MI.addOperand(MCOperand::createReg(DefRegister));
1278 
1279   for (auto I = FaultingMI.operands_begin() + OperandsBeginIdx,
1280             E = FaultingMI.operands_end();
1281        I != E; ++I)
1282     if (auto MaybeOperand = MCIL.LowerMachineOperand(&FaultingMI, *I))
1283       MI.addOperand(MaybeOperand.getValue());
1284 
1285   OutStreamer->AddComment("on-fault: " + HandlerLabel->getName());
1286   OutStreamer->emitInstruction(MI, getSubtargetInfo());
1287 }
1288 
1289 void X86AsmPrinter::LowerFENTRY_CALL(const MachineInstr &MI,
1290                                      X86MCInstLower &MCIL) {
1291   bool Is64Bits = Subtarget->is64Bit();
1292   MCContext &Ctx = OutStreamer->getContext();
1293   MCSymbol *fentry = Ctx.getOrCreateSymbol("__fentry__");
1294   const MCSymbolRefExpr *Op =
1295       MCSymbolRefExpr::create(fentry, MCSymbolRefExpr::VK_None, Ctx);
1296 
1297   EmitAndCountInstruction(
1298       MCInstBuilder(Is64Bits ? X86::CALL64pcrel32 : X86::CALLpcrel32)
1299           .addExpr(Op));
1300 }
1301 
1302 void X86AsmPrinter::LowerPATCHABLE_OP(const MachineInstr &MI,
1303                                       X86MCInstLower &MCIL) {
1304   // PATCHABLE_OP minsize, opcode, operands
1305 
1306   NoAutoPaddingScope NoPadScope(*OutStreamer);
1307 
1308   unsigned MinSize = MI.getOperand(0).getImm();
1309   unsigned Opcode = MI.getOperand(1).getImm();
1310 
1311   MCInst MCI;
1312   MCI.setOpcode(Opcode);
1313   for (auto &MO : make_range(MI.operands_begin() + 2, MI.operands_end()))
1314     if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
1315       MCI.addOperand(MaybeOperand.getValue());
1316 
1317   SmallString<256> Code;
1318   SmallVector<MCFixup, 4> Fixups;
1319   raw_svector_ostream VecOS(Code);
1320   CodeEmitter->encodeInstruction(MCI, VecOS, Fixups, getSubtargetInfo());
1321 
1322   if (Code.size() < MinSize) {
1323     if (MinSize == 2 && Opcode == X86::PUSH64r) {
1324       // This is an optimization that lets us get away without emitting a nop in
1325       // many cases.
1326       //
1327       // NB! In some cases the encoding for PUSH64r (e.g. PUSH64r %r9) takes two
1328       // bytes too, so the check on MinSize is important.
1329       MCI.setOpcode(X86::PUSH64rmr);
1330     } else {
1331       unsigned NopSize = EmitNop(*OutStreamer, MinSize, Subtarget->is64Bit(),
1332                                  getSubtargetInfo());
1333       assert(NopSize == MinSize && "Could not implement MinSize!");
1334       (void)NopSize;
1335     }
1336   }
1337 
1338   OutStreamer->emitInstruction(MCI, getSubtargetInfo());
1339 }
1340 
1341 // Lower a stackmap of the form:
1342 // <id>, <shadowBytes>, ...
1343 void X86AsmPrinter::LowerSTACKMAP(const MachineInstr &MI) {
1344   SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
1345 
1346   auto &Ctx = OutStreamer->getContext();
1347   MCSymbol *MILabel = Ctx.createTempSymbol();
1348   OutStreamer->emitLabel(MILabel);
1349 
1350   SM.recordStackMap(*MILabel, MI);
1351   unsigned NumShadowBytes = MI.getOperand(1).getImm();
1352   SMShadowTracker.reset(NumShadowBytes);
1353 }
1354 
1355 // Lower a patchpoint of the form:
1356 // [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
1357 void X86AsmPrinter::LowerPATCHPOINT(const MachineInstr &MI,
1358                                     X86MCInstLower &MCIL) {
1359   assert(Subtarget->is64Bit() && "Patchpoint currently only supports X86-64");
1360 
1361   SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
1362 
1363   NoAutoPaddingScope NoPadScope(*OutStreamer);
1364 
1365   auto &Ctx = OutStreamer->getContext();
1366   MCSymbol *MILabel = Ctx.createTempSymbol();
1367   OutStreamer->emitLabel(MILabel);
1368   SM.recordPatchPoint(*MILabel, MI);
1369 
1370   PatchPointOpers opers(&MI);
1371   unsigned ScratchIdx = opers.getNextScratchIdx();
1372   unsigned EncodedBytes = 0;
1373   const MachineOperand &CalleeMO = opers.getCallTarget();
1374 
1375   // Check for null target. If target is non-null (i.e. is non-zero or is
1376   // symbolic) then emit a call.
1377   if (!(CalleeMO.isImm() && !CalleeMO.getImm())) {
1378     MCOperand CalleeMCOp;
1379     switch (CalleeMO.getType()) {
1380     default:
1381       /// FIXME: Add a verifier check for bad callee types.
1382       llvm_unreachable("Unrecognized callee operand type.");
1383     case MachineOperand::MO_Immediate:
1384       if (CalleeMO.getImm())
1385         CalleeMCOp = MCOperand::createImm(CalleeMO.getImm());
1386       break;
1387     case MachineOperand::MO_ExternalSymbol:
1388     case MachineOperand::MO_GlobalAddress:
1389       CalleeMCOp = MCIL.LowerSymbolOperand(CalleeMO,
1390                                            MCIL.GetSymbolFromOperand(CalleeMO));
1391       break;
1392     }
1393 
1394     // Emit MOV to materialize the target address and the CALL to target.
1395     // This is encoded with 12-13 bytes, depending on which register is used.
1396     Register ScratchReg = MI.getOperand(ScratchIdx).getReg();
1397     if (X86II::isX86_64ExtendedReg(ScratchReg))
1398       EncodedBytes = 13;
1399     else
1400       EncodedBytes = 12;
1401 
1402     EmitAndCountInstruction(
1403         MCInstBuilder(X86::MOV64ri).addReg(ScratchReg).addOperand(CalleeMCOp));
1404     // FIXME: Add retpoline support and remove this.
1405     if (Subtarget->useIndirectThunkCalls())
1406       report_fatal_error(
1407           "Lowering patchpoint with thunks not yet implemented.");
1408     EmitAndCountInstruction(MCInstBuilder(X86::CALL64r).addReg(ScratchReg));
1409   }
1410 
1411   // Emit padding.
1412   unsigned NumBytes = opers.getNumPatchBytes();
1413   assert(NumBytes >= EncodedBytes &&
1414          "Patchpoint can't request size less than the length of a call.");
1415 
1416   EmitNops(*OutStreamer, NumBytes - EncodedBytes, Subtarget->is64Bit(),
1417            getSubtargetInfo());
1418 }
1419 
1420 void X86AsmPrinter::LowerPATCHABLE_EVENT_CALL(const MachineInstr &MI,
1421                                               X86MCInstLower &MCIL) {
1422   assert(Subtarget->is64Bit() && "XRay custom events only supports X86-64");
1423 
1424   NoAutoPaddingScope NoPadScope(*OutStreamer);
1425 
1426   // We want to emit the following pattern, which follows the x86 calling
1427   // convention to prepare for the trampoline call to be patched in.
1428   //
1429   //   .p2align 1, ...
1430   // .Lxray_event_sled_N:
1431   //   jmp +N                        // jump across the instrumentation sled
1432   //   ...                           // set up arguments in register
1433   //   callq __xray_CustomEvent@plt  // force dependency to symbol
1434   //   ...
1435   //   <jump here>
1436   //
1437   // After patching, it would look something like:
1438   //
1439   //   nopw (2-byte nop)
1440   //   ...
1441   //   callq __xrayCustomEvent  // already lowered
1442   //   ...
1443   //
1444   // ---
1445   // First we emit the label and the jump.
1446   auto CurSled = OutContext.createTempSymbol("xray_event_sled_", true);
1447   OutStreamer->AddComment("# XRay Custom Event Log");
1448   OutStreamer->emitCodeAlignment(2);
1449   OutStreamer->emitLabel(CurSled);
1450 
1451   // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1452   // an operand (computed as an offset from the jmp instruction).
1453   // FIXME: Find another less hacky way do force the relative jump.
1454   OutStreamer->emitBinaryData("\xeb\x0f");
1455 
1456   // The default C calling convention will place two arguments into %rcx and
1457   // %rdx -- so we only work with those.
1458   const Register DestRegs[] = {X86::RDI, X86::RSI};
1459   bool UsedMask[] = {false, false};
1460   // Filled out in loop.
1461   Register SrcRegs[] = {0, 0};
1462 
1463   // Then we put the operands in the %rdi and %rsi registers. We spill the
1464   // values in the register before we clobber them, and mark them as used in
1465   // UsedMask. In case the arguments are already in the correct register, we use
1466   // emit nops appropriately sized to keep the sled the same size in every
1467   // situation.
1468   for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1469     if (auto Op = MCIL.LowerMachineOperand(&MI, MI.getOperand(I))) {
1470       assert(Op->isReg() && "Only support arguments in registers");
1471       SrcRegs[I] = getX86SubSuperRegister(Op->getReg(), 64);
1472       if (SrcRegs[I] != DestRegs[I]) {
1473         UsedMask[I] = true;
1474         EmitAndCountInstruction(
1475             MCInstBuilder(X86::PUSH64r).addReg(DestRegs[I]));
1476       } else {
1477         EmitNops(*OutStreamer, 4, Subtarget->is64Bit(), getSubtargetInfo());
1478       }
1479     }
1480 
1481   // Now that the register values are stashed, mov arguments into place.
1482   // FIXME: This doesn't work if one of the later SrcRegs is equal to an
1483   // earlier DestReg. We will have already overwritten over the register before
1484   // we can copy from it.
1485   for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1486     if (SrcRegs[I] != DestRegs[I])
1487       EmitAndCountInstruction(
1488           MCInstBuilder(X86::MOV64rr).addReg(DestRegs[I]).addReg(SrcRegs[I]));
1489 
1490   // We emit a hard dependency on the __xray_CustomEvent symbol, which is the
1491   // name of the trampoline to be implemented by the XRay runtime.
1492   auto TSym = OutContext.getOrCreateSymbol("__xray_CustomEvent");
1493   MachineOperand TOp = MachineOperand::CreateMCSymbol(TSym);
1494   if (isPositionIndependent())
1495     TOp.setTargetFlags(X86II::MO_PLT);
1496 
1497   // Emit the call instruction.
1498   EmitAndCountInstruction(MCInstBuilder(X86::CALL64pcrel32)
1499                               .addOperand(MCIL.LowerSymbolOperand(TOp, TSym)));
1500 
1501   // Restore caller-saved and used registers.
1502   for (unsigned I = sizeof UsedMask; I-- > 0;)
1503     if (UsedMask[I])
1504       EmitAndCountInstruction(MCInstBuilder(X86::POP64r).addReg(DestRegs[I]));
1505     else
1506       EmitNops(*OutStreamer, 1, Subtarget->is64Bit(), getSubtargetInfo());
1507 
1508   OutStreamer->AddComment("xray custom event end.");
1509 
1510   // Record the sled version. Older versions of this sled were spelled
1511   // differently, so we let the runtime handle the different offsets we're
1512   // using.
1513   recordSled(CurSled, MI, SledKind::CUSTOM_EVENT, 1);
1514 }
1515 
1516 void X86AsmPrinter::LowerPATCHABLE_TYPED_EVENT_CALL(const MachineInstr &MI,
1517                                                     X86MCInstLower &MCIL) {
1518   assert(Subtarget->is64Bit() && "XRay typed events only supports X86-64");
1519 
1520   NoAutoPaddingScope NoPadScope(*OutStreamer);
1521 
1522   // We want to emit the following pattern, which follows the x86 calling
1523   // convention to prepare for the trampoline call to be patched in.
1524   //
1525   //   .p2align 1, ...
1526   // .Lxray_event_sled_N:
1527   //   jmp +N                        // jump across the instrumentation sled
1528   //   ...                           // set up arguments in register
1529   //   callq __xray_TypedEvent@plt  // force dependency to symbol
1530   //   ...
1531   //   <jump here>
1532   //
1533   // After patching, it would look something like:
1534   //
1535   //   nopw (2-byte nop)
1536   //   ...
1537   //   callq __xrayTypedEvent  // already lowered
1538   //   ...
1539   //
1540   // ---
1541   // First we emit the label and the jump.
1542   auto CurSled = OutContext.createTempSymbol("xray_typed_event_sled_", true);
1543   OutStreamer->AddComment("# XRay Typed Event Log");
1544   OutStreamer->emitCodeAlignment(2);
1545   OutStreamer->emitLabel(CurSled);
1546 
1547   // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1548   // an operand (computed as an offset from the jmp instruction).
1549   // FIXME: Find another less hacky way do force the relative jump.
1550   OutStreamer->emitBinaryData("\xeb\x14");
1551 
1552   // An x86-64 convention may place three arguments into %rcx, %rdx, and R8,
1553   // so we'll work with those. Or we may be called via SystemV, in which case
1554   // we don't have to do any translation.
1555   const Register DestRegs[] = {X86::RDI, X86::RSI, X86::RDX};
1556   bool UsedMask[] = {false, false, false};
1557 
1558   // Will fill out src regs in the loop.
1559   Register SrcRegs[] = {0, 0, 0};
1560 
1561   // Then we put the operands in the SystemV registers. We spill the values in
1562   // the registers before we clobber them, and mark them as used in UsedMask.
1563   // In case the arguments are already in the correct register, we emit nops
1564   // appropriately sized to keep the sled the same size in every situation.
1565   for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1566     if (auto Op = MCIL.LowerMachineOperand(&MI, MI.getOperand(I))) {
1567       // TODO: Is register only support adequate?
1568       assert(Op->isReg() && "Only supports arguments in registers");
1569       SrcRegs[I] = getX86SubSuperRegister(Op->getReg(), 64);
1570       if (SrcRegs[I] != DestRegs[I]) {
1571         UsedMask[I] = true;
1572         EmitAndCountInstruction(
1573             MCInstBuilder(X86::PUSH64r).addReg(DestRegs[I]));
1574       } else {
1575         EmitNops(*OutStreamer, 4, Subtarget->is64Bit(), getSubtargetInfo());
1576       }
1577     }
1578 
1579   // In the above loop we only stash all of the destination registers or emit
1580   // nops if the arguments are already in the right place. Doing the actually
1581   // moving is postponed until after all the registers are stashed so nothing
1582   // is clobbers. We've already added nops to account for the size of mov and
1583   // push if the register is in the right place, so we only have to worry about
1584   // emitting movs.
1585   // FIXME: This doesn't work if one of the later SrcRegs is equal to an
1586   // earlier DestReg. We will have already overwritten over the register before
1587   // we can copy from it.
1588   for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1589     if (UsedMask[I])
1590       EmitAndCountInstruction(
1591           MCInstBuilder(X86::MOV64rr).addReg(DestRegs[I]).addReg(SrcRegs[I]));
1592 
1593   // We emit a hard dependency on the __xray_TypedEvent symbol, which is the
1594   // name of the trampoline to be implemented by the XRay runtime.
1595   auto TSym = OutContext.getOrCreateSymbol("__xray_TypedEvent");
1596   MachineOperand TOp = MachineOperand::CreateMCSymbol(TSym);
1597   if (isPositionIndependent())
1598     TOp.setTargetFlags(X86II::MO_PLT);
1599 
1600   // Emit the call instruction.
1601   EmitAndCountInstruction(MCInstBuilder(X86::CALL64pcrel32)
1602                               .addOperand(MCIL.LowerSymbolOperand(TOp, TSym)));
1603 
1604   // Restore caller-saved and used registers.
1605   for (unsigned I = sizeof UsedMask; I-- > 0;)
1606     if (UsedMask[I])
1607       EmitAndCountInstruction(MCInstBuilder(X86::POP64r).addReg(DestRegs[I]));
1608     else
1609       EmitNops(*OutStreamer, 1, Subtarget->is64Bit(), getSubtargetInfo());
1610 
1611   OutStreamer->AddComment("xray typed event end.");
1612 
1613   // Record the sled version.
1614   recordSled(CurSled, MI, SledKind::TYPED_EVENT, 0);
1615 }
1616 
1617 void X86AsmPrinter::LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr &MI,
1618                                                   X86MCInstLower &MCIL) {
1619 
1620   NoAutoPaddingScope NoPadScope(*OutStreamer);
1621 
1622   const Function &F = MF->getFunction();
1623   if (F.hasFnAttribute("patchable-function-entry")) {
1624     unsigned Num;
1625     if (F.getFnAttribute("patchable-function-entry")
1626             .getValueAsString()
1627             .getAsInteger(10, Num))
1628       return;
1629     EmitNops(*OutStreamer, Num, Subtarget->is64Bit(), getSubtargetInfo());
1630     return;
1631   }
1632   // We want to emit the following pattern:
1633   //
1634   //   .p2align 1, ...
1635   // .Lxray_sled_N:
1636   //   jmp .tmpN
1637   //   # 9 bytes worth of noops
1638   //
1639   // We need the 9 bytes because at runtime, we'd be patching over the full 11
1640   // bytes with the following pattern:
1641   //
1642   //   mov %r10, <function id, 32-bit>   // 6 bytes
1643   //   call <relative offset, 32-bits>   // 5 bytes
1644   //
1645   auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1646   OutStreamer->emitCodeAlignment(2);
1647   OutStreamer->emitLabel(CurSled);
1648 
1649   // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1650   // an operand (computed as an offset from the jmp instruction).
1651   // FIXME: Find another less hacky way do force the relative jump.
1652   OutStreamer->emitBytes("\xeb\x09");
1653   EmitNops(*OutStreamer, 9, Subtarget->is64Bit(), getSubtargetInfo());
1654   recordSled(CurSled, MI, SledKind::FUNCTION_ENTER);
1655 }
1656 
1657 void X86AsmPrinter::LowerPATCHABLE_RET(const MachineInstr &MI,
1658                                        X86MCInstLower &MCIL) {
1659   NoAutoPaddingScope NoPadScope(*OutStreamer);
1660 
1661   // Since PATCHABLE_RET takes the opcode of the return statement as an
1662   // argument, we use that to emit the correct form of the RET that we want.
1663   // i.e. when we see this:
1664   //
1665   //   PATCHABLE_RET X86::RET ...
1666   //
1667   // We should emit the RET followed by sleds.
1668   //
1669   //   .p2align 1, ...
1670   // .Lxray_sled_N:
1671   //   ret  # or equivalent instruction
1672   //   # 10 bytes worth of noops
1673   //
1674   // This just makes sure that the alignment for the next instruction is 2.
1675   auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1676   OutStreamer->emitCodeAlignment(2);
1677   OutStreamer->emitLabel(CurSled);
1678   unsigned OpCode = MI.getOperand(0).getImm();
1679   MCInst Ret;
1680   Ret.setOpcode(OpCode);
1681   for (auto &MO : make_range(MI.operands_begin() + 1, MI.operands_end()))
1682     if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
1683       Ret.addOperand(MaybeOperand.getValue());
1684   OutStreamer->emitInstruction(Ret, getSubtargetInfo());
1685   EmitNops(*OutStreamer, 10, Subtarget->is64Bit(), getSubtargetInfo());
1686   recordSled(CurSled, MI, SledKind::FUNCTION_EXIT);
1687 }
1688 
1689 void X86AsmPrinter::LowerPATCHABLE_TAIL_CALL(const MachineInstr &MI,
1690                                              X86MCInstLower &MCIL) {
1691   NoAutoPaddingScope NoPadScope(*OutStreamer);
1692 
1693   // Like PATCHABLE_RET, we have the actual instruction in the operands to this
1694   // instruction so we lower that particular instruction and its operands.
1695   // Unlike PATCHABLE_RET though, we put the sled before the JMP, much like how
1696   // we do it for PATCHABLE_FUNCTION_ENTER. The sled should be very similar to
1697   // the PATCHABLE_FUNCTION_ENTER case, followed by the lowering of the actual
1698   // tail call much like how we have it in PATCHABLE_RET.
1699   auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1700   OutStreamer->emitCodeAlignment(2);
1701   OutStreamer->emitLabel(CurSled);
1702   auto Target = OutContext.createTempSymbol();
1703 
1704   // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1705   // an operand (computed as an offset from the jmp instruction).
1706   // FIXME: Find another less hacky way do force the relative jump.
1707   OutStreamer->emitBytes("\xeb\x09");
1708   EmitNops(*OutStreamer, 9, Subtarget->is64Bit(), getSubtargetInfo());
1709   OutStreamer->emitLabel(Target);
1710   recordSled(CurSled, MI, SledKind::TAIL_CALL);
1711 
1712   unsigned OpCode = MI.getOperand(0).getImm();
1713   OpCode = convertTailJumpOpcode(OpCode);
1714   MCInst TC;
1715   TC.setOpcode(OpCode);
1716 
1717   // Before emitting the instruction, add a comment to indicate that this is
1718   // indeed a tail call.
1719   OutStreamer->AddComment("TAILCALL");
1720   for (auto &MO : make_range(MI.operands_begin() + 1, MI.operands_end()))
1721     if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
1722       TC.addOperand(MaybeOperand.getValue());
1723   OutStreamer->emitInstruction(TC, getSubtargetInfo());
1724 }
1725 
1726 // Returns instruction preceding MBBI in MachineFunction.
1727 // If MBBI is the first instruction of the first basic block, returns null.
1728 static MachineBasicBlock::const_iterator
1729 PrevCrossBBInst(MachineBasicBlock::const_iterator MBBI) {
1730   const MachineBasicBlock *MBB = MBBI->getParent();
1731   while (MBBI == MBB->begin()) {
1732     if (MBB == &MBB->getParent()->front())
1733       return MachineBasicBlock::const_iterator();
1734     MBB = MBB->getPrevNode();
1735     MBBI = MBB->end();
1736   }
1737   --MBBI;
1738   return MBBI;
1739 }
1740 
1741 static const Constant *getConstantFromPool(const MachineInstr &MI,
1742                                            const MachineOperand &Op) {
1743   if (!Op.isCPI() || Op.getOffset() != 0)
1744     return nullptr;
1745 
1746   ArrayRef<MachineConstantPoolEntry> Constants =
1747       MI.getParent()->getParent()->getConstantPool()->getConstants();
1748   const MachineConstantPoolEntry &ConstantEntry = Constants[Op.getIndex()];
1749 
1750   // Bail if this is a machine constant pool entry, we won't be able to dig out
1751   // anything useful.
1752   if (ConstantEntry.isMachineConstantPoolEntry())
1753     return nullptr;
1754 
1755   const Constant *C = ConstantEntry.Val.ConstVal;
1756   assert((!C || ConstantEntry.getType() == C->getType()) &&
1757          "Expected a constant of the same type!");
1758   return C;
1759 }
1760 
1761 static std::string getShuffleComment(const MachineInstr *MI, unsigned SrcOp1Idx,
1762                                      unsigned SrcOp2Idx, ArrayRef<int> Mask) {
1763   std::string Comment;
1764 
1765   // Compute the name for a register. This is really goofy because we have
1766   // multiple instruction printers that could (in theory) use different
1767   // names. Fortunately most people use the ATT style (outside of Windows)
1768   // and they actually agree on register naming here. Ultimately, this is
1769   // a comment, and so its OK if it isn't perfect.
1770   auto GetRegisterName = [](unsigned RegNum) -> StringRef {
1771     return X86ATTInstPrinter::getRegisterName(RegNum);
1772   };
1773 
1774   const MachineOperand &DstOp = MI->getOperand(0);
1775   const MachineOperand &SrcOp1 = MI->getOperand(SrcOp1Idx);
1776   const MachineOperand &SrcOp2 = MI->getOperand(SrcOp2Idx);
1777 
1778   StringRef DstName = DstOp.isReg() ? GetRegisterName(DstOp.getReg()) : "mem";
1779   StringRef Src1Name =
1780       SrcOp1.isReg() ? GetRegisterName(SrcOp1.getReg()) : "mem";
1781   StringRef Src2Name =
1782       SrcOp2.isReg() ? GetRegisterName(SrcOp2.getReg()) : "mem";
1783 
1784   // One source operand, fix the mask to print all elements in one span.
1785   SmallVector<int, 8> ShuffleMask(Mask.begin(), Mask.end());
1786   if (Src1Name == Src2Name)
1787     for (int i = 0, e = ShuffleMask.size(); i != e; ++i)
1788       if (ShuffleMask[i] >= e)
1789         ShuffleMask[i] -= e;
1790 
1791   raw_string_ostream CS(Comment);
1792   CS << DstName;
1793 
1794   // Handle AVX512 MASK/MASXZ write mask comments.
1795   // MASK: zmmX {%kY}
1796   // MASKZ: zmmX {%kY} {z}
1797   if (SrcOp1Idx > 1) {
1798     assert((SrcOp1Idx == 2 || SrcOp1Idx == 3) && "Unexpected writemask");
1799 
1800     const MachineOperand &WriteMaskOp = MI->getOperand(SrcOp1Idx - 1);
1801     if (WriteMaskOp.isReg()) {
1802       CS << " {%" << GetRegisterName(WriteMaskOp.getReg()) << "}";
1803 
1804       if (SrcOp1Idx == 2) {
1805         CS << " {z}";
1806       }
1807     }
1808   }
1809 
1810   CS << " = ";
1811 
1812   for (int i = 0, e = ShuffleMask.size(); i != e; ++i) {
1813     if (i != 0)
1814       CS << ",";
1815     if (ShuffleMask[i] == SM_SentinelZero) {
1816       CS << "zero";
1817       continue;
1818     }
1819 
1820     // Otherwise, it must come from src1 or src2.  Print the span of elements
1821     // that comes from this src.
1822     bool isSrc1 = ShuffleMask[i] < (int)e;
1823     CS << (isSrc1 ? Src1Name : Src2Name) << '[';
1824 
1825     bool IsFirst = true;
1826     while (i != e && ShuffleMask[i] != SM_SentinelZero &&
1827            (ShuffleMask[i] < (int)e) == isSrc1) {
1828       if (!IsFirst)
1829         CS << ',';
1830       else
1831         IsFirst = false;
1832       if (ShuffleMask[i] == SM_SentinelUndef)
1833         CS << "u";
1834       else
1835         CS << ShuffleMask[i] % (int)e;
1836       ++i;
1837     }
1838     CS << ']';
1839     --i; // For loop increments element #.
1840   }
1841   CS.flush();
1842 
1843   return Comment;
1844 }
1845 
1846 static void printConstant(const APInt &Val, raw_ostream &CS) {
1847   if (Val.getBitWidth() <= 64) {
1848     CS << Val.getZExtValue();
1849   } else {
1850     // print multi-word constant as (w0,w1)
1851     CS << "(";
1852     for (int i = 0, N = Val.getNumWords(); i < N; ++i) {
1853       if (i > 0)
1854         CS << ",";
1855       CS << Val.getRawData()[i];
1856     }
1857     CS << ")";
1858   }
1859 }
1860 
1861 static void printConstant(const APFloat &Flt, raw_ostream &CS) {
1862   SmallString<32> Str;
1863   // Force scientific notation to distinquish from integers.
1864   Flt.toString(Str, 0, 0);
1865   CS << Str;
1866 }
1867 
1868 static void printConstant(const Constant *COp, raw_ostream &CS) {
1869   if (isa<UndefValue>(COp)) {
1870     CS << "u";
1871   } else if (auto *CI = dyn_cast<ConstantInt>(COp)) {
1872     printConstant(CI->getValue(), CS);
1873   } else if (auto *CF = dyn_cast<ConstantFP>(COp)) {
1874     printConstant(CF->getValueAPF(), CS);
1875   } else {
1876     CS << "?";
1877   }
1878 }
1879 
1880 void X86AsmPrinter::EmitSEHInstruction(const MachineInstr *MI) {
1881   assert(MF->hasWinCFI() && "SEH_ instruction in function without WinCFI?");
1882   assert(getSubtarget().isOSWindows() && "SEH_ instruction Windows only");
1883 
1884   // Use the .cv_fpo directives if we're emitting CodeView on 32-bit x86.
1885   if (EmitFPOData) {
1886     X86TargetStreamer *XTS =
1887         static_cast<X86TargetStreamer *>(OutStreamer->getTargetStreamer());
1888     switch (MI->getOpcode()) {
1889     case X86::SEH_PushReg:
1890       XTS->emitFPOPushReg(MI->getOperand(0).getImm());
1891       break;
1892     case X86::SEH_StackAlloc:
1893       XTS->emitFPOStackAlloc(MI->getOperand(0).getImm());
1894       break;
1895     case X86::SEH_StackAlign:
1896       XTS->emitFPOStackAlign(MI->getOperand(0).getImm());
1897       break;
1898     case X86::SEH_SetFrame:
1899       assert(MI->getOperand(1).getImm() == 0 &&
1900              ".cv_fpo_setframe takes no offset");
1901       XTS->emitFPOSetFrame(MI->getOperand(0).getImm());
1902       break;
1903     case X86::SEH_EndPrologue:
1904       XTS->emitFPOEndPrologue();
1905       break;
1906     case X86::SEH_SaveReg:
1907     case X86::SEH_SaveXMM:
1908     case X86::SEH_PushFrame:
1909       llvm_unreachable("SEH_ directive incompatible with FPO");
1910       break;
1911     default:
1912       llvm_unreachable("expected SEH_ instruction");
1913     }
1914     return;
1915   }
1916 
1917   // Otherwise, use the .seh_ directives for all other Windows platforms.
1918   switch (MI->getOpcode()) {
1919   case X86::SEH_PushReg:
1920     OutStreamer->EmitWinCFIPushReg(MI->getOperand(0).getImm());
1921     break;
1922 
1923   case X86::SEH_SaveReg:
1924     OutStreamer->EmitWinCFISaveReg(MI->getOperand(0).getImm(),
1925                                    MI->getOperand(1).getImm());
1926     break;
1927 
1928   case X86::SEH_SaveXMM:
1929     OutStreamer->EmitWinCFISaveXMM(MI->getOperand(0).getImm(),
1930                                    MI->getOperand(1).getImm());
1931     break;
1932 
1933   case X86::SEH_StackAlloc:
1934     OutStreamer->EmitWinCFIAllocStack(MI->getOperand(0).getImm());
1935     break;
1936 
1937   case X86::SEH_SetFrame:
1938     OutStreamer->EmitWinCFISetFrame(MI->getOperand(0).getImm(),
1939                                     MI->getOperand(1).getImm());
1940     break;
1941 
1942   case X86::SEH_PushFrame:
1943     OutStreamer->EmitWinCFIPushFrame(MI->getOperand(0).getImm());
1944     break;
1945 
1946   case X86::SEH_EndPrologue:
1947     OutStreamer->EmitWinCFIEndProlog();
1948     break;
1949 
1950   default:
1951     llvm_unreachable("expected SEH_ instruction");
1952   }
1953 }
1954 
1955 static unsigned getRegisterWidth(const MCOperandInfo &Info) {
1956   if (Info.RegClass == X86::VR128RegClassID ||
1957       Info.RegClass == X86::VR128XRegClassID)
1958     return 128;
1959   if (Info.RegClass == X86::VR256RegClassID ||
1960       Info.RegClass == X86::VR256XRegClassID)
1961     return 256;
1962   if (Info.RegClass == X86::VR512RegClassID)
1963     return 512;
1964   llvm_unreachable("Unknown register class!");
1965 }
1966 
1967 void X86AsmPrinter::emitInstruction(const MachineInstr *MI) {
1968   X86MCInstLower MCInstLowering(*MF, *this);
1969   const X86RegisterInfo *RI =
1970       MF->getSubtarget<X86Subtarget>().getRegisterInfo();
1971 
1972   // Add a comment about EVEX-2-VEX compression for AVX-512 instrs that
1973   // are compressed from EVEX encoding to VEX encoding.
1974   if (TM.Options.MCOptions.ShowMCEncoding) {
1975     if (MI->getAsmPrinterFlags() & X86::AC_EVEX_2_VEX)
1976       OutStreamer->AddComment("EVEX TO VEX Compression ", false);
1977   }
1978 
1979   switch (MI->getOpcode()) {
1980   case TargetOpcode::DBG_VALUE:
1981     llvm_unreachable("Should be handled target independently");
1982 
1983   // Emit nothing here but a comment if we can.
1984   case X86::Int_MemBarrier:
1985     OutStreamer->emitRawComment("MEMBARRIER");
1986     return;
1987 
1988   case X86::EH_RETURN:
1989   case X86::EH_RETURN64: {
1990     // Lower these as normal, but add some comments.
1991     Register Reg = MI->getOperand(0).getReg();
1992     OutStreamer->AddComment(StringRef("eh_return, addr: %") +
1993                             X86ATTInstPrinter::getRegisterName(Reg));
1994     break;
1995   }
1996   case X86::CLEANUPRET: {
1997     // Lower these as normal, but add some comments.
1998     OutStreamer->AddComment("CLEANUPRET");
1999     break;
2000   }
2001 
2002   case X86::CATCHRET: {
2003     // Lower these as normal, but add some comments.
2004     OutStreamer->AddComment("CATCHRET");
2005     break;
2006   }
2007 
2008   case X86::ENDBR32:
2009   case X86::ENDBR64: {
2010     // CurrentPatchableFunctionEntrySym can be CurrentFnBegin only for
2011     // -fpatchable-function-entry=N,0. The entry MBB is guaranteed to be
2012     // non-empty. If MI is the initial ENDBR, place the
2013     // __patchable_function_entries label after ENDBR.
2014     if (CurrentPatchableFunctionEntrySym &&
2015         CurrentPatchableFunctionEntrySym == CurrentFnBegin &&
2016         MI == &MF->front().front()) {
2017       MCInst Inst;
2018       MCInstLowering.Lower(MI, Inst);
2019       EmitAndCountInstruction(Inst);
2020       CurrentPatchableFunctionEntrySym = createTempSymbol("patch");
2021       OutStreamer->emitLabel(CurrentPatchableFunctionEntrySym);
2022       return;
2023     }
2024     break;
2025   }
2026 
2027   case X86::TAILJMPr:
2028   case X86::TAILJMPm:
2029   case X86::TAILJMPd:
2030   case X86::TAILJMPd_CC:
2031   case X86::TAILJMPr64:
2032   case X86::TAILJMPm64:
2033   case X86::TAILJMPd64:
2034   case X86::TAILJMPd64_CC:
2035   case X86::TAILJMPr64_REX:
2036   case X86::TAILJMPm64_REX:
2037     // Lower these as normal, but add some comments.
2038     OutStreamer->AddComment("TAILCALL");
2039     break;
2040 
2041   case X86::TLS_addr32:
2042   case X86::TLS_addr64:
2043   case X86::TLS_base_addr32:
2044   case X86::TLS_base_addr64:
2045     return LowerTlsAddr(MCInstLowering, *MI);
2046 
2047   // Loading/storing mask pairs requires two kmov operations. The second one of these
2048   // needs a 2 byte displacement relative to the specified address (with 32 bit spill
2049   // size). The pairs of 1bit masks up to 16 bit masks all use the same spill size,
2050   // they all are stored using MASKPAIR16STORE, loaded using MASKPAIR16LOAD.
2051   //
2052   // The displacement value might wrap around in theory, thus the asserts in both
2053   // cases.
2054   case X86::MASKPAIR16LOAD: {
2055     int64_t Disp = MI->getOperand(1 + X86::AddrDisp).getImm();
2056     assert(Disp >= 0 && Disp <= INT32_MAX - 2 && "Unexpected displacement");
2057     Register Reg = MI->getOperand(0).getReg();
2058     Register Reg0 = RI->getSubReg(Reg, X86::sub_mask_0);
2059     Register Reg1 = RI->getSubReg(Reg, X86::sub_mask_1);
2060 
2061     // Load the first mask register
2062     MCInstBuilder MIB = MCInstBuilder(X86::KMOVWkm);
2063     MIB.addReg(Reg0);
2064     for (int i = 0; i < X86::AddrNumOperands; ++i) {
2065       auto Op = MCInstLowering.LowerMachineOperand(MI, MI->getOperand(1 + i));
2066       MIB.addOperand(Op.getValue());
2067     }
2068     EmitAndCountInstruction(MIB);
2069 
2070     // Load the second mask register of the pair
2071     MIB = MCInstBuilder(X86::KMOVWkm);
2072     MIB.addReg(Reg1);
2073     for (int i = 0; i < X86::AddrNumOperands; ++i) {
2074       if (i == X86::AddrDisp) {
2075         MIB.addImm(Disp + 2);
2076       } else {
2077         auto Op = MCInstLowering.LowerMachineOperand(MI, MI->getOperand(1 + i));
2078         MIB.addOperand(Op.getValue());
2079       }
2080     }
2081     EmitAndCountInstruction(MIB);
2082     return;
2083   }
2084 
2085   case X86::MASKPAIR16STORE: {
2086     int64_t Disp = MI->getOperand(X86::AddrDisp).getImm();
2087     assert(Disp >= 0 && Disp <= INT32_MAX - 2 && "Unexpected displacement");
2088     Register Reg = MI->getOperand(X86::AddrNumOperands).getReg();
2089     Register Reg0 = RI->getSubReg(Reg, X86::sub_mask_0);
2090     Register Reg1 = RI->getSubReg(Reg, X86::sub_mask_1);
2091 
2092     // Store the first mask register
2093     MCInstBuilder MIB = MCInstBuilder(X86::KMOVWmk);
2094     for (int i = 0; i < X86::AddrNumOperands; ++i)
2095       MIB.addOperand(MCInstLowering.LowerMachineOperand(MI, MI->getOperand(i)).getValue());
2096     MIB.addReg(Reg0);
2097     EmitAndCountInstruction(MIB);
2098 
2099     // Store the second mask register of the pair
2100     MIB = MCInstBuilder(X86::KMOVWmk);
2101     for (int i = 0; i < X86::AddrNumOperands; ++i) {
2102       if (i == X86::AddrDisp) {
2103         MIB.addImm(Disp + 2);
2104       } else {
2105         auto Op = MCInstLowering.LowerMachineOperand(MI, MI->getOperand(0 + i));
2106         MIB.addOperand(Op.getValue());
2107       }
2108     }
2109     MIB.addReg(Reg1);
2110     EmitAndCountInstruction(MIB);
2111     return;
2112   }
2113 
2114   case X86::MOVPC32r: {
2115     // This is a pseudo op for a two instruction sequence with a label, which
2116     // looks like:
2117     //     call "L1$pb"
2118     // "L1$pb":
2119     //     popl %esi
2120 
2121     // Emit the call.
2122     MCSymbol *PICBase = MF->getPICBaseSymbol();
2123     // FIXME: We would like an efficient form for this, so we don't have to do a
2124     // lot of extra uniquing.
2125     EmitAndCountInstruction(
2126         MCInstBuilder(X86::CALLpcrel32)
2127             .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
2128 
2129     const X86FrameLowering *FrameLowering =
2130         MF->getSubtarget<X86Subtarget>().getFrameLowering();
2131     bool hasFP = FrameLowering->hasFP(*MF);
2132 
2133     // TODO: This is needed only if we require precise CFA.
2134     bool HasActiveDwarfFrame = OutStreamer->getNumFrameInfos() &&
2135                                !OutStreamer->getDwarfFrameInfos().back().End;
2136 
2137     int stackGrowth = -RI->getSlotSize();
2138 
2139     if (HasActiveDwarfFrame && !hasFP) {
2140       OutStreamer->emitCFIAdjustCfaOffset(-stackGrowth);
2141     }
2142 
2143     // Emit the label.
2144     OutStreamer->emitLabel(PICBase);
2145 
2146     // popl $reg
2147     EmitAndCountInstruction(
2148         MCInstBuilder(X86::POP32r).addReg(MI->getOperand(0).getReg()));
2149 
2150     if (HasActiveDwarfFrame && !hasFP) {
2151       OutStreamer->emitCFIAdjustCfaOffset(stackGrowth);
2152     }
2153     return;
2154   }
2155 
2156   case X86::ADD32ri: {
2157     // Lower the MO_GOT_ABSOLUTE_ADDRESS form of ADD32ri.
2158     if (MI->getOperand(2).getTargetFlags() != X86II::MO_GOT_ABSOLUTE_ADDRESS)
2159       break;
2160 
2161     // Okay, we have something like:
2162     //  EAX = ADD32ri EAX, MO_GOT_ABSOLUTE_ADDRESS(@MYGLOBAL)
2163 
2164     // For this, we want to print something like:
2165     //   MYGLOBAL + (. - PICBASE)
2166     // However, we can't generate a ".", so just emit a new label here and refer
2167     // to it.
2168     MCSymbol *DotSym = OutContext.createTempSymbol();
2169     OutStreamer->emitLabel(DotSym);
2170 
2171     // Now that we have emitted the label, lower the complex operand expression.
2172     MCSymbol *OpSym = MCInstLowering.GetSymbolFromOperand(MI->getOperand(2));
2173 
2174     const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
2175     const MCExpr *PICBase =
2176         MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
2177     DotExpr = MCBinaryExpr::createSub(DotExpr, PICBase, OutContext);
2178 
2179     DotExpr = MCBinaryExpr::createAdd(
2180         MCSymbolRefExpr::create(OpSym, OutContext), DotExpr, OutContext);
2181 
2182     EmitAndCountInstruction(MCInstBuilder(X86::ADD32ri)
2183                                 .addReg(MI->getOperand(0).getReg())
2184                                 .addReg(MI->getOperand(1).getReg())
2185                                 .addExpr(DotExpr));
2186     return;
2187   }
2188   case TargetOpcode::STATEPOINT:
2189     return LowerSTATEPOINT(*MI, MCInstLowering);
2190 
2191   case TargetOpcode::FAULTING_OP:
2192     return LowerFAULTING_OP(*MI, MCInstLowering);
2193 
2194   case TargetOpcode::FENTRY_CALL:
2195     return LowerFENTRY_CALL(*MI, MCInstLowering);
2196 
2197   case TargetOpcode::PATCHABLE_OP:
2198     return LowerPATCHABLE_OP(*MI, MCInstLowering);
2199 
2200   case TargetOpcode::STACKMAP:
2201     return LowerSTACKMAP(*MI);
2202 
2203   case TargetOpcode::PATCHPOINT:
2204     return LowerPATCHPOINT(*MI, MCInstLowering);
2205 
2206   case TargetOpcode::PATCHABLE_FUNCTION_ENTER:
2207     return LowerPATCHABLE_FUNCTION_ENTER(*MI, MCInstLowering);
2208 
2209   case TargetOpcode::PATCHABLE_RET:
2210     return LowerPATCHABLE_RET(*MI, MCInstLowering);
2211 
2212   case TargetOpcode::PATCHABLE_TAIL_CALL:
2213     return LowerPATCHABLE_TAIL_CALL(*MI, MCInstLowering);
2214 
2215   case TargetOpcode::PATCHABLE_EVENT_CALL:
2216     return LowerPATCHABLE_EVENT_CALL(*MI, MCInstLowering);
2217 
2218   case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
2219     return LowerPATCHABLE_TYPED_EVENT_CALL(*MI, MCInstLowering);
2220 
2221   case X86::MORESTACK_RET:
2222     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
2223     return;
2224 
2225   case X86::MORESTACK_RET_RESTORE_R10:
2226     // Return, then restore R10.
2227     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
2228     EmitAndCountInstruction(
2229         MCInstBuilder(X86::MOV64rr).addReg(X86::R10).addReg(X86::RAX));
2230     return;
2231 
2232   case X86::SEH_PushReg:
2233   case X86::SEH_SaveReg:
2234   case X86::SEH_SaveXMM:
2235   case X86::SEH_StackAlloc:
2236   case X86::SEH_StackAlign:
2237   case X86::SEH_SetFrame:
2238   case X86::SEH_PushFrame:
2239   case X86::SEH_EndPrologue:
2240     EmitSEHInstruction(MI);
2241     return;
2242 
2243   case X86::SEH_Epilogue: {
2244     assert(MF->hasWinCFI() && "SEH_ instruction in function without WinCFI?");
2245     MachineBasicBlock::const_iterator MBBI(MI);
2246     // Check if preceded by a call and emit nop if so.
2247     for (MBBI = PrevCrossBBInst(MBBI);
2248          MBBI != MachineBasicBlock::const_iterator();
2249          MBBI = PrevCrossBBInst(MBBI)) {
2250       // Conservatively assume that pseudo instructions don't emit code and keep
2251       // looking for a call. We may emit an unnecessary nop in some cases.
2252       if (!MBBI->isPseudo()) {
2253         if (MBBI->isCall())
2254           EmitAndCountInstruction(MCInstBuilder(X86::NOOP));
2255         break;
2256       }
2257     }
2258     return;
2259   }
2260 
2261   // Lower PSHUFB and VPERMILP normally but add a comment if we can find
2262   // a constant shuffle mask. We won't be able to do this at the MC layer
2263   // because the mask isn't an immediate.
2264   case X86::PSHUFBrm:
2265   case X86::VPSHUFBrm:
2266   case X86::VPSHUFBYrm:
2267   case X86::VPSHUFBZ128rm:
2268   case X86::VPSHUFBZ128rmk:
2269   case X86::VPSHUFBZ128rmkz:
2270   case X86::VPSHUFBZ256rm:
2271   case X86::VPSHUFBZ256rmk:
2272   case X86::VPSHUFBZ256rmkz:
2273   case X86::VPSHUFBZrm:
2274   case X86::VPSHUFBZrmk:
2275   case X86::VPSHUFBZrmkz: {
2276     if (!OutStreamer->isVerboseAsm())
2277       break;
2278     unsigned SrcIdx, MaskIdx;
2279     switch (MI->getOpcode()) {
2280     default: llvm_unreachable("Invalid opcode");
2281     case X86::PSHUFBrm:
2282     case X86::VPSHUFBrm:
2283     case X86::VPSHUFBYrm:
2284     case X86::VPSHUFBZ128rm:
2285     case X86::VPSHUFBZ256rm:
2286     case X86::VPSHUFBZrm:
2287       SrcIdx = 1; MaskIdx = 5; break;
2288     case X86::VPSHUFBZ128rmkz:
2289     case X86::VPSHUFBZ256rmkz:
2290     case X86::VPSHUFBZrmkz:
2291       SrcIdx = 2; MaskIdx = 6; break;
2292     case X86::VPSHUFBZ128rmk:
2293     case X86::VPSHUFBZ256rmk:
2294     case X86::VPSHUFBZrmk:
2295       SrcIdx = 3; MaskIdx = 7; break;
2296     }
2297 
2298     assert(MI->getNumOperands() >= 6 &&
2299            "We should always have at least 6 operands!");
2300 
2301     const MachineOperand &MaskOp = MI->getOperand(MaskIdx);
2302     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
2303       unsigned Width = getRegisterWidth(MI->getDesc().OpInfo[0]);
2304       SmallVector<int, 64> Mask;
2305       DecodePSHUFBMask(C, Width, Mask);
2306       if (!Mask.empty())
2307         OutStreamer->AddComment(getShuffleComment(MI, SrcIdx, SrcIdx, Mask));
2308     }
2309     break;
2310   }
2311 
2312   case X86::VPERMILPSrm:
2313   case X86::VPERMILPSYrm:
2314   case X86::VPERMILPSZ128rm:
2315   case X86::VPERMILPSZ128rmk:
2316   case X86::VPERMILPSZ128rmkz:
2317   case X86::VPERMILPSZ256rm:
2318   case X86::VPERMILPSZ256rmk:
2319   case X86::VPERMILPSZ256rmkz:
2320   case X86::VPERMILPSZrm:
2321   case X86::VPERMILPSZrmk:
2322   case X86::VPERMILPSZrmkz:
2323   case X86::VPERMILPDrm:
2324   case X86::VPERMILPDYrm:
2325   case X86::VPERMILPDZ128rm:
2326   case X86::VPERMILPDZ128rmk:
2327   case X86::VPERMILPDZ128rmkz:
2328   case X86::VPERMILPDZ256rm:
2329   case X86::VPERMILPDZ256rmk:
2330   case X86::VPERMILPDZ256rmkz:
2331   case X86::VPERMILPDZrm:
2332   case X86::VPERMILPDZrmk:
2333   case X86::VPERMILPDZrmkz: {
2334     if (!OutStreamer->isVerboseAsm())
2335       break;
2336     unsigned SrcIdx, MaskIdx;
2337     unsigned ElSize;
2338     switch (MI->getOpcode()) {
2339     default: llvm_unreachable("Invalid opcode");
2340     case X86::VPERMILPSrm:
2341     case X86::VPERMILPSYrm:
2342     case X86::VPERMILPSZ128rm:
2343     case X86::VPERMILPSZ256rm:
2344     case X86::VPERMILPSZrm:
2345       SrcIdx = 1; MaskIdx = 5; ElSize = 32; break;
2346     case X86::VPERMILPSZ128rmkz:
2347     case X86::VPERMILPSZ256rmkz:
2348     case X86::VPERMILPSZrmkz:
2349       SrcIdx = 2; MaskIdx = 6; ElSize = 32; break;
2350     case X86::VPERMILPSZ128rmk:
2351     case X86::VPERMILPSZ256rmk:
2352     case X86::VPERMILPSZrmk:
2353       SrcIdx = 3; MaskIdx = 7; ElSize = 32; break;
2354     case X86::VPERMILPDrm:
2355     case X86::VPERMILPDYrm:
2356     case X86::VPERMILPDZ128rm:
2357     case X86::VPERMILPDZ256rm:
2358     case X86::VPERMILPDZrm:
2359       SrcIdx = 1; MaskIdx = 5; ElSize = 64; break;
2360     case X86::VPERMILPDZ128rmkz:
2361     case X86::VPERMILPDZ256rmkz:
2362     case X86::VPERMILPDZrmkz:
2363       SrcIdx = 2; MaskIdx = 6; ElSize = 64; break;
2364     case X86::VPERMILPDZ128rmk:
2365     case X86::VPERMILPDZ256rmk:
2366     case X86::VPERMILPDZrmk:
2367       SrcIdx = 3; MaskIdx = 7; ElSize = 64; break;
2368     }
2369 
2370     assert(MI->getNumOperands() >= 6 &&
2371            "We should always have at least 6 operands!");
2372 
2373     const MachineOperand &MaskOp = MI->getOperand(MaskIdx);
2374     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
2375       unsigned Width = getRegisterWidth(MI->getDesc().OpInfo[0]);
2376       SmallVector<int, 16> Mask;
2377       DecodeVPERMILPMask(C, ElSize, Width, Mask);
2378       if (!Mask.empty())
2379         OutStreamer->AddComment(getShuffleComment(MI, SrcIdx, SrcIdx, Mask));
2380     }
2381     break;
2382   }
2383 
2384   case X86::VPERMIL2PDrm:
2385   case X86::VPERMIL2PSrm:
2386   case X86::VPERMIL2PDYrm:
2387   case X86::VPERMIL2PSYrm: {
2388     if (!OutStreamer->isVerboseAsm())
2389       break;
2390     assert(MI->getNumOperands() >= 8 &&
2391            "We should always have at least 8 operands!");
2392 
2393     const MachineOperand &CtrlOp = MI->getOperand(MI->getNumOperands() - 1);
2394     if (!CtrlOp.isImm())
2395       break;
2396 
2397     unsigned ElSize;
2398     switch (MI->getOpcode()) {
2399     default: llvm_unreachable("Invalid opcode");
2400     case X86::VPERMIL2PSrm: case X86::VPERMIL2PSYrm: ElSize = 32; break;
2401     case X86::VPERMIL2PDrm: case X86::VPERMIL2PDYrm: ElSize = 64; break;
2402     }
2403 
2404     const MachineOperand &MaskOp = MI->getOperand(6);
2405     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
2406       unsigned Width = getRegisterWidth(MI->getDesc().OpInfo[0]);
2407       SmallVector<int, 16> Mask;
2408       DecodeVPERMIL2PMask(C, (unsigned)CtrlOp.getImm(), ElSize, Width, Mask);
2409       if (!Mask.empty())
2410         OutStreamer->AddComment(getShuffleComment(MI, 1, 2, Mask));
2411     }
2412     break;
2413   }
2414 
2415   case X86::VPPERMrrm: {
2416     if (!OutStreamer->isVerboseAsm())
2417       break;
2418     assert(MI->getNumOperands() >= 7 &&
2419            "We should always have at least 7 operands!");
2420 
2421     const MachineOperand &MaskOp = MI->getOperand(6);
2422     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
2423       unsigned Width = getRegisterWidth(MI->getDesc().OpInfo[0]);
2424       SmallVector<int, 16> Mask;
2425       DecodeVPPERMMask(C, Width, Mask);
2426       if (!Mask.empty())
2427         OutStreamer->AddComment(getShuffleComment(MI, 1, 2, Mask));
2428     }
2429     break;
2430   }
2431 
2432   case X86::MMX_MOVQ64rm: {
2433     if (!OutStreamer->isVerboseAsm())
2434       break;
2435     if (MI->getNumOperands() <= 4)
2436       break;
2437     if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
2438       std::string Comment;
2439       raw_string_ostream CS(Comment);
2440       const MachineOperand &DstOp = MI->getOperand(0);
2441       CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
2442       if (auto *CF = dyn_cast<ConstantFP>(C)) {
2443         CS << "0x" << CF->getValueAPF().bitcastToAPInt().toString(16, false);
2444         OutStreamer->AddComment(CS.str());
2445       }
2446     }
2447     break;
2448   }
2449 
2450 #define MOV_CASE(Prefix, Suffix)                                               \
2451   case X86::Prefix##MOVAPD##Suffix##rm:                                        \
2452   case X86::Prefix##MOVAPS##Suffix##rm:                                        \
2453   case X86::Prefix##MOVUPD##Suffix##rm:                                        \
2454   case X86::Prefix##MOVUPS##Suffix##rm:                                        \
2455   case X86::Prefix##MOVDQA##Suffix##rm:                                        \
2456   case X86::Prefix##MOVDQU##Suffix##rm:
2457 
2458 #define MOV_AVX512_CASE(Suffix)                                                \
2459   case X86::VMOVDQA64##Suffix##rm:                                             \
2460   case X86::VMOVDQA32##Suffix##rm:                                             \
2461   case X86::VMOVDQU64##Suffix##rm:                                             \
2462   case X86::VMOVDQU32##Suffix##rm:                                             \
2463   case X86::VMOVDQU16##Suffix##rm:                                             \
2464   case X86::VMOVDQU8##Suffix##rm:                                              \
2465   case X86::VMOVAPS##Suffix##rm:                                               \
2466   case X86::VMOVAPD##Suffix##rm:                                               \
2467   case X86::VMOVUPS##Suffix##rm:                                               \
2468   case X86::VMOVUPD##Suffix##rm:
2469 
2470 #define CASE_ALL_MOV_RM()                                                      \
2471   MOV_CASE(, )   /* SSE */                                                     \
2472   MOV_CASE(V, )  /* AVX-128 */                                                 \
2473   MOV_CASE(V, Y) /* AVX-256 */                                                 \
2474   MOV_AVX512_CASE(Z)                                                           \
2475   MOV_AVX512_CASE(Z256)                                                        \
2476   MOV_AVX512_CASE(Z128)
2477 
2478     // For loads from a constant pool to a vector register, print the constant
2479     // loaded.
2480     CASE_ALL_MOV_RM()
2481   case X86::VBROADCASTF128:
2482   case X86::VBROADCASTI128:
2483   case X86::VBROADCASTF32X4Z256rm:
2484   case X86::VBROADCASTF32X4rm:
2485   case X86::VBROADCASTF32X8rm:
2486   case X86::VBROADCASTF64X2Z128rm:
2487   case X86::VBROADCASTF64X2rm:
2488   case X86::VBROADCASTF64X4rm:
2489   case X86::VBROADCASTI32X4Z256rm:
2490   case X86::VBROADCASTI32X4rm:
2491   case X86::VBROADCASTI32X8rm:
2492   case X86::VBROADCASTI64X2Z128rm:
2493   case X86::VBROADCASTI64X2rm:
2494   case X86::VBROADCASTI64X4rm:
2495     if (!OutStreamer->isVerboseAsm())
2496       break;
2497     if (MI->getNumOperands() <= 4)
2498       break;
2499     if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
2500       int NumLanes = 1;
2501       // Override NumLanes for the broadcast instructions.
2502       switch (MI->getOpcode()) {
2503       case X86::VBROADCASTF128:        NumLanes = 2; break;
2504       case X86::VBROADCASTI128:        NumLanes = 2; break;
2505       case X86::VBROADCASTF32X4Z256rm: NumLanes = 2; break;
2506       case X86::VBROADCASTF32X4rm:     NumLanes = 4; break;
2507       case X86::VBROADCASTF32X8rm:     NumLanes = 2; break;
2508       case X86::VBROADCASTF64X2Z128rm: NumLanes = 2; break;
2509       case X86::VBROADCASTF64X2rm:     NumLanes = 4; break;
2510       case X86::VBROADCASTF64X4rm:     NumLanes = 2; break;
2511       case X86::VBROADCASTI32X4Z256rm: NumLanes = 2; break;
2512       case X86::VBROADCASTI32X4rm:     NumLanes = 4; break;
2513       case X86::VBROADCASTI32X8rm:     NumLanes = 2; break;
2514       case X86::VBROADCASTI64X2Z128rm: NumLanes = 2; break;
2515       case X86::VBROADCASTI64X2rm:     NumLanes = 4; break;
2516       case X86::VBROADCASTI64X4rm:     NumLanes = 2; break;
2517       }
2518 
2519       std::string Comment;
2520       raw_string_ostream CS(Comment);
2521       const MachineOperand &DstOp = MI->getOperand(0);
2522       CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
2523       if (auto *CDS = dyn_cast<ConstantDataSequential>(C)) {
2524         CS << "[";
2525         for (int l = 0; l != NumLanes; ++l) {
2526           for (int i = 0, NumElements = CDS->getNumElements(); i < NumElements;
2527                ++i) {
2528             if (i != 0 || l != 0)
2529               CS << ",";
2530             if (CDS->getElementType()->isIntegerTy())
2531               printConstant(CDS->getElementAsAPInt(i), CS);
2532             else if (CDS->getElementType()->isHalfTy() ||
2533                      CDS->getElementType()->isFloatTy() ||
2534                      CDS->getElementType()->isDoubleTy())
2535               printConstant(CDS->getElementAsAPFloat(i), CS);
2536             else
2537               CS << "?";
2538           }
2539         }
2540         CS << "]";
2541         OutStreamer->AddComment(CS.str());
2542       } else if (auto *CV = dyn_cast<ConstantVector>(C)) {
2543         CS << "<";
2544         for (int l = 0; l != NumLanes; ++l) {
2545           for (int i = 0, NumOperands = CV->getNumOperands(); i < NumOperands;
2546                ++i) {
2547             if (i != 0 || l != 0)
2548               CS << ",";
2549             printConstant(CV->getOperand(i), CS);
2550           }
2551         }
2552         CS << ">";
2553         OutStreamer->AddComment(CS.str());
2554       }
2555     }
2556     break;
2557   case X86::MOVDDUPrm:
2558   case X86::VMOVDDUPrm:
2559   case X86::VMOVDDUPZ128rm:
2560   case X86::VBROADCASTSSrm:
2561   case X86::VBROADCASTSSYrm:
2562   case X86::VBROADCASTSSZ128rm:
2563   case X86::VBROADCASTSSZ256rm:
2564   case X86::VBROADCASTSSZrm:
2565   case X86::VBROADCASTSDYrm:
2566   case X86::VBROADCASTSDZ256rm:
2567   case X86::VBROADCASTSDZrm:
2568   case X86::VPBROADCASTBrm:
2569   case X86::VPBROADCASTBYrm:
2570   case X86::VPBROADCASTBZ128rm:
2571   case X86::VPBROADCASTBZ256rm:
2572   case X86::VPBROADCASTBZrm:
2573   case X86::VPBROADCASTDrm:
2574   case X86::VPBROADCASTDYrm:
2575   case X86::VPBROADCASTDZ128rm:
2576   case X86::VPBROADCASTDZ256rm:
2577   case X86::VPBROADCASTDZrm:
2578   case X86::VPBROADCASTQrm:
2579   case X86::VPBROADCASTQYrm:
2580   case X86::VPBROADCASTQZ128rm:
2581   case X86::VPBROADCASTQZ256rm:
2582   case X86::VPBROADCASTQZrm:
2583   case X86::VPBROADCASTWrm:
2584   case X86::VPBROADCASTWYrm:
2585   case X86::VPBROADCASTWZ128rm:
2586   case X86::VPBROADCASTWZ256rm:
2587   case X86::VPBROADCASTWZrm:
2588     if (!OutStreamer->isVerboseAsm())
2589       break;
2590     if (MI->getNumOperands() <= 4)
2591       break;
2592     if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
2593       int NumElts;
2594       switch (MI->getOpcode()) {
2595       default: llvm_unreachable("Invalid opcode");
2596       case X86::MOVDDUPrm:          NumElts = 2;  break;
2597       case X86::VMOVDDUPrm:         NumElts = 2;  break;
2598       case X86::VMOVDDUPZ128rm:     NumElts = 2;  break;
2599       case X86::VBROADCASTSSrm:     NumElts = 4;  break;
2600       case X86::VBROADCASTSSYrm:    NumElts = 8;  break;
2601       case X86::VBROADCASTSSZ128rm: NumElts = 4;  break;
2602       case X86::VBROADCASTSSZ256rm: NumElts = 8;  break;
2603       case X86::VBROADCASTSSZrm:    NumElts = 16; break;
2604       case X86::VBROADCASTSDYrm:    NumElts = 4;  break;
2605       case X86::VBROADCASTSDZ256rm: NumElts = 4;  break;
2606       case X86::VBROADCASTSDZrm:    NumElts = 8;  break;
2607       case X86::VPBROADCASTBrm:     NumElts = 16; break;
2608       case X86::VPBROADCASTBYrm:    NumElts = 32; break;
2609       case X86::VPBROADCASTBZ128rm: NumElts = 16; break;
2610       case X86::VPBROADCASTBZ256rm: NumElts = 32; break;
2611       case X86::VPBROADCASTBZrm:    NumElts = 64; break;
2612       case X86::VPBROADCASTDrm:     NumElts = 4;  break;
2613       case X86::VPBROADCASTDYrm:    NumElts = 8;  break;
2614       case X86::VPBROADCASTDZ128rm: NumElts = 4;  break;
2615       case X86::VPBROADCASTDZ256rm: NumElts = 8;  break;
2616       case X86::VPBROADCASTDZrm:    NumElts = 16; break;
2617       case X86::VPBROADCASTQrm:     NumElts = 2;  break;
2618       case X86::VPBROADCASTQYrm:    NumElts = 4;  break;
2619       case X86::VPBROADCASTQZ128rm: NumElts = 2;  break;
2620       case X86::VPBROADCASTQZ256rm: NumElts = 4;  break;
2621       case X86::VPBROADCASTQZrm:    NumElts = 8;  break;
2622       case X86::VPBROADCASTWrm:     NumElts = 8;  break;
2623       case X86::VPBROADCASTWYrm:    NumElts = 16; break;
2624       case X86::VPBROADCASTWZ128rm: NumElts = 8;  break;
2625       case X86::VPBROADCASTWZ256rm: NumElts = 16; break;
2626       case X86::VPBROADCASTWZrm:    NumElts = 32; break;
2627       }
2628 
2629       std::string Comment;
2630       raw_string_ostream CS(Comment);
2631       const MachineOperand &DstOp = MI->getOperand(0);
2632       CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
2633       CS << "[";
2634       for (int i = 0; i != NumElts; ++i) {
2635         if (i != 0)
2636           CS << ",";
2637         printConstant(C, CS);
2638       }
2639       CS << "]";
2640       OutStreamer->AddComment(CS.str());
2641     }
2642   }
2643 
2644   MCInst TmpInst;
2645   MCInstLowering.Lower(MI, TmpInst);
2646 
2647   // Stackmap shadows cannot include branch targets, so we can count the bytes
2648   // in a call towards the shadow, but must ensure that the no thread returns
2649   // in to the stackmap shadow.  The only way to achieve this is if the call
2650   // is at the end of the shadow.
2651   if (MI->isCall()) {
2652     // Count then size of the call towards the shadow
2653     SMShadowTracker.count(TmpInst, getSubtargetInfo(), CodeEmitter.get());
2654     // Then flush the shadow so that we fill with nops before the call, not
2655     // after it.
2656     SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
2657     // Then emit the call
2658     OutStreamer->emitInstruction(TmpInst, getSubtargetInfo());
2659     return;
2660   }
2661 
2662   EmitAndCountInstruction(TmpInst);
2663 }
2664