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