1 //===-- X86AsmBackend.cpp - X86 Assembler Backend -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MCTargetDesc/X86BaseInfo.h"
11 #include "MCTargetDesc/X86FixupKinds.h"
12 #include "llvm/ADT/StringSwitch.h"
13 #include "llvm/BinaryFormat/ELF.h"
14 #include "llvm/BinaryFormat/MachO.h"
15 #include "llvm/MC/MCAsmBackend.h"
16 #include "llvm/MC/MCELFObjectWriter.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCFixupKindInfo.h"
19 #include "llvm/MC/MCInst.h"
20 #include "llvm/MC/MCMachObjectWriter.h"
21 #include "llvm/MC/MCObjectWriter.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSectionCOFF.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSectionMachO.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/TargetRegistry.h"
29 #include "llvm/Support/raw_ostream.h"
32 static unsigned getFixupKindLog2Size(unsigned Kind) {
35 llvm_unreachable("invalid fixup kind!");
45 case X86::reloc_riprel_4byte:
46 case X86::reloc_riprel_4byte_relax:
47 case X86::reloc_riprel_4byte_relax_rex:
48 case X86::reloc_riprel_4byte_movq_load:
49 case X86::reloc_signed_4byte:
50 case X86::reloc_signed_4byte_relax:
51 case X86::reloc_global_offset_table:
58 case X86::reloc_global_offset_table8:
65 class X86ELFObjectWriter : public MCELFObjectTargetWriter {
67 X86ELFObjectWriter(bool is64Bit, uint8_t OSABI, uint16_t EMachine,
68 bool HasRelocationAddend, bool foobar)
69 : MCELFObjectTargetWriter(is64Bit, OSABI, EMachine, HasRelocationAddend) {}
72 class X86AsmBackend : public MCAsmBackend {
75 const uint64_t MaxNopLength;
77 X86AsmBackend(const Target &T, StringRef CPU)
78 : MCAsmBackend(), CPU(CPU),
79 MaxNopLength((CPU == "slm") ? 7 : 15) {
80 HasNopl = CPU != "generic" && CPU != "i386" && CPU != "i486" &&
81 CPU != "i586" && CPU != "pentium" && CPU != "pentium-mmx" &&
82 CPU != "i686" && CPU != "k6" && CPU != "k6-2" && CPU != "k6-3" &&
83 CPU != "geode" && CPU != "winchip-c6" && CPU != "winchip2" &&
84 CPU != "c3" && CPU != "c3-2" && CPU != "lakemont";
87 unsigned getNumFixupKinds() const override {
88 return X86::NumTargetFixupKinds;
91 const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override {
92 const static MCFixupKindInfo Infos[X86::NumTargetFixupKinds] = {
93 {"reloc_riprel_4byte", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
94 {"reloc_riprel_4byte_movq_load", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
95 {"reloc_riprel_4byte_relax", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
96 {"reloc_riprel_4byte_relax_rex", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
97 {"reloc_signed_4byte", 0, 32, 0},
98 {"reloc_signed_4byte_relax", 0, 32, 0},
99 {"reloc_global_offset_table", 0, 32, 0},
100 {"reloc_global_offset_table8", 0, 64, 0},
103 if (Kind < FirstTargetFixupKind)
104 return MCAsmBackend::getFixupKindInfo(Kind);
106 assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
108 return Infos[Kind - FirstTargetFixupKind];
111 void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
112 const MCValue &Target, MutableArrayRef<char> Data,
113 uint64_t Value, bool IsPCRel) const override {
114 unsigned Size = 1 << getFixupKindLog2Size(Fixup.getKind());
116 assert(Fixup.getOffset() + Size <= Data.size() && "Invalid fixup offset!");
118 // Check that uppper bits are either all zeros or all ones.
119 // Specifically ignore overflow/underflow as long as the leakage is
120 // limited to the lower bits. This is to remain compatible with
122 assert(isIntN(Size * 8 + 1, Value) &&
123 "Value does not fit in the Fixup field");
125 for (unsigned i = 0; i != Size; ++i)
126 Data[Fixup.getOffset() + i] = uint8_t(Value >> (i * 8));
129 bool mayNeedRelaxation(const MCInst &Inst) const override;
131 bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
132 const MCRelaxableFragment *DF,
133 const MCAsmLayout &Layout) const override;
135 void relaxInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
136 MCInst &Res) const override;
138 bool writeNopData(uint64_t Count, MCObjectWriter *OW) const override;
140 } // end anonymous namespace
142 static unsigned getRelaxedOpcodeBranch(const MCInst &Inst, bool is16BitMode) {
143 unsigned Op = Inst.getOpcode();
148 return (is16BitMode) ? X86::JAE_2 : X86::JAE_4;
150 return (is16BitMode) ? X86::JA_2 : X86::JA_4;
152 return (is16BitMode) ? X86::JBE_2 : X86::JBE_4;
154 return (is16BitMode) ? X86::JB_2 : X86::JB_4;
156 return (is16BitMode) ? X86::JE_2 : X86::JE_4;
158 return (is16BitMode) ? X86::JGE_2 : X86::JGE_4;
160 return (is16BitMode) ? X86::JG_2 : X86::JG_4;
162 return (is16BitMode) ? X86::JLE_2 : X86::JLE_4;
164 return (is16BitMode) ? X86::JL_2 : X86::JL_4;
166 return (is16BitMode) ? X86::JMP_2 : X86::JMP_4;
168 return (is16BitMode) ? X86::JNE_2 : X86::JNE_4;
170 return (is16BitMode) ? X86::JNO_2 : X86::JNO_4;
172 return (is16BitMode) ? X86::JNP_2 : X86::JNP_4;
174 return (is16BitMode) ? X86::JNS_2 : X86::JNS_4;
176 return (is16BitMode) ? X86::JO_2 : X86::JO_4;
178 return (is16BitMode) ? X86::JP_2 : X86::JP_4;
180 return (is16BitMode) ? X86::JS_2 : X86::JS_4;
184 static unsigned getRelaxedOpcodeArith(const MCInst &Inst) {
185 unsigned Op = Inst.getOpcode();
191 case X86::IMUL16rri8: return X86::IMUL16rri;
192 case X86::IMUL16rmi8: return X86::IMUL16rmi;
193 case X86::IMUL32rri8: return X86::IMUL32rri;
194 case X86::IMUL32rmi8: return X86::IMUL32rmi;
195 case X86::IMUL64rri8: return X86::IMUL64rri32;
196 case X86::IMUL64rmi8: return X86::IMUL64rmi32;
199 case X86::AND16ri8: return X86::AND16ri;
200 case X86::AND16mi8: return X86::AND16mi;
201 case X86::AND32ri8: return X86::AND32ri;
202 case X86::AND32mi8: return X86::AND32mi;
203 case X86::AND64ri8: return X86::AND64ri32;
204 case X86::AND64mi8: return X86::AND64mi32;
207 case X86::OR16ri8: return X86::OR16ri;
208 case X86::OR16mi8: return X86::OR16mi;
209 case X86::OR32ri8: return X86::OR32ri;
210 case X86::OR32mi8: return X86::OR32mi;
211 case X86::OR64ri8: return X86::OR64ri32;
212 case X86::OR64mi8: return X86::OR64mi32;
215 case X86::XOR16ri8: return X86::XOR16ri;
216 case X86::XOR16mi8: return X86::XOR16mi;
217 case X86::XOR32ri8: return X86::XOR32ri;
218 case X86::XOR32mi8: return X86::XOR32mi;
219 case X86::XOR64ri8: return X86::XOR64ri32;
220 case X86::XOR64mi8: return X86::XOR64mi32;
223 case X86::ADD16ri8: return X86::ADD16ri;
224 case X86::ADD16mi8: return X86::ADD16mi;
225 case X86::ADD32ri8: return X86::ADD32ri;
226 case X86::ADD32mi8: return X86::ADD32mi;
227 case X86::ADD64ri8: return X86::ADD64ri32;
228 case X86::ADD64mi8: return X86::ADD64mi32;
231 case X86::ADC16ri8: return X86::ADC16ri;
232 case X86::ADC16mi8: return X86::ADC16mi;
233 case X86::ADC32ri8: return X86::ADC32ri;
234 case X86::ADC32mi8: return X86::ADC32mi;
235 case X86::ADC64ri8: return X86::ADC64ri32;
236 case X86::ADC64mi8: return X86::ADC64mi32;
239 case X86::SUB16ri8: return X86::SUB16ri;
240 case X86::SUB16mi8: return X86::SUB16mi;
241 case X86::SUB32ri8: return X86::SUB32ri;
242 case X86::SUB32mi8: return X86::SUB32mi;
243 case X86::SUB64ri8: return X86::SUB64ri32;
244 case X86::SUB64mi8: return X86::SUB64mi32;
247 case X86::SBB16ri8: return X86::SBB16ri;
248 case X86::SBB16mi8: return X86::SBB16mi;
249 case X86::SBB32ri8: return X86::SBB32ri;
250 case X86::SBB32mi8: return X86::SBB32mi;
251 case X86::SBB64ri8: return X86::SBB64ri32;
252 case X86::SBB64mi8: return X86::SBB64mi32;
255 case X86::CMP16ri8: return X86::CMP16ri;
256 case X86::CMP16mi8: return X86::CMP16mi;
257 case X86::CMP32ri8: return X86::CMP32ri;
258 case X86::CMP32mi8: return X86::CMP32mi;
259 case X86::CMP64ri8: return X86::CMP64ri32;
260 case X86::CMP64mi8: return X86::CMP64mi32;
263 case X86::PUSH32i8: return X86::PUSHi32;
264 case X86::PUSH16i8: return X86::PUSHi16;
265 case X86::PUSH64i8: return X86::PUSH64i32;
269 static unsigned getRelaxedOpcode(const MCInst &Inst, bool is16BitMode) {
270 unsigned R = getRelaxedOpcodeArith(Inst);
271 if (R != Inst.getOpcode())
273 return getRelaxedOpcodeBranch(Inst, is16BitMode);
276 bool X86AsmBackend::mayNeedRelaxation(const MCInst &Inst) const {
277 // Branches can always be relaxed in either mode.
278 if (getRelaxedOpcodeBranch(Inst, false) != Inst.getOpcode())
281 // Check if this instruction is ever relaxable.
282 if (getRelaxedOpcodeArith(Inst) == Inst.getOpcode())
286 // Check if the relaxable operand has an expression. For the current set of
287 // relaxable instructions, the relaxable operand is always the last operand.
288 unsigned RelaxableOp = Inst.getNumOperands() - 1;
289 if (Inst.getOperand(RelaxableOp).isExpr())
295 bool X86AsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
297 const MCRelaxableFragment *DF,
298 const MCAsmLayout &Layout) const {
299 // Relax if the value is too big for a (signed) i8.
300 return int64_t(Value) != int64_t(int8_t(Value));
303 // FIXME: Can tblgen help at all here to verify there aren't other instructions
305 void X86AsmBackend::relaxInstruction(const MCInst &Inst,
306 const MCSubtargetInfo &STI,
308 // The only relaxations X86 does is from a 1byte pcrel to a 4byte pcrel.
309 bool is16BitMode = STI.getFeatureBits()[X86::Mode16Bit];
310 unsigned RelaxedOp = getRelaxedOpcode(Inst, is16BitMode);
312 if (RelaxedOp == Inst.getOpcode()) {
313 SmallString<256> Tmp;
314 raw_svector_ostream OS(Tmp);
315 Inst.dump_pretty(OS);
317 report_fatal_error("unexpected instruction to relax: " + OS.str());
321 Res.setOpcode(RelaxedOp);
324 /// \brief Write a sequence of optimal nops to the output, covering \p Count
326 /// \return - true on success, false on failure
327 bool X86AsmBackend::writeNopData(uint64_t Count, MCObjectWriter *OW) const {
328 static const uint8_t Nops[10][10] = {
336 {0x0f, 0x1f, 0x40, 0x00},
337 // nopl 0(%[re]ax,%[re]ax,1)
338 {0x0f, 0x1f, 0x44, 0x00, 0x00},
339 // nopw 0(%[re]ax,%[re]ax,1)
340 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
342 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
343 // nopl 0L(%[re]ax,%[re]ax,1)
344 {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
345 // nopw 0L(%[re]ax,%[re]ax,1)
346 {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
347 // nopw %cs:0L(%[re]ax,%[re]ax,1)
348 {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
351 // This CPU doesn't support long nops. If needed add more.
352 // FIXME: Can we get this from the subtarget somehow?
353 // FIXME: We could generated something better than plain 0x90.
355 for (uint64_t i = 0; i < Count; ++i)
360 // 15 is the longest single nop instruction. Emit as many 15-byte nops as
361 // needed, then emit a nop of the remaining length.
363 const uint8_t ThisNopLength = (uint8_t) std::min(Count, MaxNopLength);
364 const uint8_t Prefixes = ThisNopLength <= 10 ? 0 : ThisNopLength - 10;
365 for (uint8_t i = 0; i < Prefixes; i++)
367 const uint8_t Rest = ThisNopLength - Prefixes;
368 for (uint8_t i = 0; i < Rest; i++)
369 OW->write8(Nops[Rest - 1][i]);
370 Count -= ThisNopLength;
371 } while (Count != 0);
380 class ELFX86AsmBackend : public X86AsmBackend {
383 ELFX86AsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
384 : X86AsmBackend(T, CPU), OSABI(OSABI) {}
387 class ELFX86_32AsmBackend : public ELFX86AsmBackend {
389 ELFX86_32AsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
390 : ELFX86AsmBackend(T, OSABI, CPU) {}
392 MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
393 return createX86ELFObjectWriter(OS, /*IsELF64*/ false, OSABI, ELF::EM_386);
397 class ELFX86_X32AsmBackend : public ELFX86AsmBackend {
399 ELFX86_X32AsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
400 : ELFX86AsmBackend(T, OSABI, CPU) {}
402 MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
403 return createX86ELFObjectWriter(OS, /*IsELF64*/ false, OSABI,
408 class ELFX86_IAMCUAsmBackend : public ELFX86AsmBackend {
410 ELFX86_IAMCUAsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
411 : ELFX86AsmBackend(T, OSABI, CPU) {}
413 MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
414 return createX86ELFObjectWriter(OS, /*IsELF64*/ false, OSABI,
419 class ELFX86_64AsmBackend : public ELFX86AsmBackend {
421 ELFX86_64AsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
422 : ELFX86AsmBackend(T, OSABI, CPU) {}
424 MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
425 return createX86ELFObjectWriter(OS, /*IsELF64*/ true, OSABI, ELF::EM_X86_64);
429 class WindowsX86AsmBackend : public X86AsmBackend {
433 WindowsX86AsmBackend(const Target &T, bool is64Bit, StringRef CPU)
434 : X86AsmBackend(T, CPU)
438 Optional<MCFixupKind> getFixupKind(StringRef Name) const override {
439 return StringSwitch<Optional<MCFixupKind>>(Name)
440 .Case("dir32", FK_Data_4)
441 .Case("secrel32", FK_SecRel_4)
442 .Case("secidx", FK_SecRel_2)
443 .Default(MCAsmBackend::getFixupKind(Name));
446 MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
447 return createX86WinCOFFObjectWriter(OS, Is64Bit);
453 /// Compact unwind encoding values.
454 enum CompactUnwindEncodings {
455 /// [RE]BP based frame where [RE]BP is pused on the stack immediately after
456 /// the return address, then [RE]SP is moved to [RE]BP.
457 UNWIND_MODE_BP_FRAME = 0x01000000,
459 /// A frameless function with a small constant stack size.
460 UNWIND_MODE_STACK_IMMD = 0x02000000,
462 /// A frameless function with a large constant stack size.
463 UNWIND_MODE_STACK_IND = 0x03000000,
465 /// No compact unwind encoding is available.
466 UNWIND_MODE_DWARF = 0x04000000,
468 /// Mask for encoding the frame registers.
469 UNWIND_BP_FRAME_REGISTERS = 0x00007FFF,
471 /// Mask for encoding the frameless registers.
472 UNWIND_FRAMELESS_STACK_REG_PERMUTATION = 0x000003FF
475 } // end CU namespace
477 class DarwinX86AsmBackend : public X86AsmBackend {
478 const MCRegisterInfo &MRI;
480 /// \brief Number of registers that can be saved in a compact unwind encoding.
481 enum { CU_NUM_SAVED_REGS = 6 };
483 mutable unsigned SavedRegs[CU_NUM_SAVED_REGS];
486 unsigned OffsetSize; ///< Offset of a "push" instruction.
487 unsigned MoveInstrSize; ///< Size of a "move" instruction.
488 unsigned StackDivide; ///< Amount to adjust stack size by.
490 /// \brief Size of a "push" instruction for the given register.
491 unsigned PushInstrSize(unsigned Reg) const {
511 /// \brief Implementation of algorithm to generate the compact unwind encoding
512 /// for the CFI instructions.
514 generateCompactUnwindEncodingImpl(ArrayRef<MCCFIInstruction> Instrs) const {
515 if (Instrs.empty()) return 0;
517 // Reset the saved registers.
518 unsigned SavedRegIdx = 0;
519 memset(SavedRegs, 0, sizeof(SavedRegs));
523 // Encode that we are using EBP/RBP as the frame pointer.
524 uint32_t CompactUnwindEncoding = 0;
526 unsigned SubtractInstrIdx = Is64Bit ? 3 : 2;
527 unsigned InstrOffset = 0;
528 unsigned StackAdjust = 0;
529 unsigned StackSize = 0;
530 unsigned PrevStackSize = 0;
531 unsigned NumDefCFAOffsets = 0;
533 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
534 const MCCFIInstruction &Inst = Instrs[i];
536 switch (Inst.getOperation()) {
538 // Any other CFI directives indicate a frame that we aren't prepared
539 // to represent via compact unwind, so just bail out.
541 case MCCFIInstruction::OpDefCfaRegister: {
542 // Defines a frame pointer. E.g.
546 // .cfi_def_cfa_register %rbp
550 // If the frame pointer is other than esp/rsp, we do not have a way to
551 // generate a compact unwinding representation, so bail out.
552 if (MRI.getLLVMRegNum(Inst.getRegister(), true) !=
553 (Is64Bit ? X86::RBP : X86::EBP))
557 memset(SavedRegs, 0, sizeof(SavedRegs));
560 InstrOffset += MoveInstrSize;
563 case MCCFIInstruction::OpDefCfaOffset: {
564 // Defines a new offset for the CFA. E.g.
570 // .cfi_def_cfa_offset 16
576 // .cfi_def_cfa_offset 80
578 PrevStackSize = StackSize;
579 StackSize = std::abs(Inst.getOffset()) / StackDivide;
583 case MCCFIInstruction::OpOffset: {
584 // Defines a "push" of a callee-saved register. E.g.
592 // .cfi_offset %rbx, -40
593 // .cfi_offset %r14, -32
594 // .cfi_offset %r15, -24
596 if (SavedRegIdx == CU_NUM_SAVED_REGS)
597 // If there are too many saved registers, we cannot use a compact
599 return CU::UNWIND_MODE_DWARF;
601 unsigned Reg = MRI.getLLVMRegNum(Inst.getRegister(), true);
602 SavedRegs[SavedRegIdx++] = Reg;
603 StackAdjust += OffsetSize;
604 InstrOffset += PushInstrSize(Reg);
610 StackAdjust /= StackDivide;
613 if ((StackAdjust & 0xFF) != StackAdjust)
614 // Offset was too big for a compact unwind encoding.
615 return CU::UNWIND_MODE_DWARF;
617 // Get the encoding of the saved registers when we have a frame pointer.
618 uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame();
619 if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
621 CompactUnwindEncoding |= CU::UNWIND_MODE_BP_FRAME;
622 CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16;
623 CompactUnwindEncoding |= RegEnc & CU::UNWIND_BP_FRAME_REGISTERS;
625 // If the amount of the stack allocation is the size of a register, then
626 // we "push" the RAX/EAX register onto the stack instead of adjusting the
627 // stack pointer with a SUB instruction. We don't support the push of the
628 // RAX/EAX register with compact unwind. So we check for that situation
630 if ((NumDefCFAOffsets == SavedRegIdx + 1 &&
631 StackSize - PrevStackSize == 1) ||
632 (Instrs.size() == 1 && NumDefCFAOffsets == 1 && StackSize == 2))
633 return CU::UNWIND_MODE_DWARF;
635 SubtractInstrIdx += InstrOffset;
638 if ((StackSize & 0xFF) == StackSize) {
639 // Frameless stack with a small stack size.
640 CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IMMD;
642 // Encode the stack size.
643 CompactUnwindEncoding |= (StackSize & 0xFF) << 16;
645 if ((StackAdjust & 0x7) != StackAdjust)
646 // The extra stack adjustments are too big for us to handle.
647 return CU::UNWIND_MODE_DWARF;
649 // Frameless stack with an offset too large for us to encode compactly.
650 CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IND;
652 // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
654 CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
656 // Encode any extra stack stack adjustments (done via push
658 CompactUnwindEncoding |= (StackAdjust & 0x7) << 13;
661 // Encode the number of registers saved. (Reverse the list first.)
662 std::reverse(&SavedRegs[0], &SavedRegs[SavedRegIdx]);
663 CompactUnwindEncoding |= (SavedRegIdx & 0x7) << 10;
665 // Get the encoding of the saved registers when we don't have a frame
667 uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegIdx);
668 if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
670 // Encode the register encoding.
671 CompactUnwindEncoding |=
672 RegEnc & CU::UNWIND_FRAMELESS_STACK_REG_PERMUTATION;
675 return CompactUnwindEncoding;
679 /// \brief Get the compact unwind number for a given register. The number
680 /// corresponds to the enum lists in compact_unwind_encoding.h.
681 int getCompactUnwindRegNum(unsigned Reg) const {
682 static const MCPhysReg CU32BitRegs[7] = {
683 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
685 static const MCPhysReg CU64BitRegs[] = {
686 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
688 const MCPhysReg *CURegs = Is64Bit ? CU64BitRegs : CU32BitRegs;
689 for (int Idx = 1; *CURegs; ++CURegs, ++Idx)
696 /// \brief Return the registers encoded for a compact encoding with a frame
698 uint32_t encodeCompactUnwindRegistersWithFrame() const {
699 // Encode the registers in the order they were saved --- 3-bits per
700 // register. The list of saved registers is assumed to be in reverse
701 // order. The registers are numbered from 1 to CU_NUM_SAVED_REGS.
703 for (int i = 0, Idx = 0; i != CU_NUM_SAVED_REGS; ++i) {
704 unsigned Reg = SavedRegs[i];
707 int CURegNum = getCompactUnwindRegNum(Reg);
708 if (CURegNum == -1) return ~0U;
710 // Encode the 3-bit register number in order, skipping over 3-bits for
712 RegEnc |= (CURegNum & 0x7) << (Idx++ * 3);
715 assert((RegEnc & 0x3FFFF) == RegEnc &&
716 "Invalid compact register encoding!");
720 /// \brief Create the permutation encoding used with frameless stacks. It is
721 /// passed the number of registers to be saved and an array of the registers
723 uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned RegCount) const {
724 // The saved registers are numbered from 1 to 6. In order to encode the
725 // order in which they were saved, we re-number them according to their
726 // place in the register order. The re-numbering is relative to the last
727 // re-numbered register. E.g., if we have registers {6, 2, 4, 5} saved in
737 for (unsigned i = 0; i < RegCount; ++i) {
738 int CUReg = getCompactUnwindRegNum(SavedRegs[i]);
739 if (CUReg == -1) return ~0U;
740 SavedRegs[i] = CUReg;
744 std::reverse(&SavedRegs[0], &SavedRegs[CU_NUM_SAVED_REGS]);
746 uint32_t RenumRegs[CU_NUM_SAVED_REGS];
747 for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i){
748 unsigned Countless = 0;
749 for (unsigned j = CU_NUM_SAVED_REGS - RegCount; j < i; ++j)
750 if (SavedRegs[j] < SavedRegs[i])
753 RenumRegs[i] = SavedRegs[i] - Countless - 1;
756 // Take the renumbered values and encode them into a 10-bit number.
757 uint32_t permutationEncoding = 0;
760 permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
761 + 6 * RenumRegs[2] + 2 * RenumRegs[3]
765 permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
766 + 6 * RenumRegs[3] + 2 * RenumRegs[4]
770 permutationEncoding |= 60 * RenumRegs[2] + 12 * RenumRegs[3]
771 + 3 * RenumRegs[4] + RenumRegs[5];
774 permutationEncoding |= 20 * RenumRegs[3] + 4 * RenumRegs[4]
778 permutationEncoding |= 5 * RenumRegs[4] + RenumRegs[5];
781 permutationEncoding |= RenumRegs[5];
785 assert((permutationEncoding & 0x3FF) == permutationEncoding &&
786 "Invalid compact register encoding!");
787 return permutationEncoding;
791 DarwinX86AsmBackend(const Target &T, const MCRegisterInfo &MRI, StringRef CPU,
793 : X86AsmBackend(T, CPU), MRI(MRI), Is64Bit(Is64Bit) {
794 memset(SavedRegs, 0, sizeof(SavedRegs));
795 OffsetSize = Is64Bit ? 8 : 4;
796 MoveInstrSize = Is64Bit ? 3 : 2;
797 StackDivide = Is64Bit ? 8 : 4;
801 class DarwinX86_32AsmBackend : public DarwinX86AsmBackend {
803 DarwinX86_32AsmBackend(const Target &T, const MCRegisterInfo &MRI,
805 : DarwinX86AsmBackend(T, MRI, CPU, false) {}
807 MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
808 return createX86MachObjectWriter(OS, /*Is64Bit=*/false,
809 MachO::CPU_TYPE_I386,
810 MachO::CPU_SUBTYPE_I386_ALL);
813 /// \brief Generate the compact unwind encoding for the CFI instructions.
814 uint32_t generateCompactUnwindEncoding(
815 ArrayRef<MCCFIInstruction> Instrs) const override {
816 return generateCompactUnwindEncodingImpl(Instrs);
820 class DarwinX86_64AsmBackend : public DarwinX86AsmBackend {
821 const MachO::CPUSubTypeX86 Subtype;
823 DarwinX86_64AsmBackend(const Target &T, const MCRegisterInfo &MRI,
824 StringRef CPU, MachO::CPUSubTypeX86 st)
825 : DarwinX86AsmBackend(T, MRI, CPU, true), Subtype(st) {}
827 MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
828 return createX86MachObjectWriter(OS, /*Is64Bit=*/true,
829 MachO::CPU_TYPE_X86_64, Subtype);
832 /// \brief Generate the compact unwind encoding for the CFI instructions.
833 uint32_t generateCompactUnwindEncoding(
834 ArrayRef<MCCFIInstruction> Instrs) const override {
835 return generateCompactUnwindEncodingImpl(Instrs);
839 } // end anonymous namespace
841 MCAsmBackend *llvm::createX86_32AsmBackend(const Target &T,
842 const MCRegisterInfo &MRI,
843 const Triple &TheTriple,
845 const MCTargetOptions &Options) {
846 if (TheTriple.isOSBinFormatMachO())
847 return new DarwinX86_32AsmBackend(T, MRI, CPU);
849 if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
850 return new WindowsX86AsmBackend(T, false, CPU);
852 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
854 if (TheTriple.isOSIAMCU())
855 return new ELFX86_IAMCUAsmBackend(T, OSABI, CPU);
857 return new ELFX86_32AsmBackend(T, OSABI, CPU);
860 MCAsmBackend *llvm::createX86_64AsmBackend(const Target &T,
861 const MCRegisterInfo &MRI,
862 const Triple &TheTriple,
864 const MCTargetOptions &Options) {
865 if (TheTriple.isOSBinFormatMachO()) {
866 MachO::CPUSubTypeX86 CS =
867 StringSwitch<MachO::CPUSubTypeX86>(TheTriple.getArchName())
868 .Case("x86_64h", MachO::CPU_SUBTYPE_X86_64_H)
869 .Default(MachO::CPU_SUBTYPE_X86_64_ALL);
870 return new DarwinX86_64AsmBackend(T, MRI, CPU, CS);
873 if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
874 return new WindowsX86AsmBackend(T, true, CPU);
876 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
878 if (TheTriple.getEnvironment() == Triple::GNUX32)
879 return new ELFX86_X32AsmBackend(T, OSABI, CPU);
880 return new ELFX86_64AsmBackend(T, OSABI, CPU);