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