LLVM 24.0.0git
X86MCInstLower.cpp
Go to the documentation of this file.
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
21#include "X86AsmPrinter.h"
23#include "X86RegisterInfo.h"
25#include "X86Subtarget.h"
26#include "llvm/ADT/STLExtras.h"
37#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/GlobalValue.h"
39#include "llvm/IR/Mangler.h"
40#include "llvm/MC/MCAsmInfo.h"
42#include "llvm/MC/MCContext.h"
43#include "llvm/MC/MCExpr.h"
44#include "llvm/MC/MCFixup.h"
45#include "llvm/MC/MCInst.h"
47#include "llvm/MC/MCSection.h"
49#include "llvm/MC/MCStreamer.h"
50#include "llvm/MC/MCSymbol.h"
57#include <string>
58
59using namespace llvm;
60
61namespace {
62
63/// X86MCInstLower - This class is used to lower an MachineInstr into an MCInst.
64class X86MCInstLower {
65 MCContext &Ctx;
66 const MachineFunction &MF;
67 const TargetMachine &TM;
68 const MCAsmInfo &MAI;
69 X86AsmPrinter &AsmPrinter;
70
71public:
72 X86MCInstLower(const MachineFunction &MF, X86AsmPrinter &asmprinter);
73
74 MCOperand LowerMachineOperand(const MachineInstr *MI,
75 const MachineOperand &MO) const;
76 void Lower(const MachineInstr *MI, MCInst &OutMI) const;
77
78 MCSymbol *GetSymbolFromOperand(const MachineOperand &MO) const;
79 MCOperand LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const;
80
81private:
82 MachineModuleInfoMachO &getMachOMMI() const;
83};
84
85} // end anonymous namespace
86
87/// A RAII helper which defines a region of instructions which can't have
88/// padding added between them for correctness.
93 : OS(OS), OldAllowAutoPadding(OS.getAllowAutoPadding()) {
94 changeAndComment(false);
95 }
97 void changeAndComment(bool b) {
98 if (b == OS.getAllowAutoPadding())
99 return;
100 OS.setAllowAutoPadding(b);
101 if (b)
102 OS.emitRawComment("autopadding");
103 else
104 OS.emitRawComment("noautopadding");
105 }
106};
107
108// Emit a minimal sequence of nops spanning NumBytes bytes.
109static void emitX86Nops(MCStreamer &OS, unsigned NumBytes,
110 const X86Subtarget *Subtarget);
111
112void X86AsmPrinter::StackMapShadowTracker::count(const MCInst &Inst,
113 const MCSubtargetInfo &STI,
114 MCCodeEmitter *CodeEmitter) {
115 if (InShadow) {
116 SmallString<256> Code;
118 CodeEmitter->encodeInstruction(Inst, Code, Fixups, STI);
119 CurrentShadowSize += Code.size();
120 if (CurrentShadowSize >= RequiredShadowSize)
121 InShadow = false; // The shadow is big enough. Stop counting.
122 }
123}
124
125void X86AsmPrinter::StackMapShadowTracker::emitShadowPadding(
126 MCStreamer &OutStreamer, const MCSubtargetInfo &STI) {
127 if (InShadow && CurrentShadowSize < RequiredShadowSize) {
128 InShadow = false;
129 emitX86Nops(OutStreamer, RequiredShadowSize - CurrentShadowSize,
130 &MF->getSubtarget<X86Subtarget>());
131 }
132}
133
134void X86AsmPrinter::EmitAndCountInstruction(MCInst &Inst) {
135 OutStreamer->emitInstruction(Inst, getSubtargetInfo());
136 SMShadowTracker.count(Inst, getSubtargetInfo(), CodeEmitter.get());
137}
138
139X86MCInstLower::X86MCInstLower(const MachineFunction &mf,
140 X86AsmPrinter &asmprinter)
141 : Ctx(asmprinter.OutContext), MF(mf), TM(mf.getTarget()),
142 MAI(TM.getMCAsmInfo()), AsmPrinter(asmprinter) {}
143
144MachineModuleInfoMachO &X86MCInstLower::getMachOMMI() const {
145 return AsmPrinter.MMI->getObjFileInfo<MachineModuleInfoMachO>();
146}
147
148/// GetSymbolFromOperand - Lower an MO_GlobalAddress or MO_ExternalSymbol
149/// operand to an MCSymbol.
150MCSymbol *X86MCInstLower::GetSymbolFromOperand(const MachineOperand &MO) const {
151 const Triple &TT = TM.getTargetTriple();
152 if (MO.isGlobal() && TT.isOSBinFormatELF())
153 return AsmPrinter.getSymbolPreferLocal(*MO.getGlobal());
154
155 const DataLayout &DL = MF.getDataLayout();
156 assert((MO.isGlobal() || MO.isSymbol() || MO.isMBB()) &&
157 "Isn't a symbol reference");
158
159 MCSymbol *Sym = nullptr;
160 SmallString<128> Name;
161 StringRef Suffix;
162
163 switch (MO.getTargetFlags()) {
165 // Handle dllimport linkage.
166 Name += "__imp_";
167 break;
169 Name += ".refptr.";
170 break;
173 Suffix = "$non_lazy_ptr";
174 break;
175 }
176
177 if (!Suffix.empty())
178 Name += DL.getInternalSymbolPrefix();
179
180 if (MO.isGlobal()) {
181 const GlobalValue *GV = MO.getGlobal();
182 AsmPrinter.getNameWithPrefix(Name, GV);
183 } else if (MO.isSymbol()) {
185 } else if (MO.isMBB()) {
186 assert(Suffix.empty());
187 Sym = MO.getMBB()->getSymbol();
188 }
189
190 Name += Suffix;
191 if (!Sym)
192 Sym = Ctx.getOrCreateSymbol(Name);
193
194 // If the target flags on the operand changes the name of the symbol, do that
195 // before we return the symbol.
196 switch (MO.getTargetFlags()) {
197 default:
198 break;
199 case X86II::MO_COFFSTUB: {
200 MachineModuleInfoCOFF &MMICOFF =
201 AsmPrinter.MMI->getObjFileInfo<MachineModuleInfoCOFF>();
203 if (!StubSym.getPointer()) {
204 assert(MO.isGlobal() && "Extern symbol not handled yet");
206 AsmPrinter.getSymbol(MO.getGlobal()), true);
207 }
208 break;
209 }
213 getMachOMMI().getGVStubEntry(Sym);
214 if (!StubSym.getPointer()) {
215 assert(MO.isGlobal() && "Extern symbol not handled yet");
217 AsmPrinter.getSymbol(MO.getGlobal()),
219 }
220 break;
221 }
222 }
223
224 return Sym;
225}
226
227MCOperand X86MCInstLower::LowerSymbolOperand(const MachineOperand &MO,
228 MCSymbol *Sym) const {
229 // FIXME: We would like an efficient form for this, so we don't have to do a
230 // lot of extra uniquing.
231 const MCExpr *Expr = nullptr;
232 uint16_t Specifier = X86::S_None;
233
234 switch (MO.getTargetFlags()) {
235 default:
236 llvm_unreachable("Unknown target flag on GV operand");
237 case X86II::MO_NO_FLAG: // No flag.
238 // These affect the name of the symbol, not any suffix.
242 break;
243
244 case X86II::MO_TLVP:
246 break;
248 Expr = MCSymbolRefExpr::create(Sym, X86::S_TLVP, Ctx);
249 // Subtract the pic base.
251 Expr, MCSymbolRefExpr::create(MF.getPICBaseSymbol(), Ctx), Ctx);
252 break;
253 case X86II::MO_SECREL:
254 Specifier = uint16_t(X86::S_COFF_SECREL);
255 break;
256 case X86II::MO_TLSGD:
258 break;
259 case X86II::MO_TLSLD:
261 break;
262 case X86II::MO_TLSLDM:
264 break;
267 break;
270 break;
271 case X86II::MO_TPOFF:
273 break;
274 case X86II::MO_DTPOFF:
276 break;
277 case X86II::MO_NTPOFF:
279 break;
282 break;
285 break;
288 break;
289 case X86II::MO_GOT:
291 break;
292 case X86II::MO_GOTOFF:
294 break;
295 case X86II::MO_PLT:
297 break;
298 case X86II::MO_ABS8:
300 break;
303 Expr = MCSymbolRefExpr::create(Sym, Ctx);
304 // Subtract the pic base.
306 Expr, MCSymbolRefExpr::create(MF.getPICBaseSymbol(), Ctx), Ctx);
307 if (MO.isJTI()) {
309 // If .set directive is supported, use it to reduce the number of
310 // relocations the assembler will generate for differences between
311 // local labels. This is only safe when the symbols are in the same
312 // section so we are restricting it to jumptable references.
314 AsmPrinter.OutStreamer->emitAssignment(Label, Expr);
315 Expr = MCSymbolRefExpr::create(Label, Ctx);
316 }
317 break;
318 }
319
320 if (!Expr)
321 Expr = MCSymbolRefExpr::create(Sym, Specifier, Ctx);
322
323 if (!MO.isJTI() && !MO.isMBB() && MO.getOffset())
325 Expr, MCConstantExpr::create(MO.getOffset(), Ctx), Ctx);
326 return MCOperand::createExpr(Expr);
327}
328
329static unsigned getRetOpcode(const X86Subtarget &Subtarget) {
330 return Subtarget.is64Bit() ? X86::RET64 : X86::RET32;
331}
332
333MCOperand X86MCInstLower::LowerMachineOperand(const MachineInstr *MI,
334 const MachineOperand &MO) const {
335 switch (MO.getType()) {
336 default:
337 MI->print(errs());
338 llvm_unreachable("unknown operand type");
340 // Ignore all implicit register operands.
341 if (MO.isImplicit())
342 return MCOperand();
343 return MCOperand::createReg(MO.getReg());
345 return MCOperand::createImm(MO.getImm());
351 return LowerSymbolOperand(MO, MO.getMCSymbol());
353 return LowerSymbolOperand(MO, AsmPrinter.GetJTISymbol(MO.getIndex()));
355 return LowerSymbolOperand(MO, AsmPrinter.GetCPISymbol(MO.getIndex()));
357 return LowerSymbolOperand(
358 MO, AsmPrinter.GetBlockAddressSymbol(MO.getBlockAddress()));
360 // Ignore call clobbers.
361 return MCOperand();
362 }
363}
364
365// Replace TAILJMP opcodes with their equivalent opcodes that have encoding
366// information.
367static unsigned convertTailJumpOpcode(unsigned Opcode, bool IsLarge = false) {
368 switch (Opcode) {
369 case X86::TAILJMPr:
370 Opcode = X86::JMP32r;
371 break;
372 case X86::TAILJMPm:
373 Opcode = X86::JMP32m;
374 break;
375 case X86::TAILJMPr64:
376 Opcode = X86::JMP64r;
377 break;
378 case X86::TAILJMPm64:
379 Opcode = X86::JMP64m;
380 break;
381 case X86::TAILJMPr64_REX:
382 Opcode = X86::JMP64r_REX;
383 break;
384 case X86::TAILJMPm64_REX:
385 Opcode = X86::JMP64m_REX;
386 break;
387 case X86::TAILJMPd:
388 case X86::TAILJMPd64:
389 Opcode = IsLarge ? X86::JMPABS64i : X86::JMP_1;
390 break;
391 case X86::TAILJMPd_CC:
392 case X86::TAILJMPd64_CC:
393 Opcode = X86::JCC_1;
394 break;
395 }
396
397 return Opcode;
398}
399
400void X86MCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const {
401 OutMI.setOpcode(MI->getOpcode());
402
403 for (const MachineOperand &MO : MI->operands())
404 if (auto Op = LowerMachineOperand(MI, MO); Op.isValid())
405 OutMI.addOperand(Op);
406
407 bool In64BitMode = AsmPrinter.getSubtarget().is64Bit();
408 if (X86::optimizeInstFromVEX3ToVEX2(OutMI, MI->getDesc()) ||
411 X86::optimizeMOVSX(OutMI) || X86::optimizeINCDEC(OutMI, In64BitMode) ||
412 X86::optimizeMOV(OutMI, In64BitMode) ||
414 return;
415
416 // Handle a few special cases to eliminate operand modifiers.
417 switch (OutMI.getOpcode()) {
418 case X86::LEA64_32r:
419 case X86::LEA64r:
420 case X86::LEA16r:
421 case X86::LEA32r:
422 // LEA should have a segment register, but it must be empty.
424 "Unexpected # of LEA operands");
425 assert(OutMI.getOperand(1 + X86::AddrSegmentReg).getReg() == 0 &&
426 "LEA has segment specified!");
427 break;
428 case X86::MULX32Hrr:
429 case X86::MULX32Hrm:
430 case X86::MULX64Hrr:
431 case X86::MULX64Hrm: {
432 // Turn into regular MULX by duplicating the destination.
433 unsigned NewOpc;
434 switch (OutMI.getOpcode()) {
435 default: llvm_unreachable("Invalid opcode");
436 case X86::MULX32Hrr: NewOpc = X86::MULX32rr; break;
437 case X86::MULX32Hrm: NewOpc = X86::MULX32rm; break;
438 case X86::MULX64Hrr: NewOpc = X86::MULX64rr; break;
439 case X86::MULX64Hrm: NewOpc = X86::MULX64rm; break;
440 }
441 OutMI.setOpcode(NewOpc);
442 // Duplicate the destination.
443 MCRegister DestReg = OutMI.getOperand(0).getReg();
444 OutMI.insert(OutMI.begin(), MCOperand::createReg(DestReg));
445 break;
446 }
447 // CALL64r, CALL64pcrel32 - These instructions used to have
448 // register inputs modeled as normal uses instead of implicit uses. As such,
449 // they we used to truncate off all but the first operand (the callee). This
450 // issue seems to have been fixed at some point. This assert verifies that.
451 case X86::CALL64r:
452 case X86::CALL64pcrel32:
453 assert(OutMI.getNumOperands() == 1 && "Unexpected number of operands!");
454 break;
455 case X86::EH_RETURN:
456 case X86::EH_RETURN64: {
457 OutMI = MCInst();
458 OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
459 break;
460 }
461 case X86::CLEANUPRET: {
462 // Replace CLEANUPRET with the appropriate RET.
463 OutMI = MCInst();
464 OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
465 break;
466 }
467 case X86::CATCHRET: {
468 // Replace CATCHRET with the appropriate RET.
469 const X86Subtarget &Subtarget = AsmPrinter.getSubtarget();
470 unsigned ReturnReg = In64BitMode ? X86::RAX : X86::EAX;
471 OutMI = MCInst();
473 OutMI.addOperand(MCOperand::createReg(ReturnReg));
474 break;
475 }
476 // TAILJMPd, TAILJMPd64, TailJMPd_cc - Lower to the correct jump
477 // instruction.
478 case X86::TAILJMPr:
479 case X86::TAILJMPr64:
480 case X86::TAILJMPr64_REX:
481 case X86::TAILJMPd:
482 assert(OutMI.getNumOperands() == 1 && "Unexpected number of operands!");
484 break;
485 case X86::TAILJMPd64: {
486 assert(OutMI.getNumOperands() == 1 && "Unexpected number of operands!");
487 bool IsLarge = TM.getCodeModel() == CodeModel::Large;
488 assert((!IsLarge || AsmPrinter.getSubtarget().hasJMPABS()) &&
489 "Unexpected TAILJMPd64 in large code model without JMPABS");
490 OutMI.setOpcode(convertTailJumpOpcode(OutMI.getOpcode(), IsLarge));
491 break;
492 }
493 case X86::TAILJMPd_CC:
494 case X86::TAILJMPd64_CC:
495 assert(OutMI.getNumOperands() == 2 && "Unexpected number of operands!");
497 break;
498 case X86::TAILJMPm:
499 case X86::TAILJMPm64:
500 case X86::TAILJMPm64_REX:
502 "Unexpected number of operands!");
504 break;
505 case X86::MASKMOVDQU:
506 case X86::VMASKMOVDQU:
507 if (In64BitMode)
509 break;
510 case X86::BSF16rm:
511 case X86::BSF16rr:
512 case X86::BSF32rm:
513 case X86::BSF32rr:
514 case X86::BSF64rm:
515 case X86::BSF64rr: {
516 // Add an REP prefix to BSF instructions so that new processors can
517 // recognize as TZCNT, which has better performance than BSF.
518 // BSF and TZCNT have different interpretations on ZF bit. So make sure
519 // it won't be used later.
520 const MachineOperand *FlagDef =
521 MI->findRegisterDefOperand(X86::EFLAGS, /*TRI=*/nullptr);
522 if (!MF.getFunction().hasOptSize() && FlagDef && FlagDef->isDead())
524 break;
525 }
526 default:
527 break;
528 }
529}
530
531void X86AsmPrinter::LowerTlsAddr(X86MCInstLower &MCInstLowering,
532 const MachineInstr &MI) {
533 NoAutoPaddingScope NoPadScope(*OutStreamer);
534 bool Is64Bits = getSubtarget().is64Bit();
535 bool Is64BitsLP64 = getSubtarget().isTarget64BitLP64();
536 MCContext &Ctx = OutStreamer->getContext();
537
539 switch (MI.getOpcode()) {
540 case X86::TLS_addr32:
541 case X86::TLS_addr64:
542 case X86::TLS_addrX32:
544 break;
545 case X86::TLS_base_addr32:
547 break;
548 case X86::TLS_base_addr64:
549 case X86::TLS_base_addrX32:
551 break;
552 case X86::TLS_desc32:
553 case X86::TLS_desc64:
555 break;
556 default:
557 llvm_unreachable("unexpected opcode");
558 }
559
560 const MCSymbolRefExpr *Sym = MCSymbolRefExpr::create(
561 MCInstLowering.GetSymbolFromOperand(MI.getOperand(3)), Specifier, Ctx);
562
563 // Before binutils 2.41, ld has a bogus TLS relaxation error when the GD/LD
564 // code sequence using R_X86_64_GOTPCREL (instead of R_X86_64_GOTPCRELX) is
565 // attempted to be relaxed to IE/LE (binutils PR24784). Work around the bug by
566 // only using GOT when GOTPCRELX is enabled.
567 // TODO Delete the workaround when rustc no longer relies on the hack
568 bool UseGot = MMI->getModule()->getRtLibUseGOT() &&
570
571 if (Specifier == X86::S_TLSDESC) {
572 const MCSymbolRefExpr *Expr = MCSymbolRefExpr::create(
573 MCInstLowering.GetSymbolFromOperand(MI.getOperand(3)), X86::S_TLSCALL,
574 Ctx);
575 EmitAndCountInstruction(
576 MCInstBuilder(Is64BitsLP64 ? X86::LEA64r : X86::LEA32r)
577 .addReg(Is64BitsLP64 ? X86::RAX : X86::EAX)
578 .addReg(Is64Bits ? X86::RIP : X86::EBX)
579 .addImm(1)
580 .addReg(0)
581 .addExpr(Sym)
582 .addReg(0));
583 EmitAndCountInstruction(
584 MCInstBuilder(Is64Bits ? X86::CALL64m : X86::CALL32m)
585 .addReg(Is64BitsLP64 ? X86::RAX : X86::EAX)
586 .addImm(1)
587 .addReg(0)
588 .addExpr(Expr)
589 .addReg(0));
590 } else if (Is64Bits) {
591 bool NeedsPadding = Specifier == X86::S_TLSGD;
592 if (NeedsPadding && Is64BitsLP64)
593 EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
594 EmitAndCountInstruction(MCInstBuilder(X86::LEA64r)
595 .addReg(X86::RDI)
596 .addReg(X86::RIP)
597 .addImm(1)
598 .addReg(0)
599 .addExpr(Sym)
600 .addReg(0));
601 const MCSymbol *TlsGetAddr = Ctx.getOrCreateSymbol("__tls_get_addr");
602 if (NeedsPadding) {
603 if (!UseGot)
604 EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
605 EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
606 EmitAndCountInstruction(MCInstBuilder(X86::REX64_PREFIX));
607 }
608 if (UseGot) {
609 const MCExpr *Expr =
611 EmitAndCountInstruction(MCInstBuilder(X86::CALL64m)
612 .addReg(X86::RIP)
613 .addImm(1)
614 .addReg(0)
615 .addExpr(Expr)
616 .addReg(0));
617 } else {
618 EmitAndCountInstruction(
619 MCInstBuilder(X86::CALL64pcrel32)
620 .addExpr(MCSymbolRefExpr::create(TlsGetAddr, X86::S_PLT, Ctx)));
621 }
622 } else {
623 if (Specifier == X86::S_TLSGD && !UseGot) {
624 EmitAndCountInstruction(MCInstBuilder(X86::LEA32r)
625 .addReg(X86::EAX)
626 .addReg(0)
627 .addImm(1)
628 .addReg(X86::EBX)
629 .addExpr(Sym)
630 .addReg(0));
631 } else {
632 EmitAndCountInstruction(MCInstBuilder(X86::LEA32r)
633 .addReg(X86::EAX)
634 .addReg(X86::EBX)
635 .addImm(1)
636 .addReg(0)
637 .addExpr(Sym)
638 .addReg(0));
639 }
640
641 const MCSymbol *TlsGetAddr = Ctx.getOrCreateSymbol("___tls_get_addr");
642 if (UseGot) {
643 const MCExpr *Expr = MCSymbolRefExpr::create(TlsGetAddr, X86::S_GOT, Ctx);
644 EmitAndCountInstruction(MCInstBuilder(X86::CALL32m)
645 .addReg(X86::EBX)
646 .addImm(1)
647 .addReg(0)
648 .addExpr(Expr)
649 .addReg(0));
650 } else {
651 EmitAndCountInstruction(
652 MCInstBuilder(X86::CALLpcrel32)
653 .addExpr(MCSymbolRefExpr::create(TlsGetAddr, X86::S_PLT, Ctx)));
654 }
655 }
656}
657
658/// Emit the largest nop instruction smaller than or equal to \p NumBytes
659/// bytes. Return the size of nop emitted.
660static unsigned emitNop(MCStreamer &OS, unsigned NumBytes,
661 const X86Subtarget *Subtarget) {
662 // Determine the longest nop which can be efficiently decoded for the given
663 // target cpu. 15-bytes is the longest single NOP instruction, but some
664 // platforms can't decode the longest forms efficiently.
665 unsigned MaxNopLength = 1;
666 unsigned BaseReg = X86::RAX;
667 if (Subtarget->is64Bit()) {
668 if (Subtarget->hasFeature(X86::TuningFast7ByteNOP))
669 MaxNopLength = 7;
670 else if (Subtarget->hasFeature(X86::TuningFast15ByteNOP))
671 MaxNopLength = 15;
672 else if (Subtarget->hasFeature(X86::TuningFast11ByteNOP))
673 MaxNopLength = 11;
674 else
675 MaxNopLength = 10;
676 } else if (Subtarget->is32Bit() && Subtarget->hasFeature(X86::FeatureNOPL)) {
677 BaseReg = X86::EAX;
678 MaxNopLength = 10;
679 } else if (Subtarget->is32Bit())
680 MaxNopLength = 2;
681
682 // Cap a single nop emission at the profitable value for the target
683 NumBytes = std::min(NumBytes, MaxNopLength);
684
685 unsigned NopSize;
686 unsigned Opc, ScaleVal, IndexReg, Displacement, SegmentReg;
687 IndexReg = Displacement = SegmentReg = 0;
688 ScaleVal = 1;
689 switch (NumBytes) {
690 case 0:
691 llvm_unreachable("Zero nops?");
692 break;
693 case 1:
694 NopSize = 1;
695 Opc = X86::NOOP;
696 break;
697 case 2:
698 NopSize = 2;
699 Opc = X86::XCHG16ar;
700 break;
701 case 3:
702 NopSize = 3;
703 Opc = X86::NOOPL;
704 break;
705 case 4:
706 NopSize = 4;
707 Opc = X86::NOOPL;
708 Displacement = 8;
709 break;
710 case 5:
711 NopSize = 5;
712 Opc = X86::NOOPL;
713 Displacement = 8;
714 IndexReg = BaseReg;
715 break;
716 case 6:
717 NopSize = 6;
718 Opc = X86::NOOPW;
719 Displacement = 8;
720 IndexReg = BaseReg;
721 break;
722 case 7:
723 NopSize = 7;
724 Opc = X86::NOOPL;
725 Displacement = 512;
726 break;
727 case 8:
728 NopSize = 8;
729 Opc = X86::NOOPL;
730 Displacement = 512;
731 IndexReg = BaseReg;
732 break;
733 case 9:
734 NopSize = 9;
735 Opc = X86::NOOPW;
736 Displacement = 512;
737 IndexReg = BaseReg;
738 break;
739 default:
740 NopSize = 10;
741 Opc = X86::NOOPW;
742 Displacement = 512;
743 IndexReg = BaseReg;
744 SegmentReg = X86::CS;
745 break;
746 }
747
748 unsigned NumPrefixes = std::min(NumBytes - NopSize, 5U);
749 NopSize += NumPrefixes;
750 for (unsigned i = 0; i != NumPrefixes; ++i)
751 OS.emitBytes("\x66");
752
753 switch (Opc) {
754 default: llvm_unreachable("Unexpected opcode");
755 case X86::NOOP:
757 break;
758 case X86::XCHG16ar:
759 OS.emitInstruction(MCInstBuilder(Opc).addReg(X86::AX).addReg(X86::AX),
760 *Subtarget);
761 break;
762 case X86::NOOPL:
763 case X86::NOOPW:
765 .addReg(BaseReg)
766 .addImm(ScaleVal)
767 .addReg(IndexReg)
768 .addImm(Displacement)
769 .addReg(SegmentReg),
770 *Subtarget);
771 break;
772 }
773 assert(NopSize <= NumBytes && "We overemitted?");
774 return NopSize;
775}
776
777/// Emit the optimal amount of multi-byte nops on X86.
778static void emitX86Nops(MCStreamer &OS, unsigned NumBytes,
779 const X86Subtarget *Subtarget) {
780 unsigned NopsToEmit = NumBytes;
781 (void)NopsToEmit;
782 while (NumBytes) {
783 NumBytes -= emitNop(OS, NumBytes, Subtarget);
784 assert(NopsToEmit >= NumBytes && "Emitted more than I asked for!");
785 }
786}
787
788void X86AsmPrinter::LowerSTATEPOINT(const MachineInstr &MI,
789 X86MCInstLower &MCIL) {
790 assert(Subtarget->is64Bit() && "Statepoint currently only supports X86-64");
791
792 NoAutoPaddingScope NoPadScope(*OutStreamer);
793
794 StatepointOpers SOpers(&MI);
795 if (unsigned PatchBytes = SOpers.getNumPatchBytes()) {
796 emitX86Nops(*OutStreamer, PatchBytes, Subtarget);
797 } else {
798 // Lower call target and choose correct opcode
799 const MachineOperand &CallTarget = SOpers.getCallTarget();
800 MCOperand CallTargetMCOp;
801 unsigned CallOpcode;
802 switch (CallTarget.getType()) {
805 CallTargetMCOp = MCIL.LowerSymbolOperand(
806 CallTarget, MCIL.GetSymbolFromOperand(CallTarget));
807 CallOpcode = X86::CALL64pcrel32;
808 // Currently, we only support relative addressing with statepoints.
809 // Otherwise, we'll need a scratch register to hold the target
810 // address. You'll fail asserts during load & relocation if this
811 // symbol is to far away. (TODO: support non-relative addressing)
812 break;
814 CallTargetMCOp = MCOperand::createImm(CallTarget.getImm());
815 CallOpcode = X86::CALL64pcrel32;
816 // Currently, we only support relative addressing with statepoints.
817 // Otherwise, we'll need a scratch register to hold the target
818 // immediate. You'll fail asserts during load & relocation if this
819 // address is to far away. (TODO: support non-relative addressing)
820 break;
822 // FIXME: Add retpoline support and remove this.
823 if (Subtarget->useIndirectThunkCalls())
824 report_fatal_error("Lowering register statepoints with thunks not "
825 "yet implemented.");
826 CallTargetMCOp = MCOperand::createReg(CallTarget.getReg());
827 CallOpcode = X86::CALL64r;
828 break;
829 default:
830 llvm_unreachable("Unsupported operand type in statepoint call target");
831 break;
832 }
833
834 // Emit call
835 MCInst CallInst;
836 CallInst.setOpcode(CallOpcode);
837 CallInst.addOperand(CallTargetMCOp);
838 OutStreamer->emitInstruction(CallInst, getSubtargetInfo());
839 maybeEmitNopAfterCallForWindowsEH(&MI);
840 }
841
842 // Record our statepoint node in the same section used by STACKMAP
843 // and PATCHPOINT
844 auto &Ctx = OutStreamer->getContext();
845 MCSymbol *MILabel = Ctx.createTempSymbol();
846 OutStreamer->emitLabel(MILabel);
847 SM.recordStatepoint(*MILabel, MI);
848}
849
850void X86AsmPrinter::LowerFAULTING_OP(const MachineInstr &FaultingMI,
851 X86MCInstLower &MCIL) {
852 // FAULTING_LOAD_OP <def>, <faltinf type>, <MBB handler>,
853 // <opcode>, <operands>
854
855 NoAutoPaddingScope NoPadScope(*OutStreamer);
856
857 Register DefRegister = FaultingMI.getOperand(0).getReg();
859 static_cast<FaultMaps::FaultKind>(FaultingMI.getOperand(1).getImm());
860 MCSymbol *HandlerLabel = FaultingMI.getOperand(2).getMBB()->getSymbol();
861 unsigned Opcode = FaultingMI.getOperand(3).getImm();
862 unsigned OperandsBeginIdx = 4;
863
864 auto &Ctx = OutStreamer->getContext();
865 MCSymbol *FaultingLabel = Ctx.createTempSymbol();
866 OutStreamer->emitLabel(FaultingLabel);
867
868 assert(FK < FaultMaps::FaultKindMax && "Invalid Faulting Kind!");
869 FM.recordFaultingOp(FK, FaultingLabel, HandlerLabel);
870
871 MCInst MI;
872 MI.setOpcode(Opcode);
873
874 if (DefRegister != X86::NoRegister)
875 MI.addOperand(MCOperand::createReg(DefRegister));
876
877 for (const MachineOperand &MO :
878 llvm::drop_begin(FaultingMI.operands(), OperandsBeginIdx))
879 if (auto Op = MCIL.LowerMachineOperand(&FaultingMI, MO); Op.isValid())
880 MI.addOperand(Op);
881
882 OutStreamer->AddComment("on-fault: " + HandlerLabel->getName());
883 OutStreamer->emitInstruction(MI, getSubtargetInfo());
884}
885
886void X86AsmPrinter::LowerFENTRY_CALL(const MachineInstr &MI,
887 X86MCInstLower &MCIL) {
888 bool Is64Bits = Subtarget->is64Bit();
889 MCContext &Ctx = OutStreamer->getContext();
890
891 if (MF->getFunction().hasFnAttribute("mrecord-mcount")) {
892 MCSymbol *DotSym = OutContext.createTempSymbol();
893 OutStreamer->pushSection();
894 OutStreamer->switchSection(
895 Ctx.getELFSection("__mcount_loc", ELF::SHT_PROGBITS, ELF::SHF_ALLOC));
896 OutStreamer->emitSymbolValue(DotSym, Is64Bits ? 8 : 4);
897 OutStreamer->popSection();
898 OutStreamer->emitLabel(DotSym);
899 }
900
901 if (MF->getFunction().hasFnAttribute("mnop-mcount")) {
902 // Insert a NOP stream which can be rewritten into a 5-byte CALL
903 // instruction at runtime.
904 emitX86Nops(*OutStreamer, 5, Subtarget);
905 return;
906 }
907
908 MCSymbol *fentry = Ctx.getOrCreateSymbol("__fentry__");
909 const MCSymbolRefExpr *Op = MCSymbolRefExpr::create(fentry, Ctx);
910
911 EmitAndCountInstruction(
912 MCInstBuilder(Is64Bits ? X86::CALL64pcrel32 : X86::CALLpcrel32)
913 .addExpr(Op));
914}
915
916void X86AsmPrinter::LowerKCFI_CHECK(const MachineInstr &MI) {
917 assert(std::next(MI.getIterator())->isCall() &&
918 "KCFI_CHECK not followed by a call instruction");
919
920 // Adjust the offset for patchable-function-prefix. X86InstrInfo::getNop()
921 // returns a 1-byte X86::NOOP, which means the offset is the same in
922 // bytes. This assumes that patchable-function-prefix is the same for all
923 // functions.
924 const MachineFunction &MF = *MI.getMF();
925 int64_t PrefixNops = MF.getFunction().getFnAttributeAsParsedInteger(
926 "patchable-function-prefix");
927
928 // KCFI allows indirect calls to any location that's preceded by a valid
929 // type identifier. To avoid encoding the full constant into an instruction,
930 // and thus emitting potential call target gadgets at each indirect call
931 // site, load a negated constant to a register and compare that to the
932 // expected value at the call target.
933 const Register AddrReg = MI.getOperand(0).getReg();
934 const uint32_t Type = MI.getOperand(1).getImm();
935 // The check is immediately before the call. If the call target is in R10,
936 // we can clobber R11 for the check instead.
937 unsigned TempReg = AddrReg == X86::R10 ? X86::R11D : X86::R10D;
938 EmitAndCountInstruction(
939 MCInstBuilder(X86::MOV32ri).addReg(TempReg).addImm(-MaskKCFIType(Type)));
940 EmitAndCountInstruction(MCInstBuilder(X86::ADD32rm)
941 .addReg(X86::NoRegister)
942 .addReg(TempReg)
943 .addReg(AddrReg)
944 .addImm(1)
945 .addReg(X86::NoRegister)
946 .addImm(-(PrefixNops + 4))
947 .addReg(X86::NoRegister));
948
949 MCSymbol *Pass = OutContext.createTempSymbol();
950 EmitAndCountInstruction(
951 MCInstBuilder(X86::JCC_1)
952 .addExpr(MCSymbolRefExpr::create(Pass, OutContext))
953 .addImm(X86::COND_E));
954
955 MCSymbol *Trap = OutContext.createTempSymbol();
956 OutStreamer->emitLabel(Trap);
957 EmitAndCountInstruction(MCInstBuilder(X86::TRAP));
958 emitKCFITrapEntry(MF, Trap);
959 OutStreamer->emitLabel(Pass);
960}
961
962void X86AsmPrinter::LowerASAN_CHECK_MEMACCESS(const MachineInstr &MI) {
963 // FIXME: Make this work on non-ELF.
964 if (!TM.getTargetTriple().isOSBinFormatELF()) {
965 report_fatal_error("llvm.asan.check.memaccess only supported on ELF");
966 return;
967 }
968
969 const auto &Reg = MI.getOperand(0).getReg();
970 ASanAccessInfo AccessInfo(MI.getOperand(1).getImm());
971
972 uint64_t ShadowBase;
973 int MappingScale;
974 bool OrShadowOffset;
976 TM.getTargetTriple(), 64, AccessInfo.CompileKernel,
977 &ShadowBase, &MappingScale, &OrShadowOffset);
978
979 StringRef Name = AccessInfo.IsWrite ? "store" : "load";
980 StringRef Op = OrShadowOffset ? "or" : "add";
981 std::string SymName = ("__asan_check_" + Name + "_" + Op + "_" +
982 Twine(1ULL << AccessInfo.AccessSizeIndex) + "_" +
983 TM.getMCRegisterInfo().getName(Reg.asMCReg()))
984 .str();
985 if (OrShadowOffset)
987 "OrShadowOffset is not supported with optimized callbacks");
988
989 EmitAndCountInstruction(
990 MCInstBuilder(X86::CALL64pcrel32)
992 OutContext.getOrCreateSymbol(SymName), OutContext)));
993}
994
995void X86AsmPrinter::LowerPATCHABLE_OP(const MachineInstr &MI,
996 X86MCInstLower &MCIL) {
997 // PATCHABLE_OP minsize
998
999 NoAutoPaddingScope NoPadScope(*OutStreamer);
1000
1001 auto NextMI = skipMetaInstructionsForward(std::next(MI.getIterator()),
1002 MI.getParent()->instr_end());
1003
1004 SmallString<256> Code;
1005 unsigned MinSize = MI.getOperand(0).getImm();
1006
1007 if (NextMI != MI.getParent()->end() && !NextMI->isInlineAsm()) {
1008 // Lower the next MachineInstr to find its byte size.
1009 // If the next instruction is inline assembly, we skip lowering it for now,
1010 // and assume we should always generate NOPs.
1011 MCInst MCI;
1012 MCIL.Lower(&*NextMI, MCI);
1013
1015 CodeEmitter->encodeInstruction(MCI, Code, Fixups, getSubtargetInfo());
1016 }
1017
1018 if (Code.size() < MinSize) {
1019 if (MinSize == 2 && Subtarget->is32Bit() &&
1020 Subtarget->isTargetWindowsMSVC() &&
1021 (Subtarget->getCPU().empty() || Subtarget->getCPU() == "pentium3")) {
1022 // For compatibility reasons, when targetting MSVC, it is important to
1023 // generate a 'legacy' NOP in the form of a 8B FF MOV EDI, EDI. Some tools
1024 // rely specifically on this pattern to be able to patch a function.
1025 // This is only for 32-bit targets, when using /arch:IA32 or /arch:SSE.
1026 OutStreamer->emitInstruction(
1027 MCInstBuilder(X86::MOV32rr_REV).addReg(X86::EDI).addReg(X86::EDI),
1028 *Subtarget);
1029 } else {
1030 unsigned NopSize = emitNop(*OutStreamer, MinSize, Subtarget);
1031 assert(NopSize == MinSize && "Could not implement MinSize!");
1032 (void)NopSize;
1033 }
1034 }
1035}
1036
1037// Lower a stackmap of the form:
1038// <id>, <shadowBytes>, ...
1039void X86AsmPrinter::LowerSTACKMAP(const MachineInstr &MI) {
1040 SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
1041
1042 auto &Ctx = OutStreamer->getContext();
1043 MCSymbol *MILabel = Ctx.createTempSymbol();
1044 OutStreamer->emitLabel(MILabel);
1045
1046 SM.recordStackMap(*MILabel, MI);
1047 unsigned NumShadowBytes = MI.getOperand(1).getImm();
1048 SMShadowTracker.reset(NumShadowBytes);
1049}
1050
1051// Lower a patchpoint of the form:
1052// [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
1053void X86AsmPrinter::LowerPATCHPOINT(const MachineInstr &MI,
1054 X86MCInstLower &MCIL) {
1055 assert(Subtarget->is64Bit() && "Patchpoint currently only supports X86-64");
1056
1057 SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
1058
1059 NoAutoPaddingScope NoPadScope(*OutStreamer);
1060
1061 auto &Ctx = OutStreamer->getContext();
1062 MCSymbol *MILabel = Ctx.createTempSymbol();
1063 OutStreamer->emitLabel(MILabel);
1064 SM.recordPatchPoint(*MILabel, MI);
1065
1066 PatchPointOpers opers(&MI);
1067 unsigned ScratchIdx = opers.getNextScratchIdx();
1068 unsigned EncodedBytes = 0;
1069 const MachineOperand &CalleeMO = opers.getCallTarget();
1070
1071 // Check for null target. If target is non-null (i.e. is non-zero or is
1072 // symbolic) then emit a call.
1073 if (!(CalleeMO.isImm() && !CalleeMO.getImm())) {
1074 MCOperand CalleeMCOp;
1075 switch (CalleeMO.getType()) {
1076 default:
1077 /// FIXME: Add a verifier check for bad callee types.
1078 llvm_unreachable("Unrecognized callee operand type.");
1080 if (CalleeMO.getImm())
1081 CalleeMCOp = MCOperand::createImm(CalleeMO.getImm());
1082 break;
1085 CalleeMCOp = MCIL.LowerSymbolOperand(CalleeMO,
1086 MCIL.GetSymbolFromOperand(CalleeMO));
1087 break;
1088 }
1089
1090 // Emit MOV to materialize the target address and the CALL to target.
1091 // This is encoded with 12-13 bytes, depending on which register is used.
1092 Register ScratchReg = MI.getOperand(ScratchIdx).getReg();
1093 if (X86II::isX86_64ExtendedReg(ScratchReg))
1094 EncodedBytes = 13;
1095 else
1096 EncodedBytes = 12;
1097
1098 EmitAndCountInstruction(
1099 MCInstBuilder(X86::MOV64ri).addReg(ScratchReg).addOperand(CalleeMCOp));
1100 // FIXME: Add retpoline support and remove this.
1101 if (Subtarget->useIndirectThunkCalls())
1103 "Lowering patchpoint with thunks not yet implemented.");
1104 EmitAndCountInstruction(MCInstBuilder(X86::CALL64r).addReg(ScratchReg));
1105 }
1106
1107 // Emit padding.
1108 unsigned NumBytes = opers.getNumPatchBytes();
1109 assert(NumBytes >= EncodedBytes &&
1110 "Patchpoint can't request size less than the length of a call.");
1111
1112 emitX86Nops(*OutStreamer, NumBytes - EncodedBytes, Subtarget);
1113}
1114
1115void X86AsmPrinter::LowerPATCHABLE_EVENT_CALL(const MachineInstr &MI,
1116 X86MCInstLower &MCIL) {
1117 assert(Subtarget->is64Bit() && "XRay custom events only supports X86-64");
1118
1119 NoAutoPaddingScope NoPadScope(*OutStreamer);
1120
1121 // We want to emit the following pattern, which follows the x86 calling
1122 // convention to prepare for the trampoline call to be patched in.
1123 //
1124 // .p2align 1, ...
1125 // .Lxray_event_sled_N:
1126 // jmp +N // jump across the instrumentation sled
1127 // ... // set up arguments in register
1128 // callq __xray_CustomEvent@plt // force dependency to symbol
1129 // ...
1130 // <jump here>
1131 //
1132 // After patching, it would look something like:
1133 //
1134 // nopw (2-byte nop)
1135 // ...
1136 // callq __xrayCustomEvent // already lowered
1137 // ...
1138 //
1139 // ---
1140 // First we emit the label and the jump.
1141 auto CurSled = OutContext.createTempSymbol("xray_event_sled_", true);
1142 OutStreamer->AddComment("# XRay Custom Event Log");
1143 OutStreamer->emitCodeAlignment(Align(2), getSubtargetInfo());
1144 OutStreamer->emitLabel(CurSled);
1145
1146 // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1147 // an operand (computed as an offset from the jmp instruction).
1148 // FIXME: Find another less hacky way do force the relative jump.
1149 OutStreamer->emitBinaryData("\xeb\x0f");
1150
1151 // The default C calling convention will place two arguments into %rcx and
1152 // %rdx -- so we only work with those.
1153 const Register DestRegs[] = {X86::RDI, X86::RSI};
1154 bool UsedMask[] = {false, false};
1155 // Filled out in loop.
1156 Register SrcRegs[] = {0, 0};
1157
1158 // Then we put the operands in the %rdi and %rsi registers. We spill the
1159 // values in the register before we clobber them, and mark them as used in
1160 // UsedMask. In case the arguments are already in the correct register, we use
1161 // emit nops appropriately sized to keep the sled the same size in every
1162 // situation.
1163 for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1164 if (auto Op = MCIL.LowerMachineOperand(&MI, MI.getOperand(I));
1165 Op.isValid()) {
1166 assert(Op.isReg() && "Only support arguments in registers");
1167 SrcRegs[I] = getX86SubSuperRegister(Op.getReg(), 64);
1168 assert(SrcRegs[I].isValid() && "Invalid operand");
1169 if (SrcRegs[I] != DestRegs[I]) {
1170 UsedMask[I] = true;
1171 EmitAndCountInstruction(
1172 MCInstBuilder(X86::PUSH64r).addReg(DestRegs[I]));
1173 } else {
1174 emitX86Nops(*OutStreamer, 4, Subtarget);
1175 }
1176 }
1177
1178 // Now that the register values are stashed, mov arguments into place.
1179 // FIXME: This doesn't work if one of the later SrcRegs is equal to an
1180 // earlier DestReg. We will have already overwritten over the register before
1181 // we can copy from it.
1182 for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1183 if (SrcRegs[I] != DestRegs[I])
1184 EmitAndCountInstruction(
1185 MCInstBuilder(X86::MOV64rr).addReg(DestRegs[I]).addReg(SrcRegs[I]));
1186
1187 // We emit a hard dependency on the __xray_CustomEvent symbol, which is the
1188 // name of the trampoline to be implemented by the XRay runtime.
1189 auto TSym = OutContext.getOrCreateSymbol("__xray_CustomEvent");
1190 MachineOperand TOp = MachineOperand::CreateMCSymbol(TSym);
1191 if (isPositionIndependent())
1193
1194 // Emit the call instruction.
1195 EmitAndCountInstruction(MCInstBuilder(X86::CALL64pcrel32)
1196 .addOperand(MCIL.LowerSymbolOperand(TOp, TSym)));
1197
1198 // Restore caller-saved and used registers.
1199 for (unsigned I = sizeof UsedMask; I-- > 0;)
1200 if (UsedMask[I])
1201 EmitAndCountInstruction(MCInstBuilder(X86::POP64r).addReg(DestRegs[I]));
1202 else
1203 emitX86Nops(*OutStreamer, 1, Subtarget);
1204
1205 OutStreamer->AddComment("xray custom event end.");
1206
1207 // Record the sled version. Version 0 of this sled was spelled differently, so
1208 // we let the runtime handle the different offsets we're using. Version 2
1209 // changed the absolute address to a PC-relative address.
1210 recordSled(CurSled, MI, SledKind::CUSTOM_EVENT, 2);
1211}
1212
1213void X86AsmPrinter::LowerPATCHABLE_TYPED_EVENT_CALL(const MachineInstr &MI,
1214 X86MCInstLower &MCIL) {
1215 assert(Subtarget->is64Bit() && "XRay typed events only supports X86-64");
1216
1217 NoAutoPaddingScope NoPadScope(*OutStreamer);
1218
1219 // We want to emit the following pattern, which follows the x86 calling
1220 // convention to prepare for the trampoline call to be patched in.
1221 //
1222 // .p2align 1, ...
1223 // .Lxray_event_sled_N:
1224 // jmp +N // jump across the instrumentation sled
1225 // ... // set up arguments in register
1226 // callq __xray_TypedEvent@plt // force dependency to symbol
1227 // ...
1228 // <jump here>
1229 //
1230 // After patching, it would look something like:
1231 //
1232 // nopw (2-byte nop)
1233 // ...
1234 // callq __xrayTypedEvent // already lowered
1235 // ...
1236 //
1237 // ---
1238 // First we emit the label and the jump.
1239 auto CurSled = OutContext.createTempSymbol("xray_typed_event_sled_", true);
1240 OutStreamer->AddComment("# XRay Typed Event Log");
1241 OutStreamer->emitCodeAlignment(Align(2), getSubtargetInfo());
1242 OutStreamer->emitLabel(CurSled);
1243
1244 // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1245 // an operand (computed as an offset from the jmp instruction).
1246 // FIXME: Find another less hacky way do force the relative jump.
1247 OutStreamer->emitBinaryData("\xeb\x14");
1248
1249 // An x86-64 convention may place three arguments into %rcx, %rdx, and R8,
1250 // so we'll work with those. Or we may be called via SystemV, in which case
1251 // we don't have to do any translation.
1252 const Register DestRegs[] = {X86::RDI, X86::RSI, X86::RDX};
1253 bool UsedMask[] = {false, false, false};
1254
1255 // Will fill out src regs in the loop.
1256 Register SrcRegs[] = {0, 0, 0};
1257
1258 // Then we put the operands in the SystemV registers. We spill the values in
1259 // the registers before we clobber them, and mark them as used in UsedMask.
1260 // In case the arguments are already in the correct register, we emit nops
1261 // appropriately sized to keep the sled the same size in every situation.
1262 for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1263 if (auto Op = MCIL.LowerMachineOperand(&MI, MI.getOperand(I));
1264 Op.isValid()) {
1265 // TODO: Is register only support adequate?
1266 assert(Op.isReg() && "Only supports arguments in registers");
1267 SrcRegs[I] = getX86SubSuperRegister(Op.getReg(), 64);
1268 assert(SrcRegs[I].isValid() && "Invalid operand");
1269 if (SrcRegs[I] != DestRegs[I]) {
1270 UsedMask[I] = true;
1271 EmitAndCountInstruction(
1272 MCInstBuilder(X86::PUSH64r).addReg(DestRegs[I]));
1273 } else {
1274 emitX86Nops(*OutStreamer, 4, Subtarget);
1275 }
1276 }
1277
1278 // In the above loop we only stash all of the destination registers or emit
1279 // nops if the arguments are already in the right place. Doing the actually
1280 // moving is postponed until after all the registers are stashed so nothing
1281 // is clobbers. We've already added nops to account for the size of mov and
1282 // push if the register is in the right place, so we only have to worry about
1283 // emitting movs.
1284 // FIXME: This doesn't work if one of the later SrcRegs is equal to an
1285 // earlier DestReg. We will have already overwritten over the register before
1286 // we can copy from it.
1287 for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1288 if (UsedMask[I])
1289 EmitAndCountInstruction(
1290 MCInstBuilder(X86::MOV64rr).addReg(DestRegs[I]).addReg(SrcRegs[I]));
1291
1292 // We emit a hard dependency on the __xray_TypedEvent symbol, which is the
1293 // name of the trampoline to be implemented by the XRay runtime.
1294 auto TSym = OutContext.getOrCreateSymbol("__xray_TypedEvent");
1295 MachineOperand TOp = MachineOperand::CreateMCSymbol(TSym);
1296 if (isPositionIndependent())
1298
1299 // Emit the call instruction.
1300 EmitAndCountInstruction(MCInstBuilder(X86::CALL64pcrel32)
1301 .addOperand(MCIL.LowerSymbolOperand(TOp, TSym)));
1302
1303 // Restore caller-saved and used registers.
1304 for (unsigned I = sizeof UsedMask; I-- > 0;)
1305 if (UsedMask[I])
1306 EmitAndCountInstruction(MCInstBuilder(X86::POP64r).addReg(DestRegs[I]));
1307 else
1308 emitX86Nops(*OutStreamer, 1, Subtarget);
1309
1310 OutStreamer->AddComment("xray typed event end.");
1311
1312 // Record the sled version.
1313 recordSled(CurSled, MI, SledKind::TYPED_EVENT, 2);
1314}
1315
1316void X86AsmPrinter::LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr &MI,
1317 X86MCInstLower &MCIL) {
1318
1319 NoAutoPaddingScope NoPadScope(*OutStreamer);
1320
1321 const Function &F = MF->getFunction();
1322 if (F.hasFnAttribute("patchable-function-entry")) {
1323 unsigned Num = F.getFnAttributeAsParsedInteger("patchable-function-entry");
1324 emitX86Nops(*OutStreamer, Num, Subtarget);
1325 return;
1326 }
1327 // We want to emit the following pattern:
1328 //
1329 // .p2align 1, ...
1330 // .Lxray_sled_N:
1331 // jmp .tmpN
1332 // # 9 bytes worth of noops
1333 //
1334 // We need the 9 bytes because at runtime, we'd be patching over the full 11
1335 // bytes with the following pattern:
1336 //
1337 // mov %r10, <function id, 32-bit> // 6 bytes
1338 // call <relative offset, 32-bits> // 5 bytes
1339 //
1340 auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1341 OutStreamer->emitCodeAlignment(Align(2), getSubtargetInfo());
1342 OutStreamer->emitLabel(CurSled);
1343
1344 // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1345 // an operand (computed as an offset from the jmp instruction).
1346 // FIXME: Find another less hacky way do force the relative jump.
1347 OutStreamer->emitBytes("\xeb\x09");
1348 emitX86Nops(*OutStreamer, 9, Subtarget);
1349 recordSled(CurSled, MI, SledKind::FUNCTION_ENTER, 2);
1350}
1351
1352void X86AsmPrinter::LowerPATCHABLE_RET(const MachineInstr &MI,
1353 X86MCInstLower &MCIL) {
1354 NoAutoPaddingScope NoPadScope(*OutStreamer);
1355
1356 // Since PATCHABLE_RET takes the opcode of the return statement as an
1357 // argument, we use that to emit the correct form of the RET that we want.
1358 // i.e. when we see this:
1359 //
1360 // PATCHABLE_RET X86::RET ...
1361 //
1362 // We should emit the RET followed by sleds.
1363 //
1364 // .p2align 1, ...
1365 // .Lxray_sled_N:
1366 // ret # or equivalent instruction
1367 // # 10 bytes worth of noops
1368 //
1369 // This just makes sure that the alignment for the next instruction is 2.
1370 auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1371 OutStreamer->emitCodeAlignment(Align(2), getSubtargetInfo());
1372 OutStreamer->emitLabel(CurSled);
1373 unsigned OpCode = MI.getOperand(0).getImm();
1374 MCInst Ret;
1375 Ret.setOpcode(OpCode);
1376 for (auto &MO : drop_begin(MI.operands()))
1377 if (auto Op = MCIL.LowerMachineOperand(&MI, MO); Op.isValid())
1378 Ret.addOperand(Op);
1379 OutStreamer->emitInstruction(Ret, getSubtargetInfo());
1380 emitX86Nops(*OutStreamer, 10, Subtarget);
1381 recordSled(CurSled, MI, SledKind::FUNCTION_EXIT, 2);
1382}
1383
1384void X86AsmPrinter::LowerPATCHABLE_TAIL_CALL(const MachineInstr &MI,
1385 X86MCInstLower &MCIL) {
1386 MCInst TC;
1387 TC.setOpcode(convertTailJumpOpcode(MI.getOperand(0).getImm()));
1388 // Drop the tail jump opcode.
1389 auto TCOperands = drop_begin(MI.operands());
1390 bool IsConditional = TC.getOpcode() == X86::JCC_1;
1391 MCSymbol *FallthroughLabel;
1392 if (IsConditional) {
1393 // Rewrite:
1394 // je target
1395 //
1396 // To:
1397 // jne .fallthrough
1398 // .p2align 1, ...
1399 // .Lxray_sled_N:
1400 // SLED_CODE
1401 // jmp target
1402 // .fallthrough:
1403 FallthroughLabel = OutContext.createTempSymbol();
1404 EmitToStreamer(
1405 *OutStreamer,
1406 MCInstBuilder(X86::JCC_1)
1407 .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext))
1409 static_cast<X86::CondCode>(MI.getOperand(2).getImm()))));
1410 TC.setOpcode(X86::JMP_1);
1411 // Drop the condition code.
1412 TCOperands = drop_end(TCOperands);
1413 }
1414
1415 NoAutoPaddingScope NoPadScope(*OutStreamer);
1416
1417 // Like PATCHABLE_RET, we have the actual instruction in the operands to this
1418 // instruction so we lower that particular instruction and its operands.
1419 // Unlike PATCHABLE_RET though, we put the sled before the JMP, much like how
1420 // we do it for PATCHABLE_FUNCTION_ENTER. The sled should be very similar to
1421 // the PATCHABLE_FUNCTION_ENTER case, followed by the lowering of the actual
1422 // tail call much like how we have it in PATCHABLE_RET.
1423 auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1424 OutStreamer->emitCodeAlignment(Align(2), getSubtargetInfo());
1425 OutStreamer->emitLabel(CurSled);
1426 auto Target = OutContext.createTempSymbol();
1427
1428 // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1429 // an operand (computed as an offset from the jmp instruction).
1430 // FIXME: Find another less hacky way do force the relative jump.
1431 OutStreamer->emitBytes("\xeb\x09");
1432 emitX86Nops(*OutStreamer, 9, Subtarget);
1433 OutStreamer->emitLabel(Target);
1434 recordSled(CurSled, MI, SledKind::TAIL_CALL, 2);
1435
1436 // Before emitting the instruction, add a comment to indicate that this is
1437 // indeed a tail call.
1438 OutStreamer->AddComment("TAILCALL");
1439 for (auto &MO : TCOperands)
1440 if (auto Op = MCIL.LowerMachineOperand(&MI, MO); Op.isValid())
1441 TC.addOperand(Op);
1442 OutStreamer->emitInstruction(TC, getSubtargetInfo());
1443
1444 if (IsConditional)
1445 OutStreamer->emitLabel(FallthroughLabel);
1446}
1447
1448static unsigned getSrcIdx(const MachineInstr* MI, unsigned SrcIdx) {
1449 if (X86II::isKMasked(MI->getDesc().TSFlags)) {
1450 // Skip mask operand.
1451 ++SrcIdx;
1452 if (X86II::isKMergeMasked(MI->getDesc().TSFlags)) {
1453 // Skip passthru operand.
1454 ++SrcIdx;
1455 }
1456 }
1457 return SrcIdx;
1458}
1459
1461 unsigned SrcOpIdx) {
1462 const MachineOperand &DstOp = MI->getOperand(0);
1464
1465 // Handle AVX512 MASK/MASXZ write mask comments.
1466 // MASK: zmmX {%kY}
1467 // MASKZ: zmmX {%kY} {z}
1468 if (X86II::isKMasked(MI->getDesc().TSFlags)) {
1469 const MachineOperand &WriteMaskOp = MI->getOperand(SrcOpIdx - 1);
1471 CS << " {%" << Mask << "}";
1472 if (!X86II::isKMergeMasked(MI->getDesc().TSFlags)) {
1473 CS << " {z}";
1474 }
1475 }
1476}
1477
1478static void printShuffleMask(raw_ostream &CS, StringRef Src1Name,
1479 StringRef Src2Name, ArrayRef<int> Mask) {
1480 // One source operand, fix the mask to print all elements in one span.
1481 SmallVector<int, 8> ShuffleMask(Mask);
1482 if (Src1Name == Src2Name)
1483 for (int i = 0, e = ShuffleMask.size(); i != e; ++i)
1484 if (ShuffleMask[i] >= e)
1485 ShuffleMask[i] -= e;
1486
1487 for (int i = 0, e = ShuffleMask.size(); i != e; ++i) {
1488 if (i != 0)
1489 CS << ",";
1490 if (ShuffleMask[i] == SM_SentinelZero) {
1491 CS << "zero";
1492 continue;
1493 }
1494
1495 // Otherwise, it must come from src1 or src2. Print the span of elements
1496 // that comes from this src.
1497 bool isSrc1 = ShuffleMask[i] < (int)e;
1498 CS << (isSrc1 ? Src1Name : Src2Name) << '[';
1499
1500 bool IsFirst = true;
1501 while (i != e && ShuffleMask[i] != SM_SentinelZero &&
1502 (ShuffleMask[i] < (int)e) == isSrc1) {
1503 if (!IsFirst)
1504 CS << ',';
1505 else
1506 IsFirst = false;
1507 if (ShuffleMask[i] == SM_SentinelUndef)
1508 CS << "u";
1509 else
1510 CS << ShuffleMask[i] % (int)e;
1511 ++i;
1512 }
1513 CS << ']';
1514 --i; // For loop increments element #.
1515 }
1516}
1517
1518static std::string getShuffleComment(const MachineInstr *MI, unsigned SrcOp1Idx,
1519 unsigned SrcOp2Idx, ArrayRef<int> Mask) {
1520 std::string Comment;
1521
1522 const MachineOperand &SrcOp1 = MI->getOperand(SrcOp1Idx);
1523 const MachineOperand &SrcOp2 = MI->getOperand(SrcOp2Idx);
1524 StringRef Src1Name = SrcOp1.isReg()
1526 : "mem";
1527 StringRef Src2Name = SrcOp2.isReg()
1529 : "mem";
1530
1531 raw_string_ostream CS(Comment);
1532 printDstRegisterName(CS, MI, SrcOp1Idx);
1533 CS << " = ";
1534 printShuffleMask(CS, Src1Name, Src2Name, Mask);
1535
1536 return Comment;
1537}
1538
1539static void printConstant(const APInt &Val, raw_ostream &CS,
1540 bool PrintZero = false) {
1541 if (Val.getBitWidth() <= 64) {
1542 CS << (PrintZero ? 0ULL : Val.getZExtValue());
1543 } else {
1544 // print multi-word constant as (w0,w1)
1545 CS << "(";
1546 for (int i = 0, N = Val.getNumWords(); i < N; ++i) {
1547 if (i > 0)
1548 CS << ",";
1549 CS << (PrintZero ? 0ULL : Val.getRawData()[i]);
1550 }
1551 CS << ")";
1552 }
1553}
1554
1555static void printConstant(const APFloat &Flt, raw_ostream &CS,
1556 bool PrintZero = false) {
1557 SmallString<32> Str;
1558 // Force scientific notation to distinguish from integers.
1559 if (PrintZero)
1560 APFloat::getZero(Flt.getSemantics()).toString(Str, 0, 0);
1561 else
1562 Flt.toString(Str, 0, 0);
1563 CS << Str;
1564}
1565
1566static void printConstant(const Constant *COp, unsigned BitWidth,
1567 raw_ostream &CS, bool PrintZero = false) {
1568 if (isa<UndefValue>(COp)) {
1569 CS << "u";
1570 } else if (auto *CI = dyn_cast<ConstantInt>(COp)) {
1571 if (auto VTy = dyn_cast<FixedVectorType>(CI->getType())) {
1572 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1573 if (I != 0)
1574 CS << ',';
1575 printConstant(CI->getValue(), CS, PrintZero);
1576 }
1577 } else
1578 printConstant(CI->getValue(), CS, PrintZero);
1579 } else if (auto *CF = dyn_cast<ConstantFP>(COp)) {
1580 if (auto VTy = dyn_cast<FixedVectorType>(CF->getType())) {
1581 unsigned EltBits = VTy->getScalarSizeInBits();
1582 unsigned E = std::min(BitWidth / EltBits, VTy->getNumElements());
1583 if ((BitWidth % EltBits) == 0) {
1584 for (unsigned I = 0; I != E; ++I) {
1585 if (I != 0)
1586 CS << ",";
1587 printConstant(CF->getValueAPF(), CS, PrintZero);
1588 }
1589 } else {
1590 CS << "?";
1591 }
1592 } else
1593 printConstant(CF->getValueAPF(), CS, PrintZero);
1594 } else if (auto *CDS = dyn_cast<ConstantDataSequential>(COp)) {
1595 Type *EltTy = CDS->getElementType();
1596 bool IsInteger = EltTy->isIntegerTy();
1597 bool IsFP = EltTy->isHalfTy() || EltTy->isFloatTy() || EltTy->isDoubleTy();
1598 unsigned EltBits = EltTy->getPrimitiveSizeInBits();
1599 unsigned E = std::min(BitWidth / EltBits, (unsigned)CDS->getNumElements());
1600 if ((BitWidth % EltBits) == 0) {
1601 for (unsigned I = 0; I != E; ++I) {
1602 if (I != 0)
1603 CS << ",";
1604 if (IsInteger)
1605 printConstant(CDS->getElementAsAPInt(I), CS, PrintZero);
1606 else if (IsFP)
1607 printConstant(CDS->getElementAsAPFloat(I), CS, PrintZero);
1608 else
1609 CS << "?";
1610 }
1611 } else {
1612 CS << "?";
1613 }
1614 } else if (auto *CV = dyn_cast<ConstantVector>(COp)) {
1615 unsigned EltBits = CV->getType()->getScalarSizeInBits();
1616 unsigned E = std::min(BitWidth / EltBits, CV->getNumOperands());
1617 if ((BitWidth % EltBits) == 0) {
1618 for (unsigned I = 0; I != E; ++I) {
1619 if (I != 0)
1620 CS << ",";
1621 printConstant(CV->getOperand(I), EltBits, CS, PrintZero);
1622 }
1623 } else {
1624 CS << "?";
1625 }
1626 } else {
1627 CS << "?";
1628 }
1629}
1630
1631static void printZeroUpperMove(const MachineInstr *MI, MCStreamer &OutStreamer,
1632 int SclWidth, int VecWidth,
1633 const char *ShuffleComment) {
1634 unsigned SrcIdx = getSrcIdx(MI, 1);
1635
1636 std::string Comment;
1637 raw_string_ostream CS(Comment);
1638 printDstRegisterName(CS, MI, SrcIdx);
1639 CS << " = ";
1640
1641 if (auto *C = X86::getConstantFromPool(*MI, SrcIdx)) {
1642 CS << "[";
1643 printConstant(C, SclWidth, CS);
1644 for (int I = 1, E = VecWidth / SclWidth; I < E; ++I) {
1645 CS << ",";
1646 printConstant(C, SclWidth, CS, true);
1647 }
1648 CS << "]";
1649 OutStreamer.AddComment(CS.str());
1650 return; // early-out
1651 }
1652
1653 // We didn't find a constant load, fallback to a shuffle mask decode.
1654 CS << ShuffleComment;
1655 OutStreamer.AddComment(CS.str());
1656}
1657
1658static void printBroadcast(const MachineInstr *MI, MCStreamer &OutStreamer,
1659 int Repeats, int BitWidth) {
1660 unsigned SrcIdx = getSrcIdx(MI, 1);
1661 if (auto *C = X86::getConstantFromPool(*MI, SrcIdx)) {
1662 std::string Comment;
1663 raw_string_ostream CS(Comment);
1664 printDstRegisterName(CS, MI, SrcIdx);
1665 CS << " = [";
1666 for (int l = 0; l != Repeats; ++l) {
1667 if (l != 0)
1668 CS << ",";
1669 printConstant(C, BitWidth, CS);
1670 }
1671 CS << "]";
1672 OutStreamer.AddComment(CS.str());
1673 }
1674}
1675
1676static void addConstantComment(const MachineInstr *MI, MCStreamer &OutStreamer,
1677 unsigned OpNo, int BitWidth, int Repeats = 1) {
1678 if (auto *C = X86::getConstantFromPool(*MI, OpNo)) {
1679 std::string Comment;
1680 raw_string_ostream CS(Comment);
1681 CS << "[";
1682 for (int I = 0; I != Repeats; ++I) {
1683 if (I != 0)
1684 CS << ",";
1685 printConstant(C, BitWidth, CS);
1686 }
1687 CS << "]";
1688 OutStreamer.AddComment(CS.str());
1689 }
1690}
1691
1692static bool printExtend(const MachineInstr *MI, MCStreamer &OutStreamer,
1693 int SrcEltBits, int DstEltBits, bool IsSext) {
1694 unsigned SrcIdx = getSrcIdx(MI, 1);
1695 auto *C = X86::getConstantFromPool(*MI, SrcIdx);
1696 if (C && C->getType()->getScalarSizeInBits() == unsigned(SrcEltBits)) {
1697 if (auto *CDS = dyn_cast<ConstantDataSequential>(C)) {
1698 int NumElts = CDS->getNumElements();
1699 std::string Comment;
1700 raw_string_ostream CS(Comment);
1701 printDstRegisterName(CS, MI, SrcIdx);
1702 CS << " = [";
1703 for (int i = 0; i != NumElts; ++i) {
1704 if (i != 0)
1705 CS << ",";
1706 if (CDS->getElementType()->isIntegerTy()) {
1707 APInt Elt = CDS->getElementAsAPInt(i);
1708 Elt = IsSext ? Elt.sext(DstEltBits) : Elt.zext(DstEltBits);
1709 printConstant(Elt, CS);
1710 } else
1711 CS << "?";
1712 }
1713 CS << "]";
1714 OutStreamer.AddComment(CS.str());
1715 return true;
1716 }
1717 }
1718
1719 return false;
1720}
1721static void printSignExtend(const MachineInstr *MI, MCStreamer &OutStreamer,
1722 int SrcEltBits, int DstEltBits) {
1723 printExtend(MI, OutStreamer, SrcEltBits, DstEltBits, true);
1724}
1725static void printZeroExtend(const MachineInstr *MI, MCStreamer &OutStreamer,
1726 int SrcEltBits, int DstEltBits) {
1727 if (printExtend(MI, OutStreamer, SrcEltBits, DstEltBits, false))
1728 return;
1729
1730 // We didn't find a constant load, fallback to a shuffle mask decode.
1731 std::string Comment;
1732 raw_string_ostream CS(Comment);
1734 CS << " = ";
1735
1736 SmallVector<int> Mask;
1737 unsigned Width = X86::getVectorRegisterWidth(MI->getDesc().operands()[0]);
1738 assert((Width % DstEltBits) == 0 && (DstEltBits % SrcEltBits) == 0 &&
1739 "Illegal extension ratio");
1740 DecodeZeroExtendMask(SrcEltBits, DstEltBits, Width / DstEltBits, false, Mask);
1741 printShuffleMask(CS, "mem", "", Mask);
1742
1743 OutStreamer.AddComment(CS.str());
1744}
1745
1746void X86AsmPrinter::EmitSEHInstruction(const MachineInstr *MI) {
1747 assert(MF->hasWinCFI() && "SEH_ instruction in function without WinCFI?");
1748 assert(getSubtarget().isOSWindowsOrUEFI() &&
1749 "SEH_ instruction Windows and UEFI only");
1750
1751 // Use the .cv_fpo directives if we're emitting CodeView on 32-bit x86.
1752 if (EmitFPOData) {
1753 X86TargetStreamer *XTS =
1754 static_cast<X86TargetStreamer *>(OutStreamer->getTargetStreamer());
1755 switch (MI->getOpcode()) {
1756 case X86::SEH_PushReg:
1757 XTS->emitFPOPushReg(MI->getOperand(0).getImm());
1758 break;
1759 case X86::SEH_StackAlloc:
1760 XTS->emitFPOStackAlloc(MI->getOperand(0).getImm());
1761 break;
1762 case X86::SEH_StackAlign:
1763 XTS->emitFPOStackAlign(MI->getOperand(0).getImm());
1764 break;
1765 case X86::SEH_SetFrame:
1766 assert(MI->getOperand(1).getImm() == 0 &&
1767 ".cv_fpo_setframe takes no offset");
1768 XTS->emitFPOSetFrame(MI->getOperand(0).getImm());
1769 break;
1770 case X86::SEH_EndPrologue:
1771 XTS->emitFPOEndPrologue();
1772 break;
1773 case X86::SEH_SaveReg:
1774 case X86::SEH_SaveXMM:
1775 case X86::SEH_PushFrame:
1776 case X86::SEH_Push2Regs:
1777 llvm_unreachable("SEH_ directive incompatible with FPO");
1778 break;
1779 default:
1780 llvm_unreachable("expected SEH_ instruction");
1781 }
1782 return;
1783 }
1784
1785 // Otherwise, use the .seh_ directives for all other Windows platforms.
1786 switch (MI->getOpcode()) {
1787 case X86::SEH_PushReg:
1788 OutStreamer->emitWinCFIPushReg(MI->getOperand(0).getImm());
1789 break;
1790
1791 case X86::SEH_Push2Regs:
1792 OutStreamer->emitWinCFIPush2Regs(MI->getOperand(0).getImm(),
1793 MI->getOperand(1).getImm());
1794 break;
1795
1796 case X86::SEH_SaveReg:
1797 OutStreamer->emitWinCFISaveReg(MI->getOperand(0).getImm(),
1798 MI->getOperand(1).getImm());
1799 break;
1800
1801 case X86::SEH_SaveXMM:
1802 OutStreamer->emitWinCFISaveXMM(MI->getOperand(0).getImm(),
1803 MI->getOperand(1).getImm());
1804 break;
1805
1806 case X86::SEH_StackAlloc:
1807 OutStreamer->emitWinCFIAllocStack(MI->getOperand(0).getImm());
1808 break;
1809
1810 case X86::SEH_SetFrame:
1811 OutStreamer->emitWinCFISetFrame(MI->getOperand(0).getImm(),
1812 MI->getOperand(1).getImm());
1813 break;
1814
1815 case X86::SEH_PushFrame:
1816 OutStreamer->emitWinCFIPushFrame(MI->getOperand(0).getImm());
1817 break;
1818
1819 case X86::SEH_EndPrologue:
1820 OutStreamer->emitWinCFIEndProlog();
1821 break;
1822
1823 case X86::SEH_BeginEpilogue:
1824 OutStreamer->emitWinCFIBeginEpilogue();
1825 break;
1826
1827 case X86::SEH_EndEpilogue:
1828 OutStreamer->emitWinCFIEndEpilogue();
1829 break;
1830
1831 case X86::SEH_UnwindV2Start:
1832 OutStreamer->emitWinCFIUnwindV2Start();
1833 break;
1834
1835 case X86::SEH_UnwindVersion:
1836 OutStreamer->emitWinCFIUnwindVersion(MI->getOperand(0).getImm());
1837 break;
1838
1839 default:
1840 llvm_unreachable("expected SEH_ instruction");
1841 }
1842}
1843
1845 MCStreamer &OutStreamer) {
1846 switch (MI->getOpcode()) {
1847 // Lower PSHUFB and VPERMILP normally but add a comment if we can find
1848 // a constant shuffle mask. We won't be able to do this at the MC layer
1849 // because the mask isn't an immediate.
1850 case X86::PSHUFBrm:
1851 case X86::VPSHUFBrm:
1852 case X86::VPSHUFBYrm:
1853 case X86::VPSHUFBZ128rm:
1854 case X86::VPSHUFBZ128rmk:
1855 case X86::VPSHUFBZ128rmkz:
1856 case X86::VPSHUFBZ256rm:
1857 case X86::VPSHUFBZ256rmk:
1858 case X86::VPSHUFBZ256rmkz:
1859 case X86::VPSHUFBZrm:
1860 case X86::VPSHUFBZrmk:
1861 case X86::VPSHUFBZrmkz: {
1862 unsigned SrcIdx = getSrcIdx(MI, 1);
1863 if (auto *C = X86::getConstantFromPool(*MI, SrcIdx + 1)) {
1864 unsigned Width = X86::getVectorRegisterWidth(MI->getDesc().operands()[0]);
1866 DecodePSHUFBMask(C, Width, Mask);
1867 if (!Mask.empty())
1868 OutStreamer.AddComment(getShuffleComment(MI, SrcIdx, SrcIdx, Mask));
1869 }
1870 break;
1871 }
1872
1873 case X86::VPERMILPSrm:
1874 case X86::VPERMILPSYrm:
1875 case X86::VPERMILPSZ128rm:
1876 case X86::VPERMILPSZ128rmk:
1877 case X86::VPERMILPSZ128rmkz:
1878 case X86::VPERMILPSZ256rm:
1879 case X86::VPERMILPSZ256rmk:
1880 case X86::VPERMILPSZ256rmkz:
1881 case X86::VPERMILPSZrm:
1882 case X86::VPERMILPSZrmk:
1883 case X86::VPERMILPSZrmkz: {
1884 unsigned SrcIdx = getSrcIdx(MI, 1);
1885 if (auto *C = X86::getConstantFromPool(*MI, SrcIdx + 1)) {
1886 unsigned Width = X86::getVectorRegisterWidth(MI->getDesc().operands()[0]);
1888 DecodeVPERMILPMask(C, 32, Width, Mask);
1889 if (!Mask.empty())
1890 OutStreamer.AddComment(getShuffleComment(MI, SrcIdx, SrcIdx, Mask));
1891 }
1892 break;
1893 }
1894 case X86::VPERMILPDrm:
1895 case X86::VPERMILPDYrm:
1896 case X86::VPERMILPDZ128rm:
1897 case X86::VPERMILPDZ128rmk:
1898 case X86::VPERMILPDZ128rmkz:
1899 case X86::VPERMILPDZ256rm:
1900 case X86::VPERMILPDZ256rmk:
1901 case X86::VPERMILPDZ256rmkz:
1902 case X86::VPERMILPDZrm:
1903 case X86::VPERMILPDZrmk:
1904 case X86::VPERMILPDZrmkz: {
1905 unsigned SrcIdx = getSrcIdx(MI, 1);
1906 if (auto *C = X86::getConstantFromPool(*MI, SrcIdx + 1)) {
1907 unsigned Width = X86::getVectorRegisterWidth(MI->getDesc().operands()[0]);
1909 DecodeVPERMILPMask(C, 64, Width, Mask);
1910 if (!Mask.empty())
1911 OutStreamer.AddComment(getShuffleComment(MI, SrcIdx, SrcIdx, Mask));
1912 }
1913 break;
1914 }
1915
1916 case X86::VPERMIL2PDrm:
1917 case X86::VPERMIL2PSrm:
1918 case X86::VPERMIL2PDYrm:
1919 case X86::VPERMIL2PSYrm: {
1920 assert(MI->getNumOperands() >= (3 + X86::AddrNumOperands + 1) &&
1921 "Unexpected number of operands!");
1922
1923 const MachineOperand &CtrlOp = MI->getOperand(MI->getNumOperands() - 1);
1924 if (!CtrlOp.isImm())
1925 break;
1926
1927 unsigned ElSize;
1928 switch (MI->getOpcode()) {
1929 default: llvm_unreachable("Invalid opcode");
1930 case X86::VPERMIL2PSrm: case X86::VPERMIL2PSYrm: ElSize = 32; break;
1931 case X86::VPERMIL2PDrm: case X86::VPERMIL2PDYrm: ElSize = 64; break;
1932 }
1933
1934 if (auto *C = X86::getConstantFromPool(*MI, 3)) {
1935 unsigned Width = X86::getVectorRegisterWidth(MI->getDesc().operands()[0]);
1937 DecodeVPERMIL2PMask(C, (unsigned)CtrlOp.getImm(), ElSize, Width, Mask);
1938 if (!Mask.empty())
1939 OutStreamer.AddComment(getShuffleComment(MI, 1, 2, Mask));
1940 }
1941 break;
1942 }
1943
1944 case X86::VPPERMrrm: {
1945 if (auto *C = X86::getConstantFromPool(*MI, 3)) {
1946 unsigned Width = X86::getVectorRegisterWidth(MI->getDesc().operands()[0]);
1948 DecodeVPPERMMask(C, Width, Mask);
1949 if (!Mask.empty())
1950 OutStreamer.AddComment(getShuffleComment(MI, 1, 2, Mask));
1951 }
1952 break;
1953 }
1954
1955 case X86::MMX_MOVQ64rm: {
1956 if (auto *C = X86::getConstantFromPool(*MI, 1)) {
1957 std::string Comment;
1958 raw_string_ostream CS(Comment);
1959 const MachineOperand &DstOp = MI->getOperand(0);
1961 if (auto *CF = dyn_cast<ConstantFP>(C)) {
1962 CS << "0x" << toString(CF->getValueAPF().bitcastToAPInt(), 16, false);
1963 OutStreamer.AddComment(CS.str());
1964 }
1965 }
1966 break;
1967 }
1968
1969 case X86::GF2P8AFFINEQBrmi:
1970 case X86::VGF2P8AFFINEQBrmi:
1971 case X86::VGF2P8AFFINEQBYrmi:
1972 case X86::VGF2P8AFFINEQBZrmi:
1973 case X86::VGF2P8AFFINEQBZ128rmi:
1974 case X86::VGF2P8AFFINEQBZ256rmi: {
1975 // TODO: Add predicate handling with test coverage.
1976 unsigned SrcIdx = getSrcIdx(MI, 1);
1977 unsigned Width = X86::getVectorRegisterWidth(MI->getDesc().operands()[0]);
1978 addConstantComment(MI, OutStreamer, SrcIdx + 1, Width);
1979 break;
1980 }
1981
1982 case X86::VGF2P8AFFINEQBZ128rmbi:
1983 case X86::VGF2P8AFFINEQBZ256rmbi:
1984 case X86::VGF2P8AFFINEQBZrmbi: {
1985 unsigned SrcIdx = getSrcIdx(MI, 1);
1986 unsigned Width = X86::getVectorRegisterWidth(MI->getDesc().operands()[0]);
1987 addConstantComment(MI, OutStreamer, SrcIdx + 1, 64, Width / 64);
1988 break;
1989 }
1990
1991#define INSTR_CASE(Prefix, Instr, Suffix, Postfix) \
1992 case X86::Prefix##Instr##Suffix##rm##Postfix:
1993
1994#define CASE_AVX512_ARITH_RM(Instr) \
1995 INSTR_CASE(V, Instr, Z128, ) \
1996 INSTR_CASE(V, Instr, Z128, k) \
1997 INSTR_CASE(V, Instr, Z128, kz) \
1998 INSTR_CASE(V, Instr, Z256, ) \
1999 INSTR_CASE(V, Instr, Z256, k) \
2000 INSTR_CASE(V, Instr, Z256, kz) \
2001 INSTR_CASE(V, Instr, Z, ) \
2002 INSTR_CASE(V, Instr, Z, k) \
2003 INSTR_CASE(V, Instr, Z, kz)
2004
2005#define CASE_ARITH_RM(Instr) \
2006 INSTR_CASE(, Instr, , ) /* SSE */ \
2007 INSTR_CASE(V, Instr, , ) /* AVX-128 */ \
2008 INSTR_CASE(V, Instr, Y, ) /* AVX-256 */ \
2009 INSTR_CASE(V, Instr, Z128, ) \
2010 INSTR_CASE(V, Instr, Z128, k) \
2011 INSTR_CASE(V, Instr, Z128, kz) \
2012 INSTR_CASE(V, Instr, Z256, ) \
2013 INSTR_CASE(V, Instr, Z256, k) \
2014 INSTR_CASE(V, Instr, Z256, kz) \
2015 INSTR_CASE(V, Instr, Z, ) \
2016 INSTR_CASE(V, Instr, Z, k) \
2017 INSTR_CASE(V, Instr, Z, kz)
2018
2019 // TODO: Add additional instructions when useful.
2020 CASE_ARITH_RM(PADDB)
2021 CASE_ARITH_RM(PADDW)
2022 CASE_ARITH_RM(PADDD)
2023 CASE_ARITH_RM(PADDQ)
2024 CASE_ARITH_RM(PSUBB)
2025 CASE_ARITH_RM(PSUBW)
2026 CASE_ARITH_RM(PSUBD)
2027 CASE_ARITH_RM(PSUBQ)
2028 CASE_ARITH_RM(PMADDUBSW)
2029 CASE_ARITH_RM(PMADDWD)
2030 CASE_ARITH_RM(PMULDQ)
2031 CASE_ARITH_RM(PMULUDQ)
2032 CASE_ARITH_RM(PMULLD)
2033 CASE_AVX512_ARITH_RM(PMULLQ)
2034 CASE_ARITH_RM(PMULLW)
2035 CASE_ARITH_RM(PMULHW)
2036 CASE_ARITH_RM(PMULHUW)
2037 CASE_ARITH_RM(PMULHRSW) {
2038 unsigned SrcIdx = getSrcIdx(MI, 1);
2039 unsigned VectorWidth =
2040 X86::getVectorRegisterWidth(MI->getDesc().operands()[0]);
2041 addConstantComment(MI, OutStreamer, SrcIdx + 1, VectorWidth);
2042 break;
2043 }
2044
2045#define MASK_AVX512_CASE(Instr) \
2046 case Instr: \
2047 case Instr##k: \
2048 case Instr##kz:
2049
2050 case X86::MOVSDrm:
2051 case X86::VMOVSDrm:
2052 MASK_AVX512_CASE(X86::VMOVSDZrm)
2053 case X86::MOVSDrm_alt:
2054 case X86::VMOVSDrm_alt:
2055 case X86::VMOVSDZrm_alt:
2056 case X86::MOVQI2PQIrm:
2057 case X86::VMOVQI2PQIrm:
2058 case X86::VMOVQI2PQIZrm:
2059 printZeroUpperMove(MI, OutStreamer, 64, 128, "mem[0],zero");
2060 break;
2061
2062 MASK_AVX512_CASE(X86::VMOVSHZrm)
2063 case X86::VMOVSHZrm_alt:
2064 printZeroUpperMove(MI, OutStreamer, 16, 128,
2065 "mem[0],zero,zero,zero,zero,zero,zero,zero");
2066 break;
2067
2068 case X86::MOVSSrm:
2069 case X86::VMOVSSrm:
2070 MASK_AVX512_CASE(X86::VMOVSSZrm)
2071 case X86::MOVSSrm_alt:
2072 case X86::VMOVSSrm_alt:
2073 case X86::VMOVSSZrm_alt:
2074 case X86::MOVDI2PDIrm:
2075 case X86::VMOVDI2PDIrm:
2076 case X86::VMOVDI2PDIZrm:
2077 printZeroUpperMove(MI, OutStreamer, 32, 128, "mem[0],zero,zero,zero");
2078 break;
2079
2080#define MOV_CASE(Prefix, Suffix) \
2081 case X86::Prefix##MOVAPD##Suffix##rm: \
2082 case X86::Prefix##MOVAPS##Suffix##rm: \
2083 case X86::Prefix##MOVUPD##Suffix##rm: \
2084 case X86::Prefix##MOVUPS##Suffix##rm: \
2085 case X86::Prefix##MOVDQA##Suffix##rm: \
2086 case X86::Prefix##MOVDQU##Suffix##rm:
2087
2088#define MOV_AVX512_CASE(Suffix, Postfix) \
2089 case X86::VMOVDQA64##Suffix##rm##Postfix: \
2090 case X86::VMOVDQA32##Suffix##rm##Postfix: \
2091 case X86::VMOVDQU64##Suffix##rm##Postfix: \
2092 case X86::VMOVDQU32##Suffix##rm##Postfix: \
2093 case X86::VMOVDQU16##Suffix##rm##Postfix: \
2094 case X86::VMOVDQU8##Suffix##rm##Postfix: \
2095 case X86::VMOVAPS##Suffix##rm##Postfix: \
2096 case X86::VMOVAPD##Suffix##rm##Postfix: \
2097 case X86::VMOVUPS##Suffix##rm##Postfix: \
2098 case X86::VMOVUPD##Suffix##rm##Postfix:
2099
2100#define CASE_128_MOV_RM() \
2101 MOV_CASE(, ) /* SSE */ \
2102 MOV_CASE(V, ) /* AVX-128 */ \
2103 MOV_AVX512_CASE(Z128, ) \
2104 MOV_AVX512_CASE(Z128, k) \
2105 MOV_AVX512_CASE(Z128, kz)
2106
2107#define CASE_256_MOV_RM() \
2108 MOV_CASE(V, Y) /* AVX-256 */ \
2109 MOV_AVX512_CASE(Z256, ) \
2110 MOV_AVX512_CASE(Z256, k) \
2111 MOV_AVX512_CASE(Z256, kz) \
2112
2113#define CASE_512_MOV_RM() \
2114 MOV_AVX512_CASE(Z, ) \
2115 MOV_AVX512_CASE(Z, k) \
2116 MOV_AVX512_CASE(Z, kz) \
2117
2118 // For loads from a constant pool to a vector register, print the constant
2119 // loaded.
2121 printBroadcast(MI, OutStreamer, 1, 128);
2122 break;
2124 printBroadcast(MI, OutStreamer, 1, 256);
2125 break;
2127 printBroadcast(MI, OutStreamer, 1, 512);
2128 break;
2129 case X86::VBROADCASTF128rm:
2130 case X86::VBROADCASTI128rm:
2131 MASK_AVX512_CASE(X86::VBROADCASTF32X4Z256rm)
2132 MASK_AVX512_CASE(X86::VBROADCASTF64X2Z256rm)
2133 MASK_AVX512_CASE(X86::VBROADCASTI32X4Z256rm)
2134 MASK_AVX512_CASE(X86::VBROADCASTI64X2Z256rm)
2135 printBroadcast(MI, OutStreamer, 2, 128);
2136 break;
2137 MASK_AVX512_CASE(X86::VBROADCASTF32X4Zrm)
2138 MASK_AVX512_CASE(X86::VBROADCASTF64X2Zrm)
2139 MASK_AVX512_CASE(X86::VBROADCASTI32X4Zrm)
2140 MASK_AVX512_CASE(X86::VBROADCASTI64X2Zrm)
2141 printBroadcast(MI, OutStreamer, 4, 128);
2142 break;
2143 MASK_AVX512_CASE(X86::VBROADCASTF32X8Zrm)
2144 MASK_AVX512_CASE(X86::VBROADCASTF64X4Zrm)
2145 MASK_AVX512_CASE(X86::VBROADCASTI32X8Zrm)
2146 MASK_AVX512_CASE(X86::VBROADCASTI64X4Zrm)
2147 printBroadcast(MI, OutStreamer, 2, 256);
2148 break;
2149
2150 // For broadcast loads from a constant pool to a vector register, repeatedly
2151 // print the constant loaded.
2152 case X86::MOVDDUPrm:
2153 case X86::VMOVDDUPrm:
2154 MASK_AVX512_CASE(X86::VMOVDDUPZ128rm)
2155 case X86::VPBROADCASTQrm:
2156 MASK_AVX512_CASE(X86::VPBROADCASTQZ128rm)
2157 printBroadcast(MI, OutStreamer, 2, 64);
2158 break;
2159 case X86::VBROADCASTSDYrm:
2160 MASK_AVX512_CASE(X86::VBROADCASTSDZ256rm)
2161 case X86::VPBROADCASTQYrm:
2162 MASK_AVX512_CASE(X86::VPBROADCASTQZ256rm)
2163 printBroadcast(MI, OutStreamer, 4, 64);
2164 break;
2165 MASK_AVX512_CASE(X86::VBROADCASTSDZrm)
2166 MASK_AVX512_CASE(X86::VPBROADCASTQZrm)
2167 printBroadcast(MI, OutStreamer, 8, 64);
2168 break;
2169 case X86::VBROADCASTSSrm:
2170 MASK_AVX512_CASE(X86::VBROADCASTSSZ128rm)
2171 case X86::VPBROADCASTDrm:
2172 MASK_AVX512_CASE(X86::VPBROADCASTDZ128rm)
2173 printBroadcast(MI, OutStreamer, 4, 32);
2174 break;
2175 case X86::VBROADCASTSSYrm:
2176 MASK_AVX512_CASE(X86::VBROADCASTSSZ256rm)
2177 case X86::VPBROADCASTDYrm:
2178 MASK_AVX512_CASE(X86::VPBROADCASTDZ256rm)
2179 printBroadcast(MI, OutStreamer, 8, 32);
2180 break;
2181 MASK_AVX512_CASE(X86::VBROADCASTSSZrm)
2182 MASK_AVX512_CASE(X86::VPBROADCASTDZrm)
2183 printBroadcast(MI, OutStreamer, 16, 32);
2184 break;
2185 case X86::VPBROADCASTWrm:
2186 MASK_AVX512_CASE(X86::VPBROADCASTWZ128rm)
2187 printBroadcast(MI, OutStreamer, 8, 16);
2188 break;
2189 case X86::VPBROADCASTWYrm:
2190 MASK_AVX512_CASE(X86::VPBROADCASTWZ256rm)
2191 printBroadcast(MI, OutStreamer, 16, 16);
2192 break;
2193 MASK_AVX512_CASE(X86::VPBROADCASTWZrm)
2194 printBroadcast(MI, OutStreamer, 32, 16);
2195 break;
2196 case X86::VPBROADCASTBrm:
2197 MASK_AVX512_CASE(X86::VPBROADCASTBZ128rm)
2198 printBroadcast(MI, OutStreamer, 16, 8);
2199 break;
2200 case X86::VPBROADCASTBYrm:
2201 MASK_AVX512_CASE(X86::VPBROADCASTBZ256rm)
2202 printBroadcast(MI, OutStreamer, 32, 8);
2203 break;
2204 MASK_AVX512_CASE(X86::VPBROADCASTBZrm)
2205 printBroadcast(MI, OutStreamer, 64, 8);
2206 break;
2207
2208#define MOVX_CASE(Prefix, Ext, Type, Suffix, Postfix) \
2209 case X86::Prefix##PMOV##Ext##Type##Suffix##rm##Postfix:
2210
2211#define CASE_MOVX_RM(Ext, Type) \
2212 MOVX_CASE(, Ext, Type, , ) \
2213 MOVX_CASE(V, Ext, Type, , ) \
2214 MOVX_CASE(V, Ext, Type, Y, ) \
2215 MOVX_CASE(V, Ext, Type, Z128, ) \
2216 MOVX_CASE(V, Ext, Type, Z128, k ) \
2217 MOVX_CASE(V, Ext, Type, Z128, kz ) \
2218 MOVX_CASE(V, Ext, Type, Z256, ) \
2219 MOVX_CASE(V, Ext, Type, Z256, k ) \
2220 MOVX_CASE(V, Ext, Type, Z256, kz ) \
2221 MOVX_CASE(V, Ext, Type, Z, ) \
2222 MOVX_CASE(V, Ext, Type, Z, k ) \
2223 MOVX_CASE(V, Ext, Type, Z, kz )
2224
2225 CASE_MOVX_RM(SX, BD)
2226 printSignExtend(MI, OutStreamer, 8, 32);
2227 break;
2228 CASE_MOVX_RM(SX, BQ)
2229 printSignExtend(MI, OutStreamer, 8, 64);
2230 break;
2231 CASE_MOVX_RM(SX, BW)
2232 printSignExtend(MI, OutStreamer, 8, 16);
2233 break;
2234 CASE_MOVX_RM(SX, DQ)
2235 printSignExtend(MI, OutStreamer, 32, 64);
2236 break;
2237 CASE_MOVX_RM(SX, WD)
2238 printSignExtend(MI, OutStreamer, 16, 32);
2239 break;
2240 CASE_MOVX_RM(SX, WQ)
2241 printSignExtend(MI, OutStreamer, 16, 64);
2242 break;
2243
2244 CASE_MOVX_RM(ZX, BD)
2245 printZeroExtend(MI, OutStreamer, 8, 32);
2246 break;
2247 CASE_MOVX_RM(ZX, BQ)
2248 printZeroExtend(MI, OutStreamer, 8, 64);
2249 break;
2250 CASE_MOVX_RM(ZX, BW)
2251 printZeroExtend(MI, OutStreamer, 8, 16);
2252 break;
2253 CASE_MOVX_RM(ZX, DQ)
2254 printZeroExtend(MI, OutStreamer, 32, 64);
2255 break;
2256 CASE_MOVX_RM(ZX, WD)
2257 printZeroExtend(MI, OutStreamer, 16, 32);
2258 break;
2259 CASE_MOVX_RM(ZX, WQ)
2260 printZeroExtend(MI, OutStreamer, 16, 64);
2261 break;
2262 }
2263}
2264
2265// Does the given operand refer to a DLLIMPORT function?
2267 return MO.isGlobal() && (MO.getTargetFlags() == X86II::MO_DLLIMPORT);
2268}
2269
2270// Is the given instruction a call to a CFGuard function?
2272 assert(MI->getOpcode() == X86::TAILJMPm64_REX ||
2273 MI->getOpcode() == X86::CALL64m);
2274 const MachineOperand &MO = MI->getOperand(3);
2275 return MO.isGlobal() && (MO.getTargetFlags() == X86II::MO_NO_FLAG) &&
2277}
2278
2279// Does the containing block for the given instruction contain any jump table
2280// info (indicating that the block is a dispatch for a jump table)?
2282 const MachineBasicBlock &MBB = *MI->getParent();
2283 for (auto I = MBB.instr_rbegin(), E = MBB.instr_rend(); I != E; ++I)
2284 if (I->isJumpTableDebugInfo())
2285 return true;
2286
2287 return false;
2288}
2289
2291 // FIXME: Enable feature predicate checks once all the test pass.
2292 // X86_MC::verifyInstructionPredicates(MI->getOpcode(),
2293 // Subtarget->getFeatureBits());
2294
2295 X86MCInstLower MCInstLowering(*MF, *this);
2296 const X86RegisterInfo *RI =
2297 MF->getSubtarget<X86Subtarget>().getRegisterInfo();
2298
2299 if (MI->getOpcode() == X86::OR64rm) {
2300 for (auto &Opd : MI->operands()) {
2301 if (Opd.isSymbol() && StringRef(Opd.getSymbolName()) ==
2302 "swift_async_extendedFramePointerFlags") {
2303 ShouldEmitWeakSwiftAsyncExtendedFramePointerFlags = true;
2304 }
2305 }
2306 }
2307
2308 // Add comments for values loaded from constant pool.
2309 if (OutStreamer->isVerboseAsm())
2311
2312 // Add a comment about EVEX compression
2313 if (TM.Options.MCOptions.ShowMCEncoding) {
2314 if (MI->getAsmPrinterFlags() & X86::AC_EVEX_2_LEGACY)
2315 OutStreamer->AddComment("EVEX TO LEGACY Compression ", false);
2316 else if (MI->getAsmPrinterFlags() & X86::AC_EVEX_2_VEX)
2317 OutStreamer->AddComment("EVEX TO VEX Compression ", false);
2318 else if (MI->getAsmPrinterFlags() & X86::AC_EVEX_2_EVEX)
2319 OutStreamer->AddComment("EVEX TO EVEX Compression ", false);
2320 }
2321
2322 // We use this to suppress NOP padding for Windows EH.
2323 bool IsTailJump = false;
2324
2325 switch (MI->getOpcode()) {
2326 case TargetOpcode::DBG_VALUE:
2327 llvm_unreachable("Should be handled target independently");
2328
2329 case X86::EH_RETURN:
2330 case X86::EH_RETURN64: {
2331 // Lower these as normal, but add some comments.
2332 Register Reg = MI->getOperand(0).getReg();
2333 OutStreamer->AddComment(StringRef("eh_return, addr: %") +
2335 break;
2336 }
2337 case X86::CLEANUPRET: {
2338 // Lower these as normal, but add some comments.
2339 OutStreamer->AddComment("CLEANUPRET");
2340 break;
2341 }
2342
2343 case X86::CATCHRET: {
2344 // Lower these as normal, but add some comments.
2345 OutStreamer->AddComment("CATCHRET");
2346 break;
2347 }
2348
2349 case X86::ENDBR32:
2350 case X86::ENDBR64: {
2351 // CurrentPatchableFunctionEntrySym can be CurrentFnBegin only for
2352 // -fpatchable-function-entry=N,0. The entry MBB is guaranteed to be
2353 // non-empty. If MI is the initial ENDBR, place the
2354 // __patchable_function_entries label after ENDBR.
2357 MI == &MF->front().front()) {
2358 MCInst Inst;
2359 MCInstLowering.Lower(MI, Inst);
2360 EmitAndCountInstruction(Inst);
2363 return;
2364 }
2365 break;
2366 }
2367
2368 case X86::TAILJMPd64:
2369 if (IndCSPrefix && MI->hasRegisterImplicitUseOperand(X86::R11))
2370 EmitAndCountInstruction(MCInstBuilder(X86::CS_PREFIX));
2371
2372 if (EnableImportCallOptimization && isImportedFunction(MI->getOperand(0))) {
2373 emitLabelAndRecordForImportCallOptimization(
2374 IMAGE_RETPOLINE_AMD64_IMPORT_BR);
2375 }
2376
2377 // Lower this as normal, but add a comment.
2378 OutStreamer->AddComment("TAILCALL");
2379 IsTailJump = true;
2380 break;
2381
2382 case X86::TAILJMPr:
2383 case X86::TAILJMPm:
2384 case X86::TAILJMPd:
2385 case X86::TAILJMPd_CC:
2386 case X86::TAILJMPr64:
2387 case X86::TAILJMPm64:
2388 case X86::TAILJMPd64_CC:
2389 if (EnableImportCallOptimization)
2390 report_fatal_error("Unexpected TAILJMP instruction was emitted when "
2391 "import call optimization was enabled");
2392
2393 // Lower these as normal, but add some comments.
2394 OutStreamer->AddComment("TAILCALL");
2395 IsTailJump = true;
2396 break;
2397
2398 case X86::TAILJMPm64_REX:
2399 if (EnableImportCallOptimization && isCallToCFGuardFunction(MI)) {
2400 emitLabelAndRecordForImportCallOptimization(
2401 IMAGE_RETPOLINE_AMD64_CFG_BR_REX);
2402 }
2403
2404 OutStreamer->AddComment("TAILCALL");
2405 IsTailJump = true;
2406 break;
2407
2408 case X86::TAILJMPr64_REX: {
2409 if (EnableImportCallOptimization) {
2410 assert(MI->getOperand(0).getReg() == X86::RAX &&
2411 "Indirect tail calls with impcall enabled must go through RAX (as "
2412 "enforced by TCRETURNImpCallri64)");
2413 emitLabelAndRecordForImportCallOptimization(
2414 IMAGE_RETPOLINE_AMD64_INDIR_BR);
2415 }
2416
2417 OutStreamer->AddComment("TAILCALL");
2418 IsTailJump = true;
2419 break;
2420 }
2421
2422 case X86::JMP64r:
2423 if (EnableImportCallOptimization && hasJumpTableInfoInBlock(MI)) {
2424 uint16_t EncodedReg =
2425 this->getSubtarget().getRegisterInfo()->getEncodingValue(
2426 MI->getOperand(0).getReg().asMCReg());
2427 emitLabelAndRecordForImportCallOptimization(
2428 (ImportCallKind)(IMAGE_RETPOLINE_AMD64_SWITCHTABLE_FIRST +
2429 EncodedReg));
2430 }
2431 break;
2432
2433 case X86::JMP16r:
2434 case X86::JMP16m:
2435 case X86::JMP32r:
2436 case X86::JMP32m:
2437 case X86::JMP64m:
2438 if (EnableImportCallOptimization && hasJumpTableInfoInBlock(MI))
2440 "Unexpected JMP instruction was emitted for a jump-table when import "
2441 "call optimization was enabled");
2442 break;
2443
2444 case X86::TLS_addr32:
2445 case X86::TLS_addr64:
2446 case X86::TLS_addrX32:
2447 case X86::TLS_base_addr32:
2448 case X86::TLS_base_addr64:
2449 case X86::TLS_base_addrX32:
2450 case X86::TLS_desc32:
2451 case X86::TLS_desc64:
2452 return LowerTlsAddr(MCInstLowering, *MI);
2453
2454 case X86::MOVPC32r: {
2455 // This is a pseudo op for a two instruction sequence with a label, which
2456 // looks like:
2457 // call "L1$pb"
2458 // "L1$pb":
2459 // popl %esi
2460
2461 // Emit the call.
2462 MCSymbol *PICBase = MF->getPICBaseSymbol();
2463 // FIXME: We would like an efficient form for this, so we don't have to do a
2464 // lot of extra uniquing.
2465 EmitAndCountInstruction(
2466 MCInstBuilder(X86::CALLpcrel32)
2467 .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
2468
2469 const X86FrameLowering *FrameLowering =
2470 MF->getSubtarget<X86Subtarget>().getFrameLowering();
2471 bool hasFP = FrameLowering->hasFP(*MF);
2472
2473 // TODO: This is needed only if we require precise CFA.
2474 bool HasActiveDwarfFrame = OutStreamer->getNumFrameInfos() &&
2475 !OutStreamer->getDwarfFrameInfos().back().End;
2476
2477 int stackGrowth = -RI->getSlotSize();
2478
2479 if (HasActiveDwarfFrame && !hasFP) {
2480 OutStreamer->emitCFIAdjustCfaOffset(-stackGrowth);
2481 MF->getInfo<X86MachineFunctionInfo>()->setHasCFIAdjustCfa(true);
2482 }
2483
2484 // Emit the label.
2485 OutStreamer->emitLabel(PICBase);
2486
2487 // popl $reg
2488 EmitAndCountInstruction(
2489 MCInstBuilder(X86::POP32r).addReg(MI->getOperand(0).getReg()));
2490
2491 if (HasActiveDwarfFrame && !hasFP) {
2492 OutStreamer->emitCFIAdjustCfaOffset(stackGrowth);
2493 }
2494 return;
2495 }
2496
2497 case X86::ADD32ri: {
2498 // Lower the MO_GOT_ABSOLUTE_ADDRESS form of ADD32ri.
2499 if (MI->getOperand(2).getTargetFlags() != X86II::MO_GOT_ABSOLUTE_ADDRESS)
2500 break;
2501
2502 // Okay, we have something like:
2503 // EAX = ADD32ri EAX, MO_GOT_ABSOLUTE_ADDRESS(@MYGLOBAL)
2504
2505 // For this, we want to print something like:
2506 // MYGLOBAL + (. - PICBASE)
2507 // However, we can't generate a ".", so just emit a new label here and refer
2508 // to it.
2509 MCSymbol *DotSym = OutContext.createTempSymbol();
2510 OutStreamer->emitLabel(DotSym);
2511
2512 // Now that we have emitted the label, lower the complex operand expression.
2513 MCSymbol *OpSym = MCInstLowering.GetSymbolFromOperand(MI->getOperand(2));
2514
2515 const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
2516 const MCExpr *PICBase =
2517 MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
2518 DotExpr = MCBinaryExpr::createSub(DotExpr, PICBase, OutContext);
2519
2520 DotExpr = MCBinaryExpr::createAdd(
2522
2523 EmitAndCountInstruction(MCInstBuilder(X86::ADD32ri)
2524 .addReg(MI->getOperand(0).getReg())
2525 .addReg(MI->getOperand(1).getReg())
2526 .addExpr(DotExpr));
2527 return;
2528 }
2529 case TargetOpcode::STATEPOINT:
2530 return LowerSTATEPOINT(*MI, MCInstLowering);
2531
2532 case TargetOpcode::FAULTING_OP:
2533 return LowerFAULTING_OP(*MI, MCInstLowering);
2534
2535 case TargetOpcode::FENTRY_CALL:
2536 return LowerFENTRY_CALL(*MI, MCInstLowering);
2537
2538 case TargetOpcode::PATCHABLE_OP:
2539 return LowerPATCHABLE_OP(*MI, MCInstLowering);
2540
2541 case TargetOpcode::STACKMAP:
2542 return LowerSTACKMAP(*MI);
2543
2544 case TargetOpcode::PATCHPOINT:
2545 return LowerPATCHPOINT(*MI, MCInstLowering);
2546
2547 case TargetOpcode::PATCHABLE_FUNCTION_ENTER:
2548 return LowerPATCHABLE_FUNCTION_ENTER(*MI, MCInstLowering);
2549
2550 case TargetOpcode::PATCHABLE_RET:
2551 return LowerPATCHABLE_RET(*MI, MCInstLowering);
2552
2553 case TargetOpcode::PATCHABLE_TAIL_CALL:
2554 return LowerPATCHABLE_TAIL_CALL(*MI, MCInstLowering);
2555
2556 case TargetOpcode::PATCHABLE_EVENT_CALL:
2557 return LowerPATCHABLE_EVENT_CALL(*MI, MCInstLowering);
2558
2559 case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
2560 return LowerPATCHABLE_TYPED_EVENT_CALL(*MI, MCInstLowering);
2561
2562 case X86::MORESTACK_RET:
2563 EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
2564 return;
2565
2566 case X86::KCFI_CHECK:
2567 return LowerKCFI_CHECK(*MI);
2568
2569 case X86::ASAN_CHECK_MEMACCESS:
2570 return LowerASAN_CHECK_MEMACCESS(*MI);
2571
2572 case X86::MORESTACK_RET_RESTORE_R10:
2573 // Return, then restore R10.
2574 EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
2575 EmitAndCountInstruction(
2576 MCInstBuilder(X86::MOV64rr).addReg(X86::R10).addReg(X86::RAX));
2577 return;
2578
2579 case X86::SEH_PushReg:
2580 case X86::SEH_Push2Regs:
2581 case X86::SEH_SaveReg:
2582 case X86::SEH_SaveXMM:
2583 case X86::SEH_StackAlloc:
2584 case X86::SEH_StackAlign:
2585 case X86::SEH_SetFrame:
2586 case X86::SEH_PushFrame:
2587 case X86::SEH_EndPrologue:
2588 case X86::SEH_EndEpilogue:
2589 case X86::SEH_UnwindV2Start:
2590 case X86::SEH_UnwindVersion:
2591 EmitSEHInstruction(MI);
2592 return;
2593
2594 case X86::SEH_SplitChainedAtEndOfBlock:
2595 assert(!SplitChainedAtEndOfBlock &&
2596 "Duplicate SEH_SplitChainedAtEndOfBlock in a current block");
2597 SplitChainedAtEndOfBlock = true;
2598 return;
2599
2600 case X86::SEH_SplitChained:
2601 assert(MF->hasWinCFI() && "SEH_ instruction in function without WinCFI?");
2602 OutStreamer->emitWinCFISplitChained();
2603 return;
2604
2605 case X86::SEH_BeginEpilogue: {
2606 assert(MF->hasWinCFI() && "SEH_ instruction in function without WinCFI?");
2607 EmitSEHInstruction(MI);
2608 return;
2609 }
2610 case X86::UBSAN_UD1:
2611 EmitAndCountInstruction(MCInstBuilder(X86::UD1Lm)
2612 .addReg(X86::EAX)
2613 .addReg(X86::EAX)
2614 .addImm(1)
2615 .addReg(X86::NoRegister)
2616 .addImm(MI->getOperand(0).getImm())
2617 .addReg(X86::NoRegister));
2618 return;
2619 case X86::CALL64pcrel32:
2620 if (IndCSPrefix && MI->hasRegisterImplicitUseOperand(X86::R11))
2621 EmitAndCountInstruction(MCInstBuilder(X86::CS_PREFIX));
2622
2623 if (EnableImportCallOptimization && isImportedFunction(MI->getOperand(0))) {
2624 emitLabelAndRecordForImportCallOptimization(
2625 IMAGE_RETPOLINE_AMD64_IMPORT_CALL);
2626
2627 MCInst TmpInst;
2628 MCInstLowering.Lower(MI, TmpInst);
2629
2630 // For Import Call Optimization to work, we need a the call instruction
2631 // with a rex prefix, and a 5-byte nop after the call instruction.
2632 EmitAndCountInstruction(MCInstBuilder(X86::REX64_PREFIX));
2633 emitCallInstruction(TmpInst);
2634 emitNop(*OutStreamer, 5, Subtarget);
2635 maybeEmitNopAfterCallForWindowsEH(MI);
2636 return;
2637 }
2638
2639 break;
2640
2641 case X86::CALL64r:
2642 if (EnableImportCallOptimization) {
2643 assert(MI->getOperand(0).getReg() == X86::RAX &&
2644 "Indirect calls with impcall enabled must go through RAX (as "
2645 "enforced by CALL64r_ImpCall)");
2646
2647 emitLabelAndRecordForImportCallOptimization(
2648 IMAGE_RETPOLINE_AMD64_INDIR_CALL);
2649 MCInst TmpInst;
2650 MCInstLowering.Lower(MI, TmpInst);
2651 emitCallInstruction(TmpInst);
2652
2653 // For Import Call Optimization to work, we need a 3-byte nop after the
2654 // call instruction.
2655 emitNop(*OutStreamer, 3, Subtarget);
2656 maybeEmitNopAfterCallForWindowsEH(MI);
2657 return;
2658 }
2659 break;
2660
2661 case X86::CALL64m:
2662 if (EnableImportCallOptimization && isCallToCFGuardFunction(MI)) {
2663 emitLabelAndRecordForImportCallOptimization(
2664 IMAGE_RETPOLINE_AMD64_CFG_CALL);
2665 }
2666 break;
2667
2668 case X86::JCC_1:
2669 // Two instruction prefixes (2EH for branch not-taken and 3EH for branch
2670 // taken) are used as branch hints. Here we add branch taken prefix for
2671 // jump instruction with higher probability than threshold.
2672 if (getSubtarget().hasBranchHint() &&
2673 getSubtarget().getCLOpts().enable_branch_hint) {
2674 const MachineBranchProbabilityInfo *MBPI = GetMBPI(*MF);
2675 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
2676 BranchProbability EdgeProb =
2677 MBPI->getEdgeProbability(MI->getParent(), DestBB);
2678 BranchProbability Threshold(
2679 getSubtarget().getCLOpts().branch_hint_probability_threshold, 100);
2680 if (EdgeProb > Threshold)
2681 EmitAndCountInstruction(MCInstBuilder(X86::DS_PREFIX));
2682 }
2683 break;
2684
2685 case X86::JCC_SELF:
2686 MCSymbol *Sym = OutContext.createTempSymbol();
2687 OutStreamer->emitLabel(Sym);
2688 EmitAndCountInstruction(
2689 MCInstBuilder(X86::JCC_1)
2690 .addExpr(MCSymbolRefExpr::create(Sym, OutContext))
2691 .addImm(MI->getOperand(0).getImm()));
2692 return;
2693 }
2694
2695 MCInst TmpInst;
2696 MCInstLowering.Lower(MI, TmpInst);
2697
2698 if (MI->isCall()) {
2699 emitCallInstruction(TmpInst);
2700 // Since tail calls transfer control without leaving a stack frame, there is
2701 // never a need for NOP padding tail calls.
2702 if (!IsTailJump)
2703 maybeEmitNopAfterCallForWindowsEH(MI);
2704 return;
2705 }
2706
2707 EmitAndCountInstruction(TmpInst);
2708}
2709
2711 const MCSubtargetInfo *EndInfo,
2712 const MachineInstr *MI) {
2713 if (MI) {
2714 // If unwinding inline asm ends on a call, wineh may require insertion of
2715 // a nop.
2716 unsigned ExtraInfo = MI->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
2717 if (ExtraInfo & InlineAsm::Extra_MayUnwind)
2718 maybeEmitNopAfterCallForWindowsEH(MI);
2719 }
2720}
2721
2722void X86AsmPrinter::emitCallInstruction(const llvm::MCInst &MCI) {
2723 // Stackmap shadows cannot include branch targets, so we can count the bytes
2724 // in a call towards the shadow, but must ensure that the no thread returns
2725 // in to the stackmap shadow. The only way to achieve this is if the call
2726 // is at the end of the shadow.
2727
2728 // Count then size of the call towards the shadow
2729 SMShadowTracker.count(MCI, getSubtargetInfo(), CodeEmitter.get());
2730 // Then flush the shadow so that we fill with nops before the call, not
2731 // after it.
2732 SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
2733 // Then emit the call
2734 OutStreamer->emitInstruction(MCI, getSubtargetInfo());
2735}
2736
2737// Determines whether a NOP is required after a CALL, so that Windows EH
2738// IP2State tables have the correct information.
2739//
2740// On most Windows platforms (AMD64, ARM64, ARM32, IA64, but *not* x86-32),
2741// exception handling works by looking up instruction pointers in lookup
2742// tables. These lookup tables are stored in .xdata sections in executables.
2743// One element of the lookup tables are the "IP2State" tables (Instruction
2744// Pointer to State).
2745//
2746// If a function has any instructions that require cleanup during exception
2747// unwinding, then it will have an IP2State table. Each entry in the IP2State
2748// table describes a range of bytes in the function's instruction stream, and
2749// associates an "EH state number" with that range of instructions. A value of
2750// -1 means "the null state", which does not require any code to execute.
2751// A value other than -1 is an index into the State table.
2752//
2753// The entries in the IP2State table contain byte offsets within the instruction
2754// stream of the function. The Windows ABI requires that these offsets are
2755// aligned to instruction boundaries; they are not permitted to point to a byte
2756// that is not the first byte of an instruction.
2757//
2758// Unfortunately, CALL instructions present a problem during unwinding. CALL
2759// instructions push the address of the instruction after the CALL instruction,
2760// so that execution can resume after the CALL. If the CALL is the last
2761// instruction within an IP2State region, then the return address (on the stack)
2762// points to the *next* IP2State region. This means that the unwinder will
2763// use the wrong cleanup funclet during unwinding.
2764//
2765// To fix this problem, the Windows AMD64 ABI requires that CALL instructions
2766// are never placed at the end of an IP2State region. Stated equivalently, the
2767// end of a CALL instruction cannot be aligned to an IP2State boundary. If a
2768// CALL instruction would occur at the end of an IP2State region, then the
2769// compiler must insert a NOP instruction after the CALL. The NOP instruction
2770// is placed in the same EH region as the CALL instruction, so that the return
2771// address points to the NOP and the unwinder will locate the correct region.
2772//
2773// NOP padding is only necessary on Windows AMD64 targets. On ARM64 and ARM32,
2774// instructions have a fixed size so the unwinder knows how to "back up" by
2775// one instruction.
2776//
2777// Interaction with Import Call Optimization (ICO):
2778//
2779// Import Call Optimization (ICO) is a compiler + OS feature on Windows which
2780// improves the performance and security of DLL imports. ICO relies on using a
2781// specific CALL idiom that can be replaced by the OS DLL loader. This removes
2782// a load and indirect CALL and replaces it with a single direct CALL.
2783//
2784// To achieve this, ICO also inserts NOPs after the CALL instruction. If the
2785// end of the CALL is aligned with an EH state transition, we *also* insert
2786// a single-byte NOP. **Both forms of NOPs must be preserved.** They cannot
2787// be combined into a single larger NOP; nor can the second NOP be removed.
2788//
2789// This is necessary because, if ICO is active and the call site is modified
2790// by the loader, the loader will end up overwriting the NOPs that were inserted
2791// for ICO. That means that those NOPs cannot be used for the correct
2792// termination of the exception handling region (the IP2State transition),
2793// so we still need an additional NOP instruction. The NOPs cannot be combined
2794// into a longer NOP (which is ordinarily desirable) because then ICO would
2795// split one instruction, producing a malformed instruction after the ICO call.
2796void X86AsmPrinter::maybeEmitNopAfterCallForWindowsEH(const MachineInstr *MI) {
2797 // We only need to insert NOPs after CALLs when targeting Windows on AMD64.
2798 // (Don't let the name fool you: Itanium refers to table-based exception
2799 // handling, not the Itanium architecture.)
2800 if (getModuleExceptionModel() != ExceptionHandling::WinEH ||
2801 MAI.getWinEHEncodingType() != WinEH::EncodingType::Itanium) {
2802 return;
2803 }
2804
2805 bool HasEHPersonality = MF->getWinEHFuncInfo() != nullptr;
2806
2807 // Set up MBB iterator, initially positioned on the same MBB as MI.
2808 MachineFunction::const_iterator MFI(MI->getParent());
2810
2811 // Set up instruction iterator, positioned immediately *after* MI.
2813 MachineBasicBlock::const_iterator MBBE = MI->getParent()->end();
2814 ++MBBI; // Step over MI
2815
2816 // This loop iterates MBBs
2817 for (;;) {
2818 // This loop iterates instructions
2819 for (; MBBI != MBBE; ++MBBI) {
2820 // Check the instruction that follows this CALL.
2821 const MachineInstr &NextMI = *MBBI;
2822
2823 // If there is an EH_LABEL after this CALL, then there is an EH state
2824 // transition after this CALL. This is exactly the situation which
2825 // requires NOP padding.
2826 if (NextMI.isEHLabel()) {
2827 if (HasEHPersonality) {
2828 EmitAndCountInstruction(MCInstBuilder(X86::NOOP));
2829 return;
2830 }
2831 // We actually want to continue, in case there is an SEH_BeginEpilogue
2832 // instruction after the EH_LABEL. In some situations, IR is produced
2833 // that contains EH_LABEL pseudo-instructions, even when we are not
2834 // generating IP2State tables. We still need to insert a NOP before
2835 // SEH_BeginEpilogue in that case.
2836 continue;
2837 }
2838
2839 // Somewhat similarly, if the CALL is the last instruction before the
2840 // SEH prologue, then we also need a NOP. This is necessary because the
2841 // Windows stack unwinder will not invoke a function's exception handler
2842 // if the instruction pointer is in the function prologue or epilogue.
2843 //
2844 // We always emit a NOP before SEH_BeginEpilogue, even if there is no
2845 // personality function (unwind info) for this frame. This is the same
2846 // behavior as MSVC.
2847 if (NextMI.getOpcode() == X86::SEH_BeginEpilogue) {
2848 EmitAndCountInstruction(MCInstBuilder(X86::NOOP));
2849 return;
2850 }
2851
2852 if (!NextMI.isPseudo() && !NextMI.isMetaInstruction()) {
2853 // We found a real instruction. During the CALL, the return IP will
2854 // point to this instruction. Since this instruction has the same EH
2855 // state as the call itself (because there is no intervening EH_LABEL),
2856 // the IP2State table will be accurate; there is no need to insert a
2857 // NOP.
2858 return;
2859 }
2860
2861 // The next instruction is a pseudo-op. Ignore it and keep searching.
2862 // Because these instructions do not generate any machine code, they
2863 // cannot prevent the IP2State table from pointing at the wrong
2864 // instruction during a CALL.
2865 }
2866
2867 // We've reached the end of this MBB. Find the next MBB in program order.
2868 // MBB order should be finalized by this point, so falling across MBBs is
2869 // expected.
2870 ++MFI;
2871 if (MFI == MFE) {
2872 // No more blocks; we've reached the end of the function. This should
2873 // only happen with no-return functions, but double-check to be sure.
2874 if (HasEHPersonality) {
2875 // If the CALL has no successors, then it is a noreturn function.
2876 // Insert an INT3 instead of a NOP. This accomplishes the same purpose,
2877 // but is more clear to read. Also, analysis tools will understand
2878 // that they should not continue disassembling after the CALL (unless
2879 // there are other branches to that label).
2880 if (MI->getParent()->succ_empty())
2881 EmitAndCountInstruction(MCInstBuilder(X86::INT3));
2882 else
2883 EmitAndCountInstruction(MCInstBuilder(X86::NOOP));
2884 }
2885 return;
2886 }
2887
2888 // Set up iterator to scan the next basic block.
2889 const MachineBasicBlock *NextMBB = &*MFI;
2890 MBBI = NextMBB->instr_begin();
2891 MBBE = NextMBB->instr_end();
2892 }
2893}
2894
2895void X86AsmPrinter::emitLabelAndRecordForImportCallOptimization(
2896 ImportCallKind Kind) {
2897 assert(EnableImportCallOptimization);
2898
2899 MCSymbol *CallSiteSymbol = MMI->getContext().createNamedTempSymbol("impcall");
2900 OutStreamer->emitLabel(CallSiteSymbol);
2901
2902 SectionToImportedFunctionCalls[OutStreamer->getCurrentSectionOnly()]
2903 .push_back({CallSiteSymbol, Kind});
2904}
const AArch64Subtarget & Subtarget
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static void printShuffleMask(raw_ostream &Out, Type *Ty, ArrayRef< int > Mask)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
IRTranslator LLVM IR MI
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
print mir2vec MIR2Vec Vocabulary Printer Pass
Definition MIR2Vec.cpp:667
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCSymbol * GetSymbolFromOperand(const MachineOperand &MO, AsmPrinter &AP)
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallString class.
This file contains some functions that are useful when dealing with strings.
static MCOperand LowerSymbolOperand(const MachineInstr *MI, const MachineOperand &MO, const MCSymbol *Symbol, AsmPrinter &AP)
static void emitX86Nops(MCStreamer &OS, unsigned NumBytes, const X86Subtarget *Subtarget)
Emit the optimal amount of multi-byte nops on X86.
static unsigned getRetOpcode(const X86Subtarget &Subtarget)
static void printSignExtend(const MachineInstr *MI, MCStreamer &OutStreamer, int SrcEltBits, int DstEltBits)
static unsigned getSrcIdx(const MachineInstr *MI, unsigned SrcIdx)
static void printBroadcast(const MachineInstr *MI, MCStreamer &OutStreamer, int Repeats, int BitWidth)
static bool printExtend(const MachineInstr *MI, MCStreamer &OutStreamer, int SrcEltBits, int DstEltBits, bool IsSext)
static void printZeroUpperMove(const MachineInstr *MI, MCStreamer &OutStreamer, int SclWidth, int VecWidth, const char *ShuffleComment)
static void addConstantComment(const MachineInstr *MI, MCStreamer &OutStreamer, unsigned OpNo, int BitWidth, int Repeats=1)
static unsigned convertTailJumpOpcode(unsigned Opcode, bool IsLarge=false)
#define MASK_AVX512_CASE(Instr)
#define CASE_ARITH_RM(Instr)
static void addConstantComments(const MachineInstr *MI, MCStreamer &OutStreamer)
#define CASE_256_MOV_RM()
#define CASE_AVX512_ARITH_RM(Instr)
bool hasJumpTableInfoInBlock(const llvm::MachineInstr *MI)
static unsigned emitNop(MCStreamer &OS, unsigned NumBytes, const X86Subtarget *Subtarget)
Emit the largest nop instruction smaller than or equal to NumBytes bytes.
static void printDstRegisterName(raw_ostream &CS, const MachineInstr *MI, unsigned SrcOpIdx)
#define CASE_MOVX_RM(Ext, Type)
bool isImportedFunction(const MachineOperand &MO)
static void printConstant(const APInt &Val, raw_ostream &CS, bool PrintZero=false)
static void printZeroExtend(const MachineInstr *MI, MCStreamer &OutStreamer, int SrcEltBits, int DstEltBits)
static std::string getShuffleComment(const MachineInstr *MI, unsigned SrcOp1Idx, unsigned SrcOp2Idx, ArrayRef< int > Mask)
bool isCallToCFGuardFunction(const MachineInstr *MI)
#define CASE_512_MOV_RM()
#define CASE_128_MOV_RM()
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Definition APFloat.h:1653
const fltSemantics & getSemantics() const
Definition APFloat.h:1624
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1216
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
unsigned getNumWords() const
Get the number of words.
Definition APInt.h:1515
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition APInt.h:571
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
MCSymbol * getSymbol(const GlobalValue *GV) const
MCSymbol * CurrentFnBegin
Definition AsmPrinter.h:246
TargetMachine & TM
Target machine description.
Definition AsmPrinter.h:96
virtual MCSymbol * GetCPISymbol(unsigned CPID) const
Return the symbol for the specified constant pool entry.
MachineFunction * MF
The current machine function.
Definition AsmPrinter.h:111
MCSymbol * GetJTISymbol(unsigned JTID, bool isLinkerPrivate=false) const
Return the symbol for the specified jump table entry.
AsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > Streamer, char &ID=AsmPrinter::ID)
MCSymbol * getSymbolPreferLocal(const GlobalValue &GV) const
Similar to getSymbol() but preferred for references.
MachineModuleInfo * MMI
This is a pointer to the current MachineModuleInfo.
Definition AsmPrinter.h:114
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition AsmPrinter.h:103
MCSymbol * createTempSymbol(const Twine &Name) const
MCSymbol * CurrentPatchableFunctionEntrySym
The symbol for the entry in __patchable_function_entires.
Definition AsmPrinter.h:129
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition AsmPrinter.h:108
const MCAsmInfo & MAI
Target Asm Printer information.
Definition AsmPrinter.h:99
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV) const
MCSymbol * GetBlockAddressSymbol(const BlockAddress *BA) const
Return the MCSymbol used to satisfy BlockAddress uses of the specified basic block.
const MCSubtargetInfo & getSubtargetInfo() const
Return information about subtarget.
std::function< MachineBranchProbabilityInfo *(MachineFunction &)> GetMBPI
Definition AsmPrinter.h:185
This is an important base class in LLVM.
Definition Constant.h:44
Register getReg() const
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:708
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
Definition Function.cpp:778
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
bool hasInternalLinkage() const
bool doesSetDirectiveSuppressReloc() const
Definition MCAsmInfo.h:648
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:339
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:424
MCCodeEmitter - Generic instruction encoding interface.
virtual void encodeInstruction(const MCInst &Inst, SmallVectorImpl< char > &CB, SmallVectorImpl< MCFixup > &Fixups, const MCSubtargetInfo &STI) const =0
Encode the given Inst to bytes and append to CB.
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
LLVM_ABI MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition MCContext.h:550
LLVM_ABI MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
LLVM_ABI const MCTargetOptions & getTargetOptions() const
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:31
MCInstBuilder & addReg(MCRegister Reg)
Add a new register operand.
MCInstBuilder & addExpr(const MCExpr *Val)
Add a new MCExpr operand.
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:187
unsigned getNumOperands() const
Definition MCInst.h:211
unsigned getOpcode() const
Definition MCInst.h:201
iterator insert(iterator I, const MCOperand &Op)
Definition MCInst.h:231
void setFlags(unsigned F)
Definition MCInst.h:203
void addOperand(const MCOperand Op)
Definition MCInst.h:214
iterator begin()
Definition MCInst.h:226
void setOpcode(unsigned Op)
Definition MCInst.h:200
const MCOperand & getOperand(unsigned i) const
Definition MCInst.h:209
static MCOperand createExpr(const MCExpr *Val)
Definition MCInst.h:165
static MCOperand createReg(MCRegister Reg)
Definition MCInst.h:137
static MCOperand createImm(int64_t Val)
Definition MCInst.h:144
MCRegister getReg() const
Returns the register number.
Definition MCInst.h:72
Streaming machine code generation interface.
Definition MCStreamer.h:221
virtual void emitWinCFIUnwindVersion(uint8_t Version, SMLoc Loc=SMLoc())
virtual void emitWinCFIPushReg(MCRegister Register, SMLoc Loc=SMLoc())
virtual void emitBinaryData(StringRef Data)
Functionally identical to EmitBytes.
virtual bool popSection()
Restore the current and previous section from the section stack.
virtual void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI)
Emit the given Instruction into the current section.
void emitSymbolValue(const MCSymbol *Sym, unsigned Size)
Special case of EmitValue that avoids the client having to pass in a MCExpr for MCSymbols.
virtual void emitCodeAlignment(Align Alignment, const MCSubtargetInfo &STI, unsigned MaxBytesToEmit=0)
Emit nops until the byte alignment ByteAlignment is reached.
virtual void emitWinCFIUnwindV2Start(SMLoc Loc=SMLoc())
virtual void emitWinCFIEndEpilogue(SMLoc Loc=SMLoc())
virtual void emitWinCFIPushFrame(bool Code, SMLoc Loc=SMLoc())
virtual void emitWinCFISaveXMM(MCRegister Register, unsigned Offset, SMLoc Loc=SMLoc())
MCContext & getContext() const
Definition MCStreamer.h:329
virtual void AddComment(const Twine &T, bool EOL=true)
Add a textual comment.
Definition MCStreamer.h:407
virtual void emitWinCFIBeginEpilogue(SMLoc Loc=SMLoc())
virtual void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
MCTargetStreamer * getTargetStreamer()
Definition MCStreamer.h:339
virtual void emitWinCFISaveReg(MCRegister Register, unsigned Offset, SMLoc Loc=SMLoc())
virtual void emitWinCFIEndProlog(SMLoc Loc=SMLoc())
void pushSection()
Save the current and previous section on the section stack.
Definition MCStreamer.h:463
virtual void emitWinCFIPush2Regs(MCRegister Reg1, MCRegister Reg2, SMLoc Loc=SMLoc())
virtual void switchSection(MCSection *Section, uint32_t Subsec=0)
Set the current section where code is being emitted to Section.
virtual void emitWinCFISetFrame(MCRegister Register, unsigned Offset, SMLoc Loc=SMLoc())
virtual void emitWinCFIAllocStack(unsigned Size, SMLoc Loc=SMLoc())
MCSection * getCurrentSectionOnly() const
Definition MCStreamer.h:441
virtual void emitBytes(StringRef Data)
Emit the bytes in Data into the output.
Generic base class for all target subtargets.
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:210
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
StringRef getName() const
getName - Get the symbol name.
Definition MCSymbol.h:188
MachineInstrBundleIterator< const MachineInstr > const_iterator
LLVM_ABI MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
LLVM_ABI BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
const WinEHFuncInfo * getWinEHFuncInfo() const
getWinEHFuncInfo - Return information about how the current function uses Windows exception handling.
MCSymbol * getPICBaseSymbol() const
getPICBaseSymbol - Return a function-local symbol to represent the PIC base.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::const_iterator const_iterator
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
mop_range operands()
bool isPseudo(QueryType Type=IgnoreBundle) const
Return true if this is a pseudo instruction that doesn't correspond to a real machine instruction.
const MachineOperand & getOperand(unsigned i) const
bool isEHLabel() const
bool isMetaInstruction(QueryType Type=IgnoreBundle) const
Return true if this instruction doesn't produce any output in the form of executable instructions.
StubValueTy & getGVStubEntry(MCSymbol *Sym)
PointerIntPair< MCSymbol *, 1, bool > StubValueTy
MachineModuleInfoMachO - This is a MachineModuleInfoImpl implementation for MachO targets.
Ty & getObjFileInfo()
Keep track of various per-module pieces of information for backends that would like to do so.
MachineOperand class - Representation of each machine instruction operand.
static MachineOperand CreateMCSymbol(MCSymbol *Sym, unsigned TargetFlags=0)
const GlobalValue * getGlobal() const
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
bool isSymbol() const
isSymbol - Tests if this is a MO_ExternalSymbol operand.
bool isJTI() const
isJTI - Tests if this is a MO_JumpTableIndex operand.
const BlockAddress * getBlockAddress() const
unsigned getTargetFlags() const
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
const char * getSymbolName() const
Register getReg() const
getReg - Returns the register number.
void setTargetFlags(unsigned F)
MCSymbol * getMCSymbol() const
@ MO_Immediate
Immediate operand.
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ MO_MCSymbol
MCSymbol reference (for debug/eh info)
@ MO_GlobalAddress
Address of a global value.
@ MO_RegisterMask
Mask of preserved registers.
@ MO_BlockAddress
Address of a basic block.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_JumpTableIndex
Address of indexed Jump Table for switch.
int64_t getOffset() const
Return the offset from the symbol in this operand.
bool isMBB() const
isMBB - Tests if this is a MO_MachineBasicBlock operand.
LLVM_ABI void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
Definition Mangler.cpp:121
PointerTy getPointer() const
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
const Triple & getTargetTriple() const
CodeModel::Model getCodeModel() const
Returns the code model.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static const char * getRegisterName(MCRegister Reg)
void emitInstruction(const MachineInstr *MI) override
Targets should implement this to emit instructions.
const X86Subtarget & getSubtarget() const
X86AsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > Streamer)
void emitInlineAsmEnd(const MCSubtargetInfo &StartInfo, const MCSubtargetInfo *EndInfo, const MachineInstr *MI) override
Let the target do anything it needs to do after emitting inlineasm.
X86MachineFunctionInfo - This class is derived from MachineFunction and contains private X86 target-s...
unsigned getSlotSize() const
virtual bool emitFPOPushReg(MCRegister Reg, SMLoc L={})
virtual bool emitFPOEndPrologue(SMLoc L={})
virtual bool emitFPOStackAlign(unsigned Align, SMLoc L={})
virtual bool emitFPOSetFrame(MCRegister Reg, SMLoc L={})
virtual bool emitFPOStackAlloc(unsigned StackAlloc, SMLoc L={})
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ SHF_ALLOC
Definition ELF.h:1098
@ SHT_PROGBITS
Definition ELF.h:996
@ Itanium
Windows CE ARM, PowerPC, SH3, SH4.
Definition MCAsmInfo.h:52
bool isKMergeMasked(uint64_t TSFlags)
@ MO_TLSLD
MO_TLSLD - On a symbol operand this indicates that the immediate is the offset of the GOT entry with ...
@ MO_GOTPCREL_NORELAX
MO_GOTPCREL_NORELAX - Same as MO_GOTPCREL except that R_X86_64_GOTPCREL relocations are guaranteed to...
@ MO_GOTOFF
MO_GOTOFF - On a symbol operand this indicates that the immediate is the offset to the location of th...
@ MO_DARWIN_NONLAZY_PIC_BASE
MO_DARWIN_NONLAZY_PIC_BASE - On a symbol operand "FOO", this indicates that the reference is actually...
@ MO_GOT_ABSOLUTE_ADDRESS
MO_GOT_ABSOLUTE_ADDRESS - On a symbol operand, this represents a relocation of: SYMBOL_LABEL + [.
@ MO_COFFSTUB
MO_COFFSTUB - On a symbol operand "FOO", this indicates that the reference is actually to the "....
@ MO_NTPOFF
MO_NTPOFF - On a symbol operand this indicates that the immediate is the negative thread-pointer offs...
@ MO_DARWIN_NONLAZY
MO_DARWIN_NONLAZY - On a symbol operand "FOO", this indicates that the reference is actually to the "...
@ MO_INDNTPOFF
MO_INDNTPOFF - On a symbol operand this indicates that the immediate is the absolute address of the G...
@ MO_GOTNTPOFF
MO_GOTNTPOFF - On a symbol operand this indicates that the immediate is the offset of the GOT entry w...
@ MO_TPOFF
MO_TPOFF - On a symbol operand this indicates that the immediate is the thread-pointer offset for the...
@ MO_TLVP_PIC_BASE
MO_TLVP_PIC_BASE - On a symbol operand this indicates that the immediate is some TLS offset from the ...
@ MO_GOT
MO_GOT - On a symbol operand this indicates that the immediate is the offset to the GOT entry for the...
@ MO_ABS8
MO_ABS8 - On a symbol operand this indicates that the symbol is known to be an absolute symbol in ran...
@ MO_PLT
MO_PLT - On a symbol operand this indicates that the immediate is offset to the PLT entry of symbol n...
@ MO_TLSGD
MO_TLSGD - On a symbol operand this indicates that the immediate is the offset of the GOT entry with ...
@ MO_NO_FLAG
MO_NO_FLAG - No flag for the operand.
@ MO_TLVP
MO_TLVP - On a symbol operand this indicates that the immediate is some TLS offset.
@ MO_DLLIMPORT
MO_DLLIMPORT - On a symbol operand "FOO", this indicates that the reference is actually to the "__imp...
@ MO_GOTTPOFF
MO_GOTTPOFF - On a symbol operand this indicates that the immediate is the offset of the GOT entry wi...
@ MO_SECREL
MO_SECREL - On a symbol operand this indicates that the immediate is the offset from beginning of sec...
@ MO_DTPOFF
MO_DTPOFF - On a symbol operand this indicates that the immediate is the offset of the GOT entry with...
@ MO_PIC_BASE_OFFSET
MO_PIC_BASE_OFFSET - On a symbol operand this indicates that the immediate should get the value of th...
@ MO_TLSLDM
MO_TLSLDM - On a symbol operand this indicates that the immediate is the offset of the GOT entry with...
@ MO_GOTPCREL
MO_GOTPCREL - On a symbol operand this indicates that the immediate is offset to the GOT entry for th...
bool isKMasked(uint64_t TSFlags)
bool isX86_64ExtendedReg(MCRegister Reg)
bool optimizeToFixedRegisterOrShortImmediateForm(MCInst &MI)
@ AddrNumOperands
Definition X86BaseInfo.h:37
bool optimizeMOV(MCInst &MI, bool In64BitMode)
Simplify things like MOV32rm to MOV32o32a.
CondCode GetOppositeBranchCondition(CondCode CC)
GetOppositeBranchCondition - Return the inverse of the specified cond, e.g.
bool optimizeMOVSX(MCInst &MI)
bool optimizeVPCMPWithImmediateOneOrSix(MCInst &MI)
bool optimizeShiftRotateWithImmediateOne(MCInst &MI)
bool optimizeInstFromVEX3ToVEX2(MCInst &MI, const MCInstrDesc &Desc)
uint16_t Specifier
const Constant * getConstantFromPool(const MachineInstr &MI, unsigned OpNo)
Find any constant pool entry associated with a specific instruction operand.
bool optimizeINCDEC(MCInst &MI, bool In64BitMode)
unsigned getVectorRegisterWidth(const MCOperandInfo &Info)
Get the width of the vector register operand.
@ S_GOTPCREL_NORELAX
NodeAddr< CodeNode * > Code
Definition RDFGraph.h:388
This is an optimization pass for GlobalISel generic memory operations.
void DecodeZeroExtendMask(unsigned SrcScalarBits, unsigned DstScalarBits, unsigned NumDstElts, bool IsAnyExtend, SmallVectorImpl< int > &ShuffleMask)
Decode a zero extension instruction as a shuffle mask.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
void DecodeVPERMILPMask(unsigned NumElts, unsigned ScalarBits, ArrayRef< uint64_t > RawMask, const APInt &UndefElts, SmallVectorImpl< int > &ShuffleMask)
Decode a VPERMILPD/VPERMILPS variable mask from a raw array of constants.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
MCRegister getX86SubSuperRegister(MCRegister Reg, unsigned Size, bool High=false)
LLVM_ABI bool isCFGuardFunction(const GlobalValue *GV)
Definition CFGuard.cpp:321
IterT skipMetaInstructionsForward(IterT It, IterT End)
Increment It until it points to a non-meta instruction or to End and return the resulting iterator.
void DecodeVPERMIL2PMask(unsigned NumElts, unsigned ScalarBits, unsigned M2Z, ArrayRef< uint64_t > RawMask, const APInt &UndefElts, SmallVectorImpl< int > &ShuffleMask)
Decode a VPERMIL2PD/VPERMIL2PS variable mask from a raw array of constants.
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
LLVM_ABI void getAddressSanitizerParams(const LLVMContext &Ctx, const Triple &TargetTriple, int LongSize, bool IsKasan, uint64_t *ShadowBase, int *MappingScale, bool *OrShadowOffset)
void DecodeVPPERMMask(ArrayRef< uint64_t > RawMask, const APInt &UndefElts, SmallVectorImpl< int > &ShuffleMask)
Decode a VPPERM mask from a raw array of constants such as from BUILD_VECTOR.
DWARFExpression::Operation Op
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
@ WinEH
Windows Exception Handling.
Definition CodeGen.h:60
@ SM_SentinelUndef
@ SM_SentinelZero
void DecodePSHUFBMask(ArrayRef< uint64_t > RawMask, const APInt &UndefElts, SmallVectorImpl< int > &ShuffleMask)
Decode a PSHUFB mask from a raw array of constants such as from BUILD_VECTOR.
#define N
void changeAndComment(bool b)
NoAutoPaddingScope(MCStreamer &OS)
const bool OldAllowAutoPadding