1 //===-- X86AsmBackend.cpp - X86 Assembler Backend -------------------------===//
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 #include "MCTargetDesc/X86BaseInfo.h"
10 #include "MCTargetDesc/X86FixupKinds.h"
11 #include "llvm/ADT/StringSwitch.h"
12 #include "llvm/BinaryFormat/ELF.h"
13 #include "llvm/BinaryFormat/MachO.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCDwarf.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/MCSectionMachO.h"
24 #include "llvm/MC/MCSubtargetInfo.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 using namespace llvm;
28 
29 static unsigned getFixupKindLog2Size(unsigned Kind) {
30   switch (Kind) {
31   default:
32     llvm_unreachable("invalid fixup kind!");
33   case FK_PCRel_1:
34   case FK_SecRel_1:
35   case FK_Data_1:
36     return 0;
37   case FK_PCRel_2:
38   case FK_SecRel_2:
39   case FK_Data_2:
40     return 1;
41   case FK_PCRel_4:
42   case X86::reloc_riprel_4byte:
43   case X86::reloc_riprel_4byte_relax:
44   case X86::reloc_riprel_4byte_relax_rex:
45   case X86::reloc_riprel_4byte_movq_load:
46   case X86::reloc_signed_4byte:
47   case X86::reloc_signed_4byte_relax:
48   case X86::reloc_global_offset_table:
49   case X86::reloc_branch_4byte_pcrel:
50   case FK_SecRel_4:
51   case FK_Data_4:
52     return 2;
53   case FK_PCRel_8:
54   case FK_SecRel_8:
55   case FK_Data_8:
56   case X86::reloc_global_offset_table8:
57     return 3;
58   }
59 }
60 
61 namespace {
62 
63 class X86ELFObjectWriter : public MCELFObjectTargetWriter {
64 public:
65   X86ELFObjectWriter(bool is64Bit, uint8_t OSABI, uint16_t EMachine,
66                      bool HasRelocationAddend, bool foobar)
67     : MCELFObjectTargetWriter(is64Bit, OSABI, EMachine, HasRelocationAddend) {}
68 };
69 
70 class X86AsmBackend : public MCAsmBackend {
71   const MCSubtargetInfo &STI;
72 public:
73   X86AsmBackend(const Target &T, const MCSubtargetInfo &STI)
74       : MCAsmBackend(support::little), STI(STI) {}
75 
76   unsigned getNumFixupKinds() const override {
77     return X86::NumTargetFixupKinds;
78   }
79 
80   const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override {
81     const static MCFixupKindInfo Infos[X86::NumTargetFixupKinds] = {
82         {"reloc_riprel_4byte", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
83         {"reloc_riprel_4byte_movq_load", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
84         {"reloc_riprel_4byte_relax", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
85         {"reloc_riprel_4byte_relax_rex", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
86         {"reloc_signed_4byte", 0, 32, 0},
87         {"reloc_signed_4byte_relax", 0, 32, 0},
88         {"reloc_global_offset_table", 0, 32, 0},
89         {"reloc_global_offset_table8", 0, 64, 0},
90         {"reloc_branch_4byte_pcrel", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
91     };
92 
93     if (Kind < FirstTargetFixupKind)
94       return MCAsmBackend::getFixupKindInfo(Kind);
95 
96     assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
97            "Invalid kind!");
98     assert(Infos[Kind - FirstTargetFixupKind].Name && "Empty fixup name!");
99     return Infos[Kind - FirstTargetFixupKind];
100   }
101 
102   void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
103                   const MCValue &Target, MutableArrayRef<char> Data,
104                   uint64_t Value, bool IsResolved,
105                   const MCSubtargetInfo *STI) const override {
106     unsigned Size = 1 << getFixupKindLog2Size(Fixup.getKind());
107 
108     assert(Fixup.getOffset() + Size <= Data.size() && "Invalid fixup offset!");
109 
110     // Check that uppper bits are either all zeros or all ones.
111     // Specifically ignore overflow/underflow as long as the leakage is
112     // limited to the lower bits. This is to remain compatible with
113     // other assemblers.
114     assert(isIntN(Size * 8 + 1, Value) &&
115            "Value does not fit in the Fixup field");
116 
117     for (unsigned i = 0; i != Size; ++i)
118       Data[Fixup.getOffset() + i] = uint8_t(Value >> (i * 8));
119   }
120 
121   bool mayNeedRelaxation(const MCInst &Inst,
122                          const MCSubtargetInfo &STI) const override;
123 
124   bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
125                             const MCRelaxableFragment *DF,
126                             const MCAsmLayout &Layout) const override;
127 
128   void relaxInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
129                         MCInst &Res) const override;
130 
131   bool writeNopData(raw_ostream &OS, uint64_t Count) const override;
132 };
133 } // end anonymous namespace
134 
135 static unsigned getRelaxedOpcodeBranch(const MCInst &Inst, bool is16BitMode) {
136   unsigned Op = Inst.getOpcode();
137   switch (Op) {
138   default:
139     return Op;
140   case X86::JCC_1:
141     return (is16BitMode) ? X86::JCC_2 : X86::JCC_4;
142   case X86::JMP_1:
143     return (is16BitMode) ? X86::JMP_2 : X86::JMP_4;
144   }
145 }
146 
147 static unsigned getRelaxedOpcodeArith(const MCInst &Inst) {
148   unsigned Op = Inst.getOpcode();
149   switch (Op) {
150   default:
151     return Op;
152 
153     // IMUL
154   case X86::IMUL16rri8: return X86::IMUL16rri;
155   case X86::IMUL16rmi8: return X86::IMUL16rmi;
156   case X86::IMUL32rri8: return X86::IMUL32rri;
157   case X86::IMUL32rmi8: return X86::IMUL32rmi;
158   case X86::IMUL64rri8: return X86::IMUL64rri32;
159   case X86::IMUL64rmi8: return X86::IMUL64rmi32;
160 
161     // AND
162   case X86::AND16ri8: return X86::AND16ri;
163   case X86::AND16mi8: return X86::AND16mi;
164   case X86::AND32ri8: return X86::AND32ri;
165   case X86::AND32mi8: return X86::AND32mi;
166   case X86::AND64ri8: return X86::AND64ri32;
167   case X86::AND64mi8: return X86::AND64mi32;
168 
169     // OR
170   case X86::OR16ri8: return X86::OR16ri;
171   case X86::OR16mi8: return X86::OR16mi;
172   case X86::OR32ri8: return X86::OR32ri;
173   case X86::OR32mi8: return X86::OR32mi;
174   case X86::OR64ri8: return X86::OR64ri32;
175   case X86::OR64mi8: return X86::OR64mi32;
176 
177     // XOR
178   case X86::XOR16ri8: return X86::XOR16ri;
179   case X86::XOR16mi8: return X86::XOR16mi;
180   case X86::XOR32ri8: return X86::XOR32ri;
181   case X86::XOR32mi8: return X86::XOR32mi;
182   case X86::XOR64ri8: return X86::XOR64ri32;
183   case X86::XOR64mi8: return X86::XOR64mi32;
184 
185     // ADD
186   case X86::ADD16ri8: return X86::ADD16ri;
187   case X86::ADD16mi8: return X86::ADD16mi;
188   case X86::ADD32ri8: return X86::ADD32ri;
189   case X86::ADD32mi8: return X86::ADD32mi;
190   case X86::ADD64ri8: return X86::ADD64ri32;
191   case X86::ADD64mi8: return X86::ADD64mi32;
192 
193    // ADC
194   case X86::ADC16ri8: return X86::ADC16ri;
195   case X86::ADC16mi8: return X86::ADC16mi;
196   case X86::ADC32ri8: return X86::ADC32ri;
197   case X86::ADC32mi8: return X86::ADC32mi;
198   case X86::ADC64ri8: return X86::ADC64ri32;
199   case X86::ADC64mi8: return X86::ADC64mi32;
200 
201     // SUB
202   case X86::SUB16ri8: return X86::SUB16ri;
203   case X86::SUB16mi8: return X86::SUB16mi;
204   case X86::SUB32ri8: return X86::SUB32ri;
205   case X86::SUB32mi8: return X86::SUB32mi;
206   case X86::SUB64ri8: return X86::SUB64ri32;
207   case X86::SUB64mi8: return X86::SUB64mi32;
208 
209    // SBB
210   case X86::SBB16ri8: return X86::SBB16ri;
211   case X86::SBB16mi8: return X86::SBB16mi;
212   case X86::SBB32ri8: return X86::SBB32ri;
213   case X86::SBB32mi8: return X86::SBB32mi;
214   case X86::SBB64ri8: return X86::SBB64ri32;
215   case X86::SBB64mi8: return X86::SBB64mi32;
216 
217     // CMP
218   case X86::CMP16ri8: return X86::CMP16ri;
219   case X86::CMP16mi8: return X86::CMP16mi;
220   case X86::CMP32ri8: return X86::CMP32ri;
221   case X86::CMP32mi8: return X86::CMP32mi;
222   case X86::CMP64ri8: return X86::CMP64ri32;
223   case X86::CMP64mi8: return X86::CMP64mi32;
224 
225     // PUSH
226   case X86::PUSH32i8:  return X86::PUSHi32;
227   case X86::PUSH16i8:  return X86::PUSHi16;
228   case X86::PUSH64i8:  return X86::PUSH64i32;
229   }
230 }
231 
232 static unsigned getRelaxedOpcode(const MCInst &Inst, bool is16BitMode) {
233   unsigned R = getRelaxedOpcodeArith(Inst);
234   if (R != Inst.getOpcode())
235     return R;
236   return getRelaxedOpcodeBranch(Inst, is16BitMode);
237 }
238 
239 bool X86AsmBackend::mayNeedRelaxation(const MCInst &Inst,
240                                       const MCSubtargetInfo &STI) const {
241   // Branches can always be relaxed in either mode.
242   if (getRelaxedOpcodeBranch(Inst, false) != Inst.getOpcode())
243     return true;
244 
245   // Check if this instruction is ever relaxable.
246   if (getRelaxedOpcodeArith(Inst) == Inst.getOpcode())
247     return false;
248 
249 
250   // Check if the relaxable operand has an expression. For the current set of
251   // relaxable instructions, the relaxable operand is always the last operand.
252   unsigned RelaxableOp = Inst.getNumOperands() - 1;
253   if (Inst.getOperand(RelaxableOp).isExpr())
254     return true;
255 
256   return false;
257 }
258 
259 bool X86AsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
260                                          uint64_t Value,
261                                          const MCRelaxableFragment *DF,
262                                          const MCAsmLayout &Layout) const {
263   // Relax if the value is too big for a (signed) i8.
264   return int64_t(Value) != int64_t(int8_t(Value));
265 }
266 
267 // FIXME: Can tblgen help at all here to verify there aren't other instructions
268 // we can relax?
269 void X86AsmBackend::relaxInstruction(const MCInst &Inst,
270                                      const MCSubtargetInfo &STI,
271                                      MCInst &Res) const {
272   // The only relaxations X86 does is from a 1byte pcrel to a 4byte pcrel.
273   bool is16BitMode = STI.getFeatureBits()[X86::Mode16Bit];
274   unsigned RelaxedOp = getRelaxedOpcode(Inst, is16BitMode);
275 
276   if (RelaxedOp == Inst.getOpcode()) {
277     SmallString<256> Tmp;
278     raw_svector_ostream OS(Tmp);
279     Inst.dump_pretty(OS);
280     OS << "\n";
281     report_fatal_error("unexpected instruction to relax: " + OS.str());
282   }
283 
284   Res = Inst;
285   Res.setOpcode(RelaxedOp);
286 }
287 
288 /// Write a sequence of optimal nops to the output, covering \p Count
289 /// bytes.
290 /// \return - true on success, false on failure
291 bool X86AsmBackend::writeNopData(raw_ostream &OS, uint64_t Count) const {
292   static const char Nops[10][11] = {
293     // nop
294     "\x90",
295     // xchg %ax,%ax
296     "\x66\x90",
297     // nopl (%[re]ax)
298     "\x0f\x1f\x00",
299     // nopl 0(%[re]ax)
300     "\x0f\x1f\x40\x00",
301     // nopl 0(%[re]ax,%[re]ax,1)
302     "\x0f\x1f\x44\x00\x00",
303     // nopw 0(%[re]ax,%[re]ax,1)
304     "\x66\x0f\x1f\x44\x00\x00",
305     // nopl 0L(%[re]ax)
306     "\x0f\x1f\x80\x00\x00\x00\x00",
307     // nopl 0L(%[re]ax,%[re]ax,1)
308     "\x0f\x1f\x84\x00\x00\x00\x00\x00",
309     // nopw 0L(%[re]ax,%[re]ax,1)
310     "\x66\x0f\x1f\x84\x00\x00\x00\x00\x00",
311     // nopw %cs:0L(%[re]ax,%[re]ax,1)
312     "\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00",
313   };
314 
315   // This CPU doesn't support long nops. If needed add more.
316   // FIXME: We could generated something better than plain 0x90.
317   if (!STI.getFeatureBits()[X86::FeatureNOPL]) {
318     for (uint64_t i = 0; i < Count; ++i)
319       OS << '\x90';
320     return true;
321   }
322 
323   // 15-bytes is the longest single NOP instruction, but 10-bytes is
324   // commonly the longest that can be efficiently decoded.
325   uint64_t MaxNopLength = 10;
326   if (STI.getFeatureBits()[X86::ProcIntelSLM])
327     MaxNopLength = 7;
328   else if (STI.getFeatureBits()[X86::FeatureFast15ByteNOP])
329     MaxNopLength = 15;
330   else if (STI.getFeatureBits()[X86::FeatureFast11ByteNOP])
331     MaxNopLength = 11;
332 
333   // Emit as many MaxNopLength NOPs as needed, then emit a NOP of the remaining
334   // length.
335   do {
336     const uint8_t ThisNopLength = (uint8_t) std::min(Count, MaxNopLength);
337     const uint8_t Prefixes = ThisNopLength <= 10 ? 0 : ThisNopLength - 10;
338     for (uint8_t i = 0; i < Prefixes; i++)
339       OS << '\x66';
340     const uint8_t Rest = ThisNopLength - Prefixes;
341     if (Rest != 0)
342       OS.write(Nops[Rest - 1], Rest);
343     Count -= ThisNopLength;
344   } while (Count != 0);
345 
346   return true;
347 }
348 
349 /* *** */
350 
351 namespace {
352 
353 class ELFX86AsmBackend : public X86AsmBackend {
354 public:
355   uint8_t OSABI;
356   ELFX86AsmBackend(const Target &T, uint8_t OSABI, const MCSubtargetInfo &STI)
357       : X86AsmBackend(T, STI), OSABI(OSABI) {}
358 };
359 
360 class ELFX86_32AsmBackend : public ELFX86AsmBackend {
361 public:
362   ELFX86_32AsmBackend(const Target &T, uint8_t OSABI,
363                       const MCSubtargetInfo &STI)
364     : ELFX86AsmBackend(T, OSABI, STI) {}
365 
366   std::unique_ptr<MCObjectTargetWriter>
367   createObjectTargetWriter() const override {
368     return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI, ELF::EM_386);
369   }
370 };
371 
372 class ELFX86_X32AsmBackend : public ELFX86AsmBackend {
373 public:
374   ELFX86_X32AsmBackend(const Target &T, uint8_t OSABI,
375                        const MCSubtargetInfo &STI)
376       : ELFX86AsmBackend(T, OSABI, STI) {}
377 
378   std::unique_ptr<MCObjectTargetWriter>
379   createObjectTargetWriter() const override {
380     return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI,
381                                     ELF::EM_X86_64);
382   }
383 };
384 
385 class ELFX86_IAMCUAsmBackend : public ELFX86AsmBackend {
386 public:
387   ELFX86_IAMCUAsmBackend(const Target &T, uint8_t OSABI,
388                          const MCSubtargetInfo &STI)
389       : ELFX86AsmBackend(T, OSABI, STI) {}
390 
391   std::unique_ptr<MCObjectTargetWriter>
392   createObjectTargetWriter() const override {
393     return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI,
394                                     ELF::EM_IAMCU);
395   }
396 };
397 
398 class ELFX86_64AsmBackend : public ELFX86AsmBackend {
399 public:
400   ELFX86_64AsmBackend(const Target &T, uint8_t OSABI,
401                       const MCSubtargetInfo &STI)
402     : ELFX86AsmBackend(T, OSABI, STI) {}
403 
404   std::unique_ptr<MCObjectTargetWriter>
405   createObjectTargetWriter() const override {
406     return createX86ELFObjectWriter(/*IsELF64*/ true, OSABI, ELF::EM_X86_64);
407   }
408 };
409 
410 class WindowsX86AsmBackend : public X86AsmBackend {
411   bool Is64Bit;
412 
413 public:
414   WindowsX86AsmBackend(const Target &T, bool is64Bit,
415                        const MCSubtargetInfo &STI)
416     : X86AsmBackend(T, STI)
417     , Is64Bit(is64Bit) {
418   }
419 
420   Optional<MCFixupKind> getFixupKind(StringRef Name) const override {
421     return StringSwitch<Optional<MCFixupKind>>(Name)
422         .Case("dir32", FK_Data_4)
423         .Case("secrel32", FK_SecRel_4)
424         .Case("secidx", FK_SecRel_2)
425         .Default(MCAsmBackend::getFixupKind(Name));
426   }
427 
428   std::unique_ptr<MCObjectTargetWriter>
429   createObjectTargetWriter() const override {
430     return createX86WinCOFFObjectWriter(Is64Bit);
431   }
432 };
433 
434 namespace CU {
435 
436   /// Compact unwind encoding values.
437   enum CompactUnwindEncodings {
438     /// [RE]BP based frame where [RE]BP is pused on the stack immediately after
439     /// the return address, then [RE]SP is moved to [RE]BP.
440     UNWIND_MODE_BP_FRAME                   = 0x01000000,
441 
442     /// A frameless function with a small constant stack size.
443     UNWIND_MODE_STACK_IMMD                 = 0x02000000,
444 
445     /// A frameless function with a large constant stack size.
446     UNWIND_MODE_STACK_IND                  = 0x03000000,
447 
448     /// No compact unwind encoding is available.
449     UNWIND_MODE_DWARF                      = 0x04000000,
450 
451     /// Mask for encoding the frame registers.
452     UNWIND_BP_FRAME_REGISTERS              = 0x00007FFF,
453 
454     /// Mask for encoding the frameless registers.
455     UNWIND_FRAMELESS_STACK_REG_PERMUTATION = 0x000003FF
456   };
457 
458 } // end CU namespace
459 
460 class DarwinX86AsmBackend : public X86AsmBackend {
461   const MCRegisterInfo &MRI;
462 
463   /// Number of registers that can be saved in a compact unwind encoding.
464   enum { CU_NUM_SAVED_REGS = 6 };
465 
466   mutable unsigned SavedRegs[CU_NUM_SAVED_REGS];
467   bool Is64Bit;
468 
469   unsigned OffsetSize;                   ///< Offset of a "push" instruction.
470   unsigned MoveInstrSize;                ///< Size of a "move" instruction.
471   unsigned StackDivide;                  ///< Amount to adjust stack size by.
472 protected:
473   /// Size of a "push" instruction for the given register.
474   unsigned PushInstrSize(unsigned Reg) const {
475     switch (Reg) {
476       case X86::EBX:
477       case X86::ECX:
478       case X86::EDX:
479       case X86::EDI:
480       case X86::ESI:
481       case X86::EBP:
482       case X86::RBX:
483       case X86::RBP:
484         return 1;
485       case X86::R12:
486       case X86::R13:
487       case X86::R14:
488       case X86::R15:
489         return 2;
490     }
491     return 1;
492   }
493 
494   /// Implementation of algorithm to generate the compact unwind encoding
495   /// for the CFI instructions.
496   uint32_t
497   generateCompactUnwindEncodingImpl(ArrayRef<MCCFIInstruction> Instrs) const {
498     if (Instrs.empty()) return 0;
499 
500     // Reset the saved registers.
501     unsigned SavedRegIdx = 0;
502     memset(SavedRegs, 0, sizeof(SavedRegs));
503 
504     bool HasFP = false;
505 
506     // Encode that we are using EBP/RBP as the frame pointer.
507     uint32_t CompactUnwindEncoding = 0;
508 
509     unsigned SubtractInstrIdx = Is64Bit ? 3 : 2;
510     unsigned InstrOffset = 0;
511     unsigned StackAdjust = 0;
512     unsigned StackSize = 0;
513     unsigned NumDefCFAOffsets = 0;
514 
515     for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
516       const MCCFIInstruction &Inst = Instrs[i];
517 
518       switch (Inst.getOperation()) {
519       default:
520         // Any other CFI directives indicate a frame that we aren't prepared
521         // to represent via compact unwind, so just bail out.
522         return 0;
523       case MCCFIInstruction::OpDefCfaRegister: {
524         // Defines a frame pointer. E.g.
525         //
526         //     movq %rsp, %rbp
527         //  L0:
528         //     .cfi_def_cfa_register %rbp
529         //
530         HasFP = true;
531 
532         // If the frame pointer is other than esp/rsp, we do not have a way to
533         // generate a compact unwinding representation, so bail out.
534         if (MRI.getLLVMRegNum(Inst.getRegister(), true) !=
535             (Is64Bit ? X86::RBP : X86::EBP))
536           return 0;
537 
538         // Reset the counts.
539         memset(SavedRegs, 0, sizeof(SavedRegs));
540         StackAdjust = 0;
541         SavedRegIdx = 0;
542         InstrOffset += MoveInstrSize;
543         break;
544       }
545       case MCCFIInstruction::OpDefCfaOffset: {
546         // Defines a new offset for the CFA. E.g.
547         //
548         //  With frame:
549         //
550         //     pushq %rbp
551         //  L0:
552         //     .cfi_def_cfa_offset 16
553         //
554         //  Without frame:
555         //
556         //     subq $72, %rsp
557         //  L0:
558         //     .cfi_def_cfa_offset 80
559         //
560         StackSize = std::abs(Inst.getOffset()) / StackDivide;
561         ++NumDefCFAOffsets;
562         break;
563       }
564       case MCCFIInstruction::OpOffset: {
565         // Defines a "push" of a callee-saved register. E.g.
566         //
567         //     pushq %r15
568         //     pushq %r14
569         //     pushq %rbx
570         //  L0:
571         //     subq $120, %rsp
572         //  L1:
573         //     .cfi_offset %rbx, -40
574         //     .cfi_offset %r14, -32
575         //     .cfi_offset %r15, -24
576         //
577         if (SavedRegIdx == CU_NUM_SAVED_REGS)
578           // If there are too many saved registers, we cannot use a compact
579           // unwind encoding.
580           return CU::UNWIND_MODE_DWARF;
581 
582         unsigned Reg = MRI.getLLVMRegNum(Inst.getRegister(), true);
583         SavedRegs[SavedRegIdx++] = Reg;
584         StackAdjust += OffsetSize;
585         InstrOffset += PushInstrSize(Reg);
586         break;
587       }
588       }
589     }
590 
591     StackAdjust /= StackDivide;
592 
593     if (HasFP) {
594       if ((StackAdjust & 0xFF) != StackAdjust)
595         // Offset was too big for a compact unwind encoding.
596         return CU::UNWIND_MODE_DWARF;
597 
598       // Get the encoding of the saved registers when we have a frame pointer.
599       uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame();
600       if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
601 
602       CompactUnwindEncoding |= CU::UNWIND_MODE_BP_FRAME;
603       CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16;
604       CompactUnwindEncoding |= RegEnc & CU::UNWIND_BP_FRAME_REGISTERS;
605     } else {
606       SubtractInstrIdx += InstrOffset;
607       ++StackAdjust;
608 
609       if ((StackSize & 0xFF) == StackSize) {
610         // Frameless stack with a small stack size.
611         CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IMMD;
612 
613         // Encode the stack size.
614         CompactUnwindEncoding |= (StackSize & 0xFF) << 16;
615       } else {
616         if ((StackAdjust & 0x7) != StackAdjust)
617           // The extra stack adjustments are too big for us to handle.
618           return CU::UNWIND_MODE_DWARF;
619 
620         // Frameless stack with an offset too large for us to encode compactly.
621         CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IND;
622 
623         // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
624         // instruction.
625         CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
626 
627         // Encode any extra stack adjustments (done via push instructions).
628         CompactUnwindEncoding |= (StackAdjust & 0x7) << 13;
629       }
630 
631       // Encode the number of registers saved. (Reverse the list first.)
632       std::reverse(&SavedRegs[0], &SavedRegs[SavedRegIdx]);
633       CompactUnwindEncoding |= (SavedRegIdx & 0x7) << 10;
634 
635       // Get the encoding of the saved registers when we don't have a frame
636       // pointer.
637       uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegIdx);
638       if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
639 
640       // Encode the register encoding.
641       CompactUnwindEncoding |=
642         RegEnc & CU::UNWIND_FRAMELESS_STACK_REG_PERMUTATION;
643     }
644 
645     return CompactUnwindEncoding;
646   }
647 
648 private:
649   /// Get the compact unwind number for a given register. The number
650   /// corresponds to the enum lists in compact_unwind_encoding.h.
651   int getCompactUnwindRegNum(unsigned Reg) const {
652     static const MCPhysReg CU32BitRegs[7] = {
653       X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
654     };
655     static const MCPhysReg CU64BitRegs[] = {
656       X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
657     };
658     const MCPhysReg *CURegs = Is64Bit ? CU64BitRegs : CU32BitRegs;
659     for (int Idx = 1; *CURegs; ++CURegs, ++Idx)
660       if (*CURegs == Reg)
661         return Idx;
662 
663     return -1;
664   }
665 
666   /// Return the registers encoded for a compact encoding with a frame
667   /// pointer.
668   uint32_t encodeCompactUnwindRegistersWithFrame() const {
669     // Encode the registers in the order they were saved --- 3-bits per
670     // register. The list of saved registers is assumed to be in reverse
671     // order. The registers are numbered from 1 to CU_NUM_SAVED_REGS.
672     uint32_t RegEnc = 0;
673     for (int i = 0, Idx = 0; i != CU_NUM_SAVED_REGS; ++i) {
674       unsigned Reg = SavedRegs[i];
675       if (Reg == 0) break;
676 
677       int CURegNum = getCompactUnwindRegNum(Reg);
678       if (CURegNum == -1) return ~0U;
679 
680       // Encode the 3-bit register number in order, skipping over 3-bits for
681       // each register.
682       RegEnc |= (CURegNum & 0x7) << (Idx++ * 3);
683     }
684 
685     assert((RegEnc & 0x3FFFF) == RegEnc &&
686            "Invalid compact register encoding!");
687     return RegEnc;
688   }
689 
690   /// Create the permutation encoding used with frameless stacks. It is
691   /// passed the number of registers to be saved and an array of the registers
692   /// saved.
693   uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned RegCount) const {
694     // The saved registers are numbered from 1 to 6. In order to encode the
695     // order in which they were saved, we re-number them according to their
696     // place in the register order. The re-numbering is relative to the last
697     // re-numbered register. E.g., if we have registers {6, 2, 4, 5} saved in
698     // that order:
699     //
700     //    Orig  Re-Num
701     //    ----  ------
702     //     6       6
703     //     2       2
704     //     4       3
705     //     5       3
706     //
707     for (unsigned i = 0; i < RegCount; ++i) {
708       int CUReg = getCompactUnwindRegNum(SavedRegs[i]);
709       if (CUReg == -1) return ~0U;
710       SavedRegs[i] = CUReg;
711     }
712 
713     // Reverse the list.
714     std::reverse(&SavedRegs[0], &SavedRegs[CU_NUM_SAVED_REGS]);
715 
716     uint32_t RenumRegs[CU_NUM_SAVED_REGS];
717     for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i){
718       unsigned Countless = 0;
719       for (unsigned j = CU_NUM_SAVED_REGS - RegCount; j < i; ++j)
720         if (SavedRegs[j] < SavedRegs[i])
721           ++Countless;
722 
723       RenumRegs[i] = SavedRegs[i] - Countless - 1;
724     }
725 
726     // Take the renumbered values and encode them into a 10-bit number.
727     uint32_t permutationEncoding = 0;
728     switch (RegCount) {
729     case 6:
730       permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
731                              + 6 * RenumRegs[2] +  2 * RenumRegs[3]
732                              +     RenumRegs[4];
733       break;
734     case 5:
735       permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
736                              + 6 * RenumRegs[3] +  2 * RenumRegs[4]
737                              +     RenumRegs[5];
738       break;
739     case 4:
740       permutationEncoding |=  60 * RenumRegs[2] + 12 * RenumRegs[3]
741                              + 3 * RenumRegs[4] +      RenumRegs[5];
742       break;
743     case 3:
744       permutationEncoding |=  20 * RenumRegs[3] +  4 * RenumRegs[4]
745                              +     RenumRegs[5];
746       break;
747     case 2:
748       permutationEncoding |=   5 * RenumRegs[4] +      RenumRegs[5];
749       break;
750     case 1:
751       permutationEncoding |=       RenumRegs[5];
752       break;
753     }
754 
755     assert((permutationEncoding & 0x3FF) == permutationEncoding &&
756            "Invalid compact register encoding!");
757     return permutationEncoding;
758   }
759 
760 public:
761   DarwinX86AsmBackend(const Target &T, const MCRegisterInfo &MRI,
762                       const MCSubtargetInfo &STI, bool Is64Bit)
763     : X86AsmBackend(T, STI), MRI(MRI), Is64Bit(Is64Bit) {
764     memset(SavedRegs, 0, sizeof(SavedRegs));
765     OffsetSize = Is64Bit ? 8 : 4;
766     MoveInstrSize = Is64Bit ? 3 : 2;
767     StackDivide = Is64Bit ? 8 : 4;
768   }
769 };
770 
771 class DarwinX86_32AsmBackend : public DarwinX86AsmBackend {
772 public:
773   DarwinX86_32AsmBackend(const Target &T, const MCRegisterInfo &MRI,
774                          const MCSubtargetInfo &STI)
775       : DarwinX86AsmBackend(T, MRI, STI, false) {}
776 
777   std::unique_ptr<MCObjectTargetWriter>
778   createObjectTargetWriter() const override {
779     return createX86MachObjectWriter(/*Is64Bit=*/false,
780                                      MachO::CPU_TYPE_I386,
781                                      MachO::CPU_SUBTYPE_I386_ALL);
782   }
783 
784   /// Generate the compact unwind encoding for the CFI instructions.
785   uint32_t generateCompactUnwindEncoding(
786                              ArrayRef<MCCFIInstruction> Instrs) const override {
787     return generateCompactUnwindEncodingImpl(Instrs);
788   }
789 };
790 
791 class DarwinX86_64AsmBackend : public DarwinX86AsmBackend {
792   const MachO::CPUSubTypeX86 Subtype;
793 public:
794   DarwinX86_64AsmBackend(const Target &T, const MCRegisterInfo &MRI,
795                          const MCSubtargetInfo &STI, MachO::CPUSubTypeX86 st)
796       : DarwinX86AsmBackend(T, MRI, STI, true), Subtype(st) {}
797 
798   std::unique_ptr<MCObjectTargetWriter>
799   createObjectTargetWriter() const override {
800     return createX86MachObjectWriter(/*Is64Bit=*/true, MachO::CPU_TYPE_X86_64,
801                                      Subtype);
802   }
803 
804   /// Generate the compact unwind encoding for the CFI instructions.
805   uint32_t generateCompactUnwindEncoding(
806                              ArrayRef<MCCFIInstruction> Instrs) const override {
807     return generateCompactUnwindEncodingImpl(Instrs);
808   }
809 };
810 
811 } // end anonymous namespace
812 
813 MCAsmBackend *llvm::createX86_32AsmBackend(const Target &T,
814                                            const MCSubtargetInfo &STI,
815                                            const MCRegisterInfo &MRI,
816                                            const MCTargetOptions &Options) {
817   const Triple &TheTriple = STI.getTargetTriple();
818   if (TheTriple.isOSBinFormatMachO())
819     return new DarwinX86_32AsmBackend(T, MRI, STI);
820 
821   if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
822     return new WindowsX86AsmBackend(T, false, STI);
823 
824   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
825 
826   if (TheTriple.isOSIAMCU())
827     return new ELFX86_IAMCUAsmBackend(T, OSABI, STI);
828 
829   return new ELFX86_32AsmBackend(T, OSABI, STI);
830 }
831 
832 MCAsmBackend *llvm::createX86_64AsmBackend(const Target &T,
833                                            const MCSubtargetInfo &STI,
834                                            const MCRegisterInfo &MRI,
835                                            const MCTargetOptions &Options) {
836   const Triple &TheTriple = STI.getTargetTriple();
837   if (TheTriple.isOSBinFormatMachO()) {
838     MachO::CPUSubTypeX86 CS =
839         StringSwitch<MachO::CPUSubTypeX86>(TheTriple.getArchName())
840             .Case("x86_64h", MachO::CPU_SUBTYPE_X86_64_H)
841             .Default(MachO::CPU_SUBTYPE_X86_64_ALL);
842     return new DarwinX86_64AsmBackend(T, MRI, STI, CS);
843   }
844 
845   if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
846     return new WindowsX86AsmBackend(T, true, STI);
847 
848   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
849 
850   if (TheTriple.getEnvironment() == Triple::GNUX32)
851     return new ELFX86_X32AsmBackend(T, OSABI, STI);
852   return new ELFX86_64AsmBackend(T, OSABI, STI);
853 }
854