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