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