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/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"
30 using namespace llvm;
31 
32 static unsigned getFixupKindLog2Size(unsigned Kind) {
33   switch (Kind) {
34   default:
35     llvm_unreachable("invalid fixup kind!");
36   case FK_PCRel_1:
37   case FK_SecRel_1:
38   case FK_Data_1:
39     return 0;
40   case FK_PCRel_2:
41   case FK_SecRel_2:
42   case FK_Data_2:
43     return 1;
44   case FK_PCRel_4:
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:
52   case FK_SecRel_4:
53   case FK_Data_4:
54     return 2;
55   case FK_PCRel_8:
56   case FK_SecRel_8:
57   case FK_Data_8:
58   case X86::reloc_global_offset_table8:
59     return 3;
60   }
61 }
62 
63 namespace {
64 
65 class X86ELFObjectWriter : public MCELFObjectTargetWriter {
66 public:
67   X86ELFObjectWriter(bool is64Bit, uint8_t OSABI, uint16_t EMachine,
68                      bool HasRelocationAddend, bool foobar)
69     : MCELFObjectTargetWriter(is64Bit, OSABI, EMachine, HasRelocationAddend) {}
70 };
71 
72 class X86AsmBackend : public MCAsmBackend {
73   const StringRef CPU;
74   bool HasNopl;
75   const uint64_t MaxNopLength;
76 public:
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";
85   }
86 
87   unsigned getNumFixupKinds() const override {
88     return X86::NumTargetFixupKinds;
89   }
90 
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},
101     };
102 
103     if (Kind < FirstTargetFixupKind)
104       return MCAsmBackend::getFixupKindInfo(Kind);
105 
106     assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
107            "Invalid kind!");
108     return Infos[Kind - FirstTargetFixupKind];
109   }
110 
111   void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
112                   const MCValue &Target, MutableArrayRef<char> Data,
113                   uint64_t Value, bool IsResolved) const override {
114     unsigned Size = 1 << getFixupKindLog2Size(Fixup.getKind());
115 
116     assert(Fixup.getOffset() + Size <= Data.size() && "Invalid fixup offset!");
117 
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
121     // other assemblers.
122     assert(isIntN(Size * 8 + 1, Value) &&
123            "Value does not fit in the Fixup field");
124 
125     for (unsigned i = 0; i != Size; ++i)
126       Data[Fixup.getOffset() + i] = uint8_t(Value >> (i * 8));
127   }
128 
129   bool mayNeedRelaxation(const MCInst &Inst) const override;
130 
131   bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
132                             const MCRelaxableFragment *DF,
133                             const MCAsmLayout &Layout) const override;
134 
135   void relaxInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
136                         MCInst &Res) const override;
137 
138   bool writeNopData(uint64_t Count, MCObjectWriter *OW) const override;
139 };
140 } // end anonymous namespace
141 
142 static unsigned getRelaxedOpcodeBranch(const MCInst &Inst, bool is16BitMode) {
143   unsigned Op = Inst.getOpcode();
144   switch (Op) {
145   default:
146     return Op;
147   case X86::JAE_1:
148     return (is16BitMode) ? X86::JAE_2 : X86::JAE_4;
149   case X86::JA_1:
150     return (is16BitMode) ? X86::JA_2 : X86::JA_4;
151   case X86::JBE_1:
152     return (is16BitMode) ? X86::JBE_2 : X86::JBE_4;
153   case X86::JB_1:
154     return (is16BitMode) ? X86::JB_2 : X86::JB_4;
155   case X86::JE_1:
156     return (is16BitMode) ? X86::JE_2 : X86::JE_4;
157   case X86::JGE_1:
158     return (is16BitMode) ? X86::JGE_2 : X86::JGE_4;
159   case X86::JG_1:
160     return (is16BitMode) ? X86::JG_2 : X86::JG_4;
161   case X86::JLE_1:
162     return (is16BitMode) ? X86::JLE_2 : X86::JLE_4;
163   case X86::JL_1:
164     return (is16BitMode) ? X86::JL_2 : X86::JL_4;
165   case X86::JMP_1:
166     return (is16BitMode) ? X86::JMP_2 : X86::JMP_4;
167   case X86::JNE_1:
168     return (is16BitMode) ? X86::JNE_2 : X86::JNE_4;
169   case X86::JNO_1:
170     return (is16BitMode) ? X86::JNO_2 : X86::JNO_4;
171   case X86::JNP_1:
172     return (is16BitMode) ? X86::JNP_2 : X86::JNP_4;
173   case X86::JNS_1:
174     return (is16BitMode) ? X86::JNS_2 : X86::JNS_4;
175   case X86::JO_1:
176     return (is16BitMode) ? X86::JO_2 : X86::JO_4;
177   case X86::JP_1:
178     return (is16BitMode) ? X86::JP_2 : X86::JP_4;
179   case X86::JS_1:
180     return (is16BitMode) ? X86::JS_2 : X86::JS_4;
181   }
182 }
183 
184 static unsigned getRelaxedOpcodeArith(const MCInst &Inst) {
185   unsigned Op = Inst.getOpcode();
186   switch (Op) {
187   default:
188     return Op;
189 
190     // IMUL
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;
197 
198     // AND
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;
205 
206     // OR
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;
213 
214     // XOR
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;
221 
222     // ADD
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;
229 
230    // ADC
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;
237 
238     // SUB
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;
245 
246    // SBB
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;
253 
254     // CMP
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;
261 
262     // PUSH
263   case X86::PUSH32i8:  return X86::PUSHi32;
264   case X86::PUSH16i8:  return X86::PUSHi16;
265   case X86::PUSH64i8:  return X86::PUSH64i32;
266   }
267 }
268 
269 static unsigned getRelaxedOpcode(const MCInst &Inst, bool is16BitMode) {
270   unsigned R = getRelaxedOpcodeArith(Inst);
271   if (R != Inst.getOpcode())
272     return R;
273   return getRelaxedOpcodeBranch(Inst, is16BitMode);
274 }
275 
276 bool X86AsmBackend::mayNeedRelaxation(const MCInst &Inst) const {
277   // Branches can always be relaxed in either mode.
278   if (getRelaxedOpcodeBranch(Inst, false) != Inst.getOpcode())
279     return true;
280 
281   // Check if this instruction is ever relaxable.
282   if (getRelaxedOpcodeArith(Inst) == Inst.getOpcode())
283     return false;
284 
285 
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())
290     return true;
291 
292   return false;
293 }
294 
295 bool X86AsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
296                                          uint64_t Value,
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));
301 }
302 
303 // FIXME: Can tblgen help at all here to verify there aren't other instructions
304 // we can relax?
305 void X86AsmBackend::relaxInstruction(const MCInst &Inst,
306                                      const MCSubtargetInfo &STI,
307                                      MCInst &Res) const {
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);
311 
312   if (RelaxedOp == Inst.getOpcode()) {
313     SmallString<256> Tmp;
314     raw_svector_ostream OS(Tmp);
315     Inst.dump_pretty(OS);
316     OS << "\n";
317     report_fatal_error("unexpected instruction to relax: " + OS.str());
318   }
319 
320   Res = Inst;
321   Res.setOpcode(RelaxedOp);
322 }
323 
324 /// \brief Write a sequence of optimal nops to the output, covering \p Count
325 /// bytes.
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] = {
329     // nop
330     {0x90},
331     // xchg %ax,%ax
332     {0x66, 0x90},
333     // nopl (%[re]ax)
334     {0x0f, 0x1f, 0x00},
335     // nopl 0(%[re]ax)
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},
341     // nopl 0L(%[re]ax)
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},
349   };
350 
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.
354   if (!HasNopl) {
355     for (uint64_t i = 0; i < Count; ++i)
356       OW->write8(0x90);
357     return true;
358   }
359 
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.
362   do {
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++)
366       OW->write8(0x66);
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);
372 
373   return true;
374 }
375 
376 /* *** */
377 
378 namespace {
379 
380 class ELFX86AsmBackend : public X86AsmBackend {
381 public:
382   uint8_t OSABI;
383   ELFX86AsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
384       : X86AsmBackend(T, CPU), OSABI(OSABI) {}
385 };
386 
387 class ELFX86_32AsmBackend : public ELFX86AsmBackend {
388 public:
389   ELFX86_32AsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
390     : ELFX86AsmBackend(T, OSABI, CPU) {}
391 
392   std::unique_ptr<MCObjectWriter>
393   createObjectWriter(raw_pwrite_stream &OS) const override {
394     return createX86ELFObjectWriter(OS, /*IsELF64*/ false, OSABI, ELF::EM_386);
395   }
396 };
397 
398 class ELFX86_X32AsmBackend : public ELFX86AsmBackend {
399 public:
400   ELFX86_X32AsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
401       : ELFX86AsmBackend(T, OSABI, CPU) {}
402 
403   std::unique_ptr<MCObjectWriter>
404   createObjectWriter(raw_pwrite_stream &OS) const override {
405     return createX86ELFObjectWriter(OS, /*IsELF64*/ false, OSABI,
406                                     ELF::EM_X86_64);
407   }
408 };
409 
410 class ELFX86_IAMCUAsmBackend : public ELFX86AsmBackend {
411 public:
412   ELFX86_IAMCUAsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
413       : ELFX86AsmBackend(T, OSABI, CPU) {}
414 
415   std::unique_ptr<MCObjectWriter>
416   createObjectWriter(raw_pwrite_stream &OS) const override {
417     return createX86ELFObjectWriter(OS, /*IsELF64*/ false, OSABI,
418                                     ELF::EM_IAMCU);
419   }
420 };
421 
422 class ELFX86_64AsmBackend : public ELFX86AsmBackend {
423 public:
424   ELFX86_64AsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
425     : ELFX86AsmBackend(T, OSABI, CPU) {}
426 
427   std::unique_ptr<MCObjectWriter>
428   createObjectWriter(raw_pwrite_stream &OS) const override {
429     return createX86ELFObjectWriter(OS, /*IsELF64*/ true, OSABI, ELF::EM_X86_64);
430   }
431 };
432 
433 class WindowsX86AsmBackend : public X86AsmBackend {
434   bool Is64Bit;
435 
436 public:
437   WindowsX86AsmBackend(const Target &T, bool is64Bit, StringRef CPU)
438     : X86AsmBackend(T, CPU)
439     , Is64Bit(is64Bit) {
440   }
441 
442   Optional<MCFixupKind> getFixupKind(StringRef Name) const override {
443     return StringSwitch<Optional<MCFixupKind>>(Name)
444         .Case("dir32", FK_Data_4)
445         .Case("secrel32", FK_SecRel_4)
446         .Case("secidx", FK_SecRel_2)
447         .Default(MCAsmBackend::getFixupKind(Name));
448   }
449 
450   std::unique_ptr<MCObjectWriter>
451   createObjectWriter(raw_pwrite_stream &OS) const override {
452     return createX86WinCOFFObjectWriter(OS, Is64Bit);
453   }
454 };
455 
456 namespace CU {
457 
458   /// Compact unwind encoding values.
459   enum CompactUnwindEncodings {
460     /// [RE]BP based frame where [RE]BP is pused on the stack immediately after
461     /// the return address, then [RE]SP is moved to [RE]BP.
462     UNWIND_MODE_BP_FRAME                   = 0x01000000,
463 
464     /// A frameless function with a small constant stack size.
465     UNWIND_MODE_STACK_IMMD                 = 0x02000000,
466 
467     /// A frameless function with a large constant stack size.
468     UNWIND_MODE_STACK_IND                  = 0x03000000,
469 
470     /// No compact unwind encoding is available.
471     UNWIND_MODE_DWARF                      = 0x04000000,
472 
473     /// Mask for encoding the frame registers.
474     UNWIND_BP_FRAME_REGISTERS              = 0x00007FFF,
475 
476     /// Mask for encoding the frameless registers.
477     UNWIND_FRAMELESS_STACK_REG_PERMUTATION = 0x000003FF
478   };
479 
480 } // end CU namespace
481 
482 class DarwinX86AsmBackend : public X86AsmBackend {
483   const MCRegisterInfo &MRI;
484 
485   /// \brief Number of registers that can be saved in a compact unwind encoding.
486   enum { CU_NUM_SAVED_REGS = 6 };
487 
488   mutable unsigned SavedRegs[CU_NUM_SAVED_REGS];
489   bool Is64Bit;
490 
491   unsigned OffsetSize;                   ///< Offset of a "push" instruction.
492   unsigned MoveInstrSize;                ///< Size of a "move" instruction.
493   unsigned StackDivide;                  ///< Amount to adjust stack size by.
494 protected:
495   /// \brief Size of a "push" instruction for the given register.
496   unsigned PushInstrSize(unsigned Reg) const {
497     switch (Reg) {
498       case X86::EBX:
499       case X86::ECX:
500       case X86::EDX:
501       case X86::EDI:
502       case X86::ESI:
503       case X86::EBP:
504       case X86::RBX:
505       case X86::RBP:
506         return 1;
507       case X86::R12:
508       case X86::R13:
509       case X86::R14:
510       case X86::R15:
511         return 2;
512     }
513     return 1;
514   }
515 
516   /// \brief Implementation of algorithm to generate the compact unwind encoding
517   /// for the CFI instructions.
518   uint32_t
519   generateCompactUnwindEncodingImpl(ArrayRef<MCCFIInstruction> Instrs) const {
520     if (Instrs.empty()) return 0;
521 
522     // Reset the saved registers.
523     unsigned SavedRegIdx = 0;
524     memset(SavedRegs, 0, sizeof(SavedRegs));
525 
526     bool HasFP = false;
527 
528     // Encode that we are using EBP/RBP as the frame pointer.
529     uint32_t CompactUnwindEncoding = 0;
530 
531     unsigned SubtractInstrIdx = Is64Bit ? 3 : 2;
532     unsigned InstrOffset = 0;
533     unsigned StackAdjust = 0;
534     unsigned StackSize = 0;
535     unsigned PrevStackSize = 0;
536     unsigned NumDefCFAOffsets = 0;
537 
538     for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
539       const MCCFIInstruction &Inst = Instrs[i];
540 
541       switch (Inst.getOperation()) {
542       default:
543         // Any other CFI directives indicate a frame that we aren't prepared
544         // to represent via compact unwind, so just bail out.
545         return 0;
546       case MCCFIInstruction::OpDefCfaRegister: {
547         // Defines a frame pointer. E.g.
548         //
549         //     movq %rsp, %rbp
550         //  L0:
551         //     .cfi_def_cfa_register %rbp
552         //
553         HasFP = true;
554 
555         // If the frame pointer is other than esp/rsp, we do not have a way to
556         // generate a compact unwinding representation, so bail out.
557         if (MRI.getLLVMRegNum(Inst.getRegister(), true) !=
558             (Is64Bit ? X86::RBP : X86::EBP))
559           return 0;
560 
561         // Reset the counts.
562         memset(SavedRegs, 0, sizeof(SavedRegs));
563         StackAdjust = 0;
564         SavedRegIdx = 0;
565         InstrOffset += MoveInstrSize;
566         break;
567       }
568       case MCCFIInstruction::OpDefCfaOffset: {
569         // Defines a new offset for the CFA. E.g.
570         //
571         //  With frame:
572         //
573         //     pushq %rbp
574         //  L0:
575         //     .cfi_def_cfa_offset 16
576         //
577         //  Without frame:
578         //
579         //     subq $72, %rsp
580         //  L0:
581         //     .cfi_def_cfa_offset 80
582         //
583         PrevStackSize = StackSize;
584         StackSize = std::abs(Inst.getOffset()) / StackDivide;
585         ++NumDefCFAOffsets;
586         break;
587       }
588       case MCCFIInstruction::OpOffset: {
589         // Defines a "push" of a callee-saved register. E.g.
590         //
591         //     pushq %r15
592         //     pushq %r14
593         //     pushq %rbx
594         //  L0:
595         //     subq $120, %rsp
596         //  L1:
597         //     .cfi_offset %rbx, -40
598         //     .cfi_offset %r14, -32
599         //     .cfi_offset %r15, -24
600         //
601         if (SavedRegIdx == CU_NUM_SAVED_REGS)
602           // If there are too many saved registers, we cannot use a compact
603           // unwind encoding.
604           return CU::UNWIND_MODE_DWARF;
605 
606         unsigned Reg = MRI.getLLVMRegNum(Inst.getRegister(), true);
607         SavedRegs[SavedRegIdx++] = Reg;
608         StackAdjust += OffsetSize;
609         InstrOffset += PushInstrSize(Reg);
610         break;
611       }
612       }
613     }
614 
615     StackAdjust /= StackDivide;
616 
617     if (HasFP) {
618       if ((StackAdjust & 0xFF) != StackAdjust)
619         // Offset was too big for a compact unwind encoding.
620         return CU::UNWIND_MODE_DWARF;
621 
622       // Get the encoding of the saved registers when we have a frame pointer.
623       uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame();
624       if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
625 
626       CompactUnwindEncoding |= CU::UNWIND_MODE_BP_FRAME;
627       CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16;
628       CompactUnwindEncoding |= RegEnc & CU::UNWIND_BP_FRAME_REGISTERS;
629     } else {
630       // If the amount of the stack allocation is the size of a register, then
631       // we "push" the RAX/EAX register onto the stack instead of adjusting the
632       // stack pointer with a SUB instruction. We don't support the push of the
633       // RAX/EAX register with compact unwind. So we check for that situation
634       // here.
635       if ((NumDefCFAOffsets == SavedRegIdx + 1 &&
636            StackSize - PrevStackSize == 1) ||
637           (Instrs.size() == 1 && NumDefCFAOffsets == 1 && StackSize == 2))
638         return CU::UNWIND_MODE_DWARF;
639 
640       SubtractInstrIdx += InstrOffset;
641       ++StackAdjust;
642 
643       if ((StackSize & 0xFF) == StackSize) {
644         // Frameless stack with a small stack size.
645         CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IMMD;
646 
647         // Encode the stack size.
648         CompactUnwindEncoding |= (StackSize & 0xFF) << 16;
649       } else {
650         if ((StackAdjust & 0x7) != StackAdjust)
651           // The extra stack adjustments are too big for us to handle.
652           return CU::UNWIND_MODE_DWARF;
653 
654         // Frameless stack with an offset too large for us to encode compactly.
655         CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IND;
656 
657         // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
658         // instruction.
659         CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
660 
661         // Encode any extra stack stack adjustments (done via push
662         // instructions).
663         CompactUnwindEncoding |= (StackAdjust & 0x7) << 13;
664       }
665 
666       // Encode the number of registers saved. (Reverse the list first.)
667       std::reverse(&SavedRegs[0], &SavedRegs[SavedRegIdx]);
668       CompactUnwindEncoding |= (SavedRegIdx & 0x7) << 10;
669 
670       // Get the encoding of the saved registers when we don't have a frame
671       // pointer.
672       uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegIdx);
673       if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
674 
675       // Encode the register encoding.
676       CompactUnwindEncoding |=
677         RegEnc & CU::UNWIND_FRAMELESS_STACK_REG_PERMUTATION;
678     }
679 
680     return CompactUnwindEncoding;
681   }
682 
683 private:
684   /// \brief Get the compact unwind number for a given register. The number
685   /// corresponds to the enum lists in compact_unwind_encoding.h.
686   int getCompactUnwindRegNum(unsigned Reg) const {
687     static const MCPhysReg CU32BitRegs[7] = {
688       X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
689     };
690     static const MCPhysReg CU64BitRegs[] = {
691       X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
692     };
693     const MCPhysReg *CURegs = Is64Bit ? CU64BitRegs : CU32BitRegs;
694     for (int Idx = 1; *CURegs; ++CURegs, ++Idx)
695       if (*CURegs == Reg)
696         return Idx;
697 
698     return -1;
699   }
700 
701   /// \brief Return the registers encoded for a compact encoding with a frame
702   /// pointer.
703   uint32_t encodeCompactUnwindRegistersWithFrame() const {
704     // Encode the registers in the order they were saved --- 3-bits per
705     // register. The list of saved registers is assumed to be in reverse
706     // order. The registers are numbered from 1 to CU_NUM_SAVED_REGS.
707     uint32_t RegEnc = 0;
708     for (int i = 0, Idx = 0; i != CU_NUM_SAVED_REGS; ++i) {
709       unsigned Reg = SavedRegs[i];
710       if (Reg == 0) break;
711 
712       int CURegNum = getCompactUnwindRegNum(Reg);
713       if (CURegNum == -1) return ~0U;
714 
715       // Encode the 3-bit register number in order, skipping over 3-bits for
716       // each register.
717       RegEnc |= (CURegNum & 0x7) << (Idx++ * 3);
718     }
719 
720     assert((RegEnc & 0x3FFFF) == RegEnc &&
721            "Invalid compact register encoding!");
722     return RegEnc;
723   }
724 
725   /// \brief Create the permutation encoding used with frameless stacks. It is
726   /// passed the number of registers to be saved and an array of the registers
727   /// saved.
728   uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned RegCount) const {
729     // The saved registers are numbered from 1 to 6. In order to encode the
730     // order in which they were saved, we re-number them according to their
731     // place in the register order. The re-numbering is relative to the last
732     // re-numbered register. E.g., if we have registers {6, 2, 4, 5} saved in
733     // that order:
734     //
735     //    Orig  Re-Num
736     //    ----  ------
737     //     6       6
738     //     2       2
739     //     4       3
740     //     5       3
741     //
742     for (unsigned i = 0; i < RegCount; ++i) {
743       int CUReg = getCompactUnwindRegNum(SavedRegs[i]);
744       if (CUReg == -1) return ~0U;
745       SavedRegs[i] = CUReg;
746     }
747 
748     // Reverse the list.
749     std::reverse(&SavedRegs[0], &SavedRegs[CU_NUM_SAVED_REGS]);
750 
751     uint32_t RenumRegs[CU_NUM_SAVED_REGS];
752     for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i){
753       unsigned Countless = 0;
754       for (unsigned j = CU_NUM_SAVED_REGS - RegCount; j < i; ++j)
755         if (SavedRegs[j] < SavedRegs[i])
756           ++Countless;
757 
758       RenumRegs[i] = SavedRegs[i] - Countless - 1;
759     }
760 
761     // Take the renumbered values and encode them into a 10-bit number.
762     uint32_t permutationEncoding = 0;
763     switch (RegCount) {
764     case 6:
765       permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
766                              + 6 * RenumRegs[2] +  2 * RenumRegs[3]
767                              +     RenumRegs[4];
768       break;
769     case 5:
770       permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
771                              + 6 * RenumRegs[3] +  2 * RenumRegs[4]
772                              +     RenumRegs[5];
773       break;
774     case 4:
775       permutationEncoding |=  60 * RenumRegs[2] + 12 * RenumRegs[3]
776                              + 3 * RenumRegs[4] +      RenumRegs[5];
777       break;
778     case 3:
779       permutationEncoding |=  20 * RenumRegs[3] +  4 * RenumRegs[4]
780                              +     RenumRegs[5];
781       break;
782     case 2:
783       permutationEncoding |=   5 * RenumRegs[4] +      RenumRegs[5];
784       break;
785     case 1:
786       permutationEncoding |=       RenumRegs[5];
787       break;
788     }
789 
790     assert((permutationEncoding & 0x3FF) == permutationEncoding &&
791            "Invalid compact register encoding!");
792     return permutationEncoding;
793   }
794 
795 public:
796   DarwinX86AsmBackend(const Target &T, const MCRegisterInfo &MRI, StringRef CPU,
797                       bool Is64Bit)
798     : X86AsmBackend(T, CPU), MRI(MRI), Is64Bit(Is64Bit) {
799     memset(SavedRegs, 0, sizeof(SavedRegs));
800     OffsetSize = Is64Bit ? 8 : 4;
801     MoveInstrSize = Is64Bit ? 3 : 2;
802     StackDivide = Is64Bit ? 8 : 4;
803   }
804 };
805 
806 class DarwinX86_32AsmBackend : public DarwinX86AsmBackend {
807 public:
808   DarwinX86_32AsmBackend(const Target &T, const MCRegisterInfo &MRI,
809                          StringRef CPU)
810       : DarwinX86AsmBackend(T, MRI, CPU, false) {}
811 
812   std::unique_ptr<MCObjectWriter>
813   createObjectWriter(raw_pwrite_stream &OS) const override {
814     return createX86MachObjectWriter(OS, /*Is64Bit=*/false,
815                                      MachO::CPU_TYPE_I386,
816                                      MachO::CPU_SUBTYPE_I386_ALL);
817   }
818 
819   /// \brief Generate the compact unwind encoding for the CFI instructions.
820   uint32_t generateCompactUnwindEncoding(
821                              ArrayRef<MCCFIInstruction> Instrs) const override {
822     return generateCompactUnwindEncodingImpl(Instrs);
823   }
824 };
825 
826 class DarwinX86_64AsmBackend : public DarwinX86AsmBackend {
827   const MachO::CPUSubTypeX86 Subtype;
828 public:
829   DarwinX86_64AsmBackend(const Target &T, const MCRegisterInfo &MRI,
830                          StringRef CPU, MachO::CPUSubTypeX86 st)
831       : DarwinX86AsmBackend(T, MRI, CPU, true), Subtype(st) {}
832 
833   std::unique_ptr<MCObjectWriter>
834   createObjectWriter(raw_pwrite_stream &OS) const override {
835     return createX86MachObjectWriter(OS, /*Is64Bit=*/true,
836                                      MachO::CPU_TYPE_X86_64, Subtype);
837   }
838 
839   /// \brief Generate the compact unwind encoding for the CFI instructions.
840   uint32_t generateCompactUnwindEncoding(
841                              ArrayRef<MCCFIInstruction> Instrs) const override {
842     return generateCompactUnwindEncodingImpl(Instrs);
843   }
844 };
845 
846 } // end anonymous namespace
847 
848 MCAsmBackend *llvm::createX86_32AsmBackend(const Target &T,
849                                            const MCRegisterInfo &MRI,
850                                            const Triple &TheTriple,
851                                            StringRef CPU,
852                                            const MCTargetOptions &Options) {
853   if (TheTriple.isOSBinFormatMachO())
854     return new DarwinX86_32AsmBackend(T, MRI, CPU);
855 
856   if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
857     return new WindowsX86AsmBackend(T, false, CPU);
858 
859   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
860 
861   if (TheTriple.isOSIAMCU())
862     return new ELFX86_IAMCUAsmBackend(T, OSABI, CPU);
863 
864   return new ELFX86_32AsmBackend(T, OSABI, CPU);
865 }
866 
867 MCAsmBackend *llvm::createX86_64AsmBackend(const Target &T,
868                                            const MCRegisterInfo &MRI,
869                                            const Triple &TheTriple,
870                                            StringRef CPU,
871                                            const MCTargetOptions &Options) {
872   if (TheTriple.isOSBinFormatMachO()) {
873     MachO::CPUSubTypeX86 CS =
874         StringSwitch<MachO::CPUSubTypeX86>(TheTriple.getArchName())
875             .Case("x86_64h", MachO::CPU_SUBTYPE_X86_64_H)
876             .Default(MachO::CPU_SUBTYPE_X86_64_ALL);
877     return new DarwinX86_64AsmBackend(T, MRI, CPU, CS);
878   }
879 
880   if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
881     return new WindowsX86AsmBackend(T, true, CPU);
882 
883   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
884 
885   if (TheTriple.getEnvironment() == Triple::GNUX32)
886     return new ELFX86_X32AsmBackend(T, OSABI, CPU);
887   return new ELFX86_64AsmBackend(T, OSABI, CPU);
888 }
889