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