LLVM  4.0.0
X86AsmBackend.cpp
Go to the documentation of this file.
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 
12 #include "llvm/ADT/StringSwitch.h"
13 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCInst.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"
25 #include "llvm/Support/ELF.h"
27 #include "llvm/Support/MachO.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:
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:
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 {
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 MCFixup &Fixup, char *Data, unsigned DataSize,
112  uint64_t Value, bool IsPCRel) const override {
113  unsigned Size = 1 << getFixupKindLog2Size(Fixup.getKind());
114 
115  assert(Fixup.getOffset() + Size <= DataSize &&
116  "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  MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
393  return createX86ELFObjectWriter(OS, /*IsELF64*/ false, OSABI, ELF::EM_386);
394  }
395 };
396 
397 class ELFX86_X32AsmBackend : public ELFX86AsmBackend {
398 public:
399  ELFX86_X32AsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
400  : ELFX86AsmBackend(T, OSABI, CPU) {}
401 
402  MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
403  return createX86ELFObjectWriter(OS, /*IsELF64*/ false, OSABI,
405  }
406 };
407 
408 class ELFX86_IAMCUAsmBackend : public ELFX86AsmBackend {
409 public:
410  ELFX86_IAMCUAsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
411  : ELFX86AsmBackend(T, OSABI, CPU) {}
412 
413  MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
414  return createX86ELFObjectWriter(OS, /*IsELF64*/ false, OSABI,
415  ELF::EM_IAMCU);
416  }
417 };
418 
419 class ELFX86_64AsmBackend : public ELFX86AsmBackend {
420 public:
421  ELFX86_64AsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
422  : ELFX86AsmBackend(T, OSABI, CPU) {}
423 
424  MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
425  return createX86ELFObjectWriter(OS, /*IsELF64*/ true, OSABI, ELF::EM_X86_64);
426  }
427 };
428 
429 class WindowsX86AsmBackend : public X86AsmBackend {
430  bool Is64Bit;
431 
432 public:
433  WindowsX86AsmBackend(const Target &T, bool is64Bit, StringRef CPU)
434  : X86AsmBackend(T, CPU)
435  , Is64Bit(is64Bit) {
436  }
437 
438  Optional<MCFixupKind> getFixupKind(StringRef Name) const override {
440  .Case("dir32", FK_Data_4)
441  .Case("secrel32", FK_SecRel_4)
442  .Case("secidx", FK_SecRel_2)
444  }
445 
446  MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
447  return createX86WinCOFFObjectWriter(OS, Is64Bit);
448  }
449 };
450 
451 namespace CU {
452 
453  /// Compact unwind encoding values.
455  /// [RE]BP based frame where [RE]BP is pused on the stack immediately after
456  /// the return address, then [RE]SP is moved to [RE]BP.
457  UNWIND_MODE_BP_FRAME = 0x01000000,
458 
459  /// A frameless function with a small constant stack size.
460  UNWIND_MODE_STACK_IMMD = 0x02000000,
461 
462  /// A frameless function with a large constant stack size.
463  UNWIND_MODE_STACK_IND = 0x03000000,
464 
465  /// No compact unwind encoding is available.
466  UNWIND_MODE_DWARF = 0x04000000,
467 
468  /// Mask for encoding the frame registers.
469  UNWIND_BP_FRAME_REGISTERS = 0x00007FFF,
470 
471  /// Mask for encoding the frameless registers.
472  UNWIND_FRAMELESS_STACK_REG_PERMUTATION = 0x000003FF
473  };
474 
475 } // end CU namespace
476 
477 class DarwinX86AsmBackend : public X86AsmBackend {
478  const MCRegisterInfo &MRI;
479 
480  /// \brief Number of registers that can be saved in a compact unwind encoding.
481  enum { CU_NUM_SAVED_REGS = 6 };
482 
483  mutable unsigned SavedRegs[CU_NUM_SAVED_REGS];
484  bool Is64Bit;
485 
486  unsigned OffsetSize; ///< Offset of a "push" instruction.
487  unsigned MoveInstrSize; ///< Size of a "move" instruction.
488  unsigned StackDivide; ///< Amount to adjust stack size by.
489 protected:
490  /// \brief Size of a "push" instruction for the given register.
491  unsigned PushInstrSize(unsigned Reg) const {
492  switch (Reg) {
493  case X86::EBX:
494  case X86::ECX:
495  case X86::EDX:
496  case X86::EDI:
497  case X86::ESI:
498  case X86::EBP:
499  case X86::RBX:
500  case X86::RBP:
501  return 1;
502  case X86::R12:
503  case X86::R13:
504  case X86::R14:
505  case X86::R15:
506  return 2;
507  }
508  return 1;
509  }
510 
511  /// \brief Implementation of algorithm to generate the compact unwind encoding
512  /// for the CFI instructions.
513  uint32_t
514  generateCompactUnwindEncodingImpl(ArrayRef<MCCFIInstruction> Instrs) const {
515  if (Instrs.empty()) return 0;
516 
517  // Reset the saved registers.
518  unsigned SavedRegIdx = 0;
519  memset(SavedRegs, 0, sizeof(SavedRegs));
520 
521  bool HasFP = false;
522 
523  // Encode that we are using EBP/RBP as the frame pointer.
524  uint32_t CompactUnwindEncoding = 0;
525 
526  unsigned SubtractInstrIdx = Is64Bit ? 3 : 2;
527  unsigned InstrOffset = 0;
528  unsigned StackAdjust = 0;
529  unsigned StackSize = 0;
530  unsigned PrevStackSize = 0;
531  unsigned NumDefCFAOffsets = 0;
532 
533  for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
534  const MCCFIInstruction &Inst = Instrs[i];
535 
536  switch (Inst.getOperation()) {
537  default:
538  // Any other CFI directives indicate a frame that we aren't prepared
539  // to represent via compact unwind, so just bail out.
540  return 0;
542  // Defines a frame pointer. E.g.
543  //
544  // movq %rsp, %rbp
545  // L0:
546  // .cfi_def_cfa_register %rbp
547  //
548  HasFP = true;
549 
550  // If the frame pointer is other than esp/rsp, we do not have a way to
551  // generate a compact unwinding representation, so bail out.
552  if (MRI.getLLVMRegNum(Inst.getRegister(), true) !=
553  (Is64Bit ? X86::RBP : X86::EBP))
554  return 0;
555 
556  // Reset the counts.
557  memset(SavedRegs, 0, sizeof(SavedRegs));
558  StackAdjust = 0;
559  SavedRegIdx = 0;
560  InstrOffset += MoveInstrSize;
561  break;
562  }
564  // Defines a new offset for the CFA. E.g.
565  //
566  // With frame:
567  //
568  // pushq %rbp
569  // L0:
570  // .cfi_def_cfa_offset 16
571  //
572  // Without frame:
573  //
574  // subq $72, %rsp
575  // L0:
576  // .cfi_def_cfa_offset 80
577  //
578  PrevStackSize = StackSize;
579  StackSize = std::abs(Inst.getOffset()) / StackDivide;
580  ++NumDefCFAOffsets;
581  break;
582  }
584  // Defines a "push" of a callee-saved register. E.g.
585  //
586  // pushq %r15
587  // pushq %r14
588  // pushq %rbx
589  // L0:
590  // subq $120, %rsp
591  // L1:
592  // .cfi_offset %rbx, -40
593  // .cfi_offset %r14, -32
594  // .cfi_offset %r15, -24
595  //
596  if (SavedRegIdx == CU_NUM_SAVED_REGS)
597  // If there are too many saved registers, we cannot use a compact
598  // unwind encoding.
599  return CU::UNWIND_MODE_DWARF;
600 
601  unsigned Reg = MRI.getLLVMRegNum(Inst.getRegister(), true);
602  SavedRegs[SavedRegIdx++] = Reg;
603  StackAdjust += OffsetSize;
604  InstrOffset += PushInstrSize(Reg);
605  break;
606  }
607  }
608  }
609 
610  StackAdjust /= StackDivide;
611 
612  if (HasFP) {
613  if ((StackAdjust & 0xFF) != StackAdjust)
614  // Offset was too big for a compact unwind encoding.
615  return CU::UNWIND_MODE_DWARF;
616 
617  // Get the encoding of the saved registers when we have a frame pointer.
618  uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame();
619  if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
620 
621  CompactUnwindEncoding |= CU::UNWIND_MODE_BP_FRAME;
622  CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16;
623  CompactUnwindEncoding |= RegEnc & CU::UNWIND_BP_FRAME_REGISTERS;
624  } else {
625  // If the amount of the stack allocation is the size of a register, then
626  // we "push" the RAX/EAX register onto the stack instead of adjusting the
627  // stack pointer with a SUB instruction. We don't support the push of the
628  // RAX/EAX register with compact unwind. So we check for that situation
629  // here.
630  if ((NumDefCFAOffsets == SavedRegIdx + 1 &&
631  StackSize - PrevStackSize == 1) ||
632  (Instrs.size() == 1 && NumDefCFAOffsets == 1 && StackSize == 2))
633  return CU::UNWIND_MODE_DWARF;
634 
635  SubtractInstrIdx += InstrOffset;
636  ++StackAdjust;
637 
638  if ((StackSize & 0xFF) == StackSize) {
639  // Frameless stack with a small stack size.
640  CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IMMD;
641 
642  // Encode the stack size.
643  CompactUnwindEncoding |= (StackSize & 0xFF) << 16;
644  } else {
645  if ((StackAdjust & 0x7) != StackAdjust)
646  // The extra stack adjustments are too big for us to handle.
647  return CU::UNWIND_MODE_DWARF;
648 
649  // Frameless stack with an offset too large for us to encode compactly.
650  CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IND;
651 
652  // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
653  // instruction.
654  CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
655 
656  // Encode any extra stack stack adjustments (done via push
657  // instructions).
658  CompactUnwindEncoding |= (StackAdjust & 0x7) << 13;
659  }
660 
661  // Encode the number of registers saved. (Reverse the list first.)
662  std::reverse(&SavedRegs[0], &SavedRegs[SavedRegIdx]);
663  CompactUnwindEncoding |= (SavedRegIdx & 0x7) << 10;
664 
665  // Get the encoding of the saved registers when we don't have a frame
666  // pointer.
667  uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegIdx);
668  if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
669 
670  // Encode the register encoding.
671  CompactUnwindEncoding |=
672  RegEnc & CU::UNWIND_FRAMELESS_STACK_REG_PERMUTATION;
673  }
674 
675  return CompactUnwindEncoding;
676  }
677 
678 private:
679  /// \brief Get the compact unwind number for a given register. The number
680  /// corresponds to the enum lists in compact_unwind_encoding.h.
681  int getCompactUnwindRegNum(unsigned Reg) const {
682  static const MCPhysReg CU32BitRegs[7] = {
683  X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
684  };
685  static const MCPhysReg CU64BitRegs[] = {
686  X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
687  };
688  const MCPhysReg *CURegs = Is64Bit ? CU64BitRegs : CU32BitRegs;
689  for (int Idx = 1; *CURegs; ++CURegs, ++Idx)
690  if (*CURegs == Reg)
691  return Idx;
692 
693  return -1;
694  }
695 
696  /// \brief Return the registers encoded for a compact encoding with a frame
697  /// pointer.
698  uint32_t encodeCompactUnwindRegistersWithFrame() const {
699  // Encode the registers in the order they were saved --- 3-bits per
700  // register. The list of saved registers is assumed to be in reverse
701  // order. The registers are numbered from 1 to CU_NUM_SAVED_REGS.
702  uint32_t RegEnc = 0;
703  for (int i = 0, Idx = 0; i != CU_NUM_SAVED_REGS; ++i) {
704  unsigned Reg = SavedRegs[i];
705  if (Reg == 0) break;
706 
707  int CURegNum = getCompactUnwindRegNum(Reg);
708  if (CURegNum == -1) return ~0U;
709 
710  // Encode the 3-bit register number in order, skipping over 3-bits for
711  // each register.
712  RegEnc |= (CURegNum & 0x7) << (Idx++ * 3);
713  }
714 
715  assert((RegEnc & 0x3FFFF) == RegEnc &&
716  "Invalid compact register encoding!");
717  return RegEnc;
718  }
719 
720  /// \brief Create the permutation encoding used with frameless stacks. It is
721  /// passed the number of registers to be saved and an array of the registers
722  /// saved.
723  uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned RegCount) const {
724  // The saved registers are numbered from 1 to 6. In order to encode the
725  // order in which they were saved, we re-number them according to their
726  // place in the register order. The re-numbering is relative to the last
727  // re-numbered register. E.g., if we have registers {6, 2, 4, 5} saved in
728  // that order:
729  //
730  // Orig Re-Num
731  // ---- ------
732  // 6 6
733  // 2 2
734  // 4 3
735  // 5 3
736  //
737  for (unsigned i = 0; i < RegCount; ++i) {
738  int CUReg = getCompactUnwindRegNum(SavedRegs[i]);
739  if (CUReg == -1) return ~0U;
740  SavedRegs[i] = CUReg;
741  }
742 
743  // Reverse the list.
744  std::reverse(&SavedRegs[0], &SavedRegs[CU_NUM_SAVED_REGS]);
745 
746  uint32_t RenumRegs[CU_NUM_SAVED_REGS];
747  for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i){
748  unsigned Countless = 0;
749  for (unsigned j = CU_NUM_SAVED_REGS - RegCount; j < i; ++j)
750  if (SavedRegs[j] < SavedRegs[i])
751  ++Countless;
752 
753  RenumRegs[i] = SavedRegs[i] - Countless - 1;
754  }
755 
756  // Take the renumbered values and encode them into a 10-bit number.
757  uint32_t permutationEncoding = 0;
758  switch (RegCount) {
759  case 6:
760  permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
761  + 6 * RenumRegs[2] + 2 * RenumRegs[3]
762  + RenumRegs[4];
763  break;
764  case 5:
765  permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
766  + 6 * RenumRegs[3] + 2 * RenumRegs[4]
767  + RenumRegs[5];
768  break;
769  case 4:
770  permutationEncoding |= 60 * RenumRegs[2] + 12 * RenumRegs[3]
771  + 3 * RenumRegs[4] + RenumRegs[5];
772  break;
773  case 3:
774  permutationEncoding |= 20 * RenumRegs[3] + 4 * RenumRegs[4]
775  + RenumRegs[5];
776  break;
777  case 2:
778  permutationEncoding |= 5 * RenumRegs[4] + RenumRegs[5];
779  break;
780  case 1:
781  permutationEncoding |= RenumRegs[5];
782  break;
783  }
784 
785  assert((permutationEncoding & 0x3FF) == permutationEncoding &&
786  "Invalid compact register encoding!");
787  return permutationEncoding;
788  }
789 
790 public:
791  DarwinX86AsmBackend(const Target &T, const MCRegisterInfo &MRI, StringRef CPU,
792  bool Is64Bit)
793  : X86AsmBackend(T, CPU), MRI(MRI), Is64Bit(Is64Bit) {
794  memset(SavedRegs, 0, sizeof(SavedRegs));
795  OffsetSize = Is64Bit ? 8 : 4;
796  MoveInstrSize = Is64Bit ? 3 : 2;
797  StackDivide = Is64Bit ? 8 : 4;
798  }
799 };
800 
801 class DarwinX86_32AsmBackend : public DarwinX86AsmBackend {
802 public:
803  DarwinX86_32AsmBackend(const Target &T, const MCRegisterInfo &MRI,
804  StringRef CPU)
805  : DarwinX86AsmBackend(T, MRI, CPU, false) {}
806 
807  MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
808  return createX86MachObjectWriter(OS, /*Is64Bit=*/false,
811  }
812 
813  /// \brief Generate the compact unwind encoding for the CFI instructions.
814  uint32_t generateCompactUnwindEncoding(
815  ArrayRef<MCCFIInstruction> Instrs) const override {
816  return generateCompactUnwindEncodingImpl(Instrs);
817  }
818 };
819 
820 class DarwinX86_64AsmBackend : public DarwinX86AsmBackend {
821  const MachO::CPUSubTypeX86 Subtype;
822 public:
823  DarwinX86_64AsmBackend(const Target &T, const MCRegisterInfo &MRI,
825  : DarwinX86AsmBackend(T, MRI, CPU, true), Subtype(st) {}
826 
827  MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
828  return createX86MachObjectWriter(OS, /*Is64Bit=*/true,
829  MachO::CPU_TYPE_X86_64, Subtype);
830  }
831 
832  /// \brief Generate the compact unwind encoding for the CFI instructions.
833  uint32_t generateCompactUnwindEncoding(
834  ArrayRef<MCCFIInstruction> Instrs) const override {
835  return generateCompactUnwindEncodingImpl(Instrs);
836  }
837 };
838 
839 } // end anonymous namespace
840 
842  const MCRegisterInfo &MRI,
843  const Triple &TheTriple,
844  StringRef CPU,
845  const MCTargetOptions &Options) {
846  if (TheTriple.isOSBinFormatMachO())
847  return new DarwinX86_32AsmBackend(T, MRI, CPU);
848 
849  if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
850  return new WindowsX86AsmBackend(T, false, CPU);
851 
852  uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
853 
854  if (TheTriple.isOSIAMCU())
855  return new ELFX86_IAMCUAsmBackend(T, OSABI, CPU);
856 
857  return new ELFX86_32AsmBackend(T, OSABI, CPU);
858 }
859 
861  const MCRegisterInfo &MRI,
862  const Triple &TheTriple,
863  StringRef CPU,
864  const MCTargetOptions &Options) {
865  if (TheTriple.isOSBinFormatMachO()) {
868  .Case("x86_64h", MachO::CPU_SUBTYPE_X86_64_H)
870  return new DarwinX86_64AsmBackend(T, MRI, CPU, CS);
871  }
872 
873  if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
874  return new WindowsX86AsmBackend(T, true, CPU);
875 
876  uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
877 
878  if (TheTriple.getEnvironment() == Triple::GNUX32)
879  return new ELFX86_X32AsmBackend(T, OSABI, CPU);
880  return new ELFX86_64AsmBackend(T, OSABI, CPU);
881 }
OSType getOS() const
getOS - Get the parsed operating system type of this triple.
Definition: Triple.h:279
A eight-byte pc relative fixup.
Definition: MCFixup.h:31
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition: Triple.h:575
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
size_t i
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:490
bool isOSIAMCU() const
Definition: Triple.h:485
Defines the object file and target independent interfaces used by the assembler backend to write nati...
void write8(uint8_t Value)
unsigned getRegister() const
Definition: MCDwarf.h:464
void dump_pretty(raw_ostream &OS, const MCInstPrinter *Printer=nullptr, StringRef Separator=" ") const
Dump the MCInst as prettily as possible using the additional MC structures, if given.
Definition: MCInst.cpp:51
bool isOSWindows() const
Tests whether the OS is Windows.
Definition: Triple.h:540
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:66
Is this fixup kind PCrelative? This is used by the assembler backend to evaluate fixup values in a ta...
A one-byte pc relative fixup.
Definition: MCFixup.h:28
int getOffset() const
Definition: MCDwarf.h:477
MCObjectWriter * createX86WinCOFFObjectWriter(raw_pwrite_stream &OS, bool Is64Bit)
Construct an X86 Win COFF object writer.
Encapsulates the layout of an assembly file at a particular point in time.
Definition: MCAsmLayout.h:29
LLVM_ATTRIBUTE_ALWAYS_INLINE R Default(const T &Value) const
Definition: StringSwitch.h:244
Reg
All possible values of the reg field in the ModR/M byte.
A four-byte section relative fixup.
Definition: MCFixup.h:42
A four-byte fixup.
Definition: MCFixup.h:26
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:241
LLVM_ATTRIBUTE_ALWAYS_INLINE StringSwitch & Case(const char(&S)[N], const T &Value)
Definition: StringSwitch.h:74
const MCSubtargetInfo * STI
A two-byte section relative fixup.
Definition: MCFixup.h:41
Function Alias Analysis false
CompactUnwindEncodings
Compact unwind encoding values.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
uint32_t getOffset() const
Definition: MCFixup.h:95
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:141
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with etc Experimental Use value profile to guide fuzzing Number of simultaneous worker processes to run the jobs If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:150
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
A relaxable fragment holds on to its MCInst, since it may need to be relaxed during the assembler lay...
Definition: MCFragment.h:249
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:43
unsigned const MachineRegisterInfo * MRI
MCObjectWriter * createX86MachObjectWriter(raw_pwrite_stream &OS, bool Is64Bit, uint32_t CPUType, uint32_t CPUSubtype)
Construct an X86 Mach-O object writer.
static bool is64Bit(const char *name)
MCFixupKind
Extensible enumeration to represent the type of a fixup.
Definition: MCFixup.h:23
virtual Optional< MCFixupKind > getFixupKind(StringRef Name) const
Map a relocation name used in .reloc to a fixup kind.
bool isExpr() const
Definition: MCInst.h:59
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:136
static unsigned getFixupKindLog2Size(unsigned Kind)
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition: Triple.h:570
static unsigned getRelaxedOpcodeArith(const MCInst &Inst)
bool isIntN(unsigned N, int64_t x)
isIntN - Checks if an signed integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:366
MCFixupKind getKind() const
Definition: MCFixup.h:93
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
A one-byte fixup.
Definition: MCFixup.h:24
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
OpType getOperation() const
Definition: MCDwarf.h:461
MCAsmBackend * createX86_64AsmBackend(const Target &T, const MCRegisterInfo &MRI, const Triple &TT, StringRef CPU, const MCTargetOptions &Options)
void setOpcode(unsigned Op)
Definition: MCInst.h:158
A two-byte pc relative fixup.
Definition: MCFixup.h:29
A four-byte pc relative fixup.
Definition: MCFixup.h:30
const FeatureBitset & getFeatureBits() const
getFeatureBits - Return the feature bits.
static unsigned getRelaxedOpcodeBranch(const MCInst &Inst, bool is16BitMode)
MCObjectWriter * createX86ELFObjectWriter(raw_pwrite_stream &OS, bool IsELF64, uint8_t OSABI, uint16_t EMachine)
Construct an X86 ELF object writer.
unsigned getOpcode() const
Definition: MCInst.h:159
Target - Wrapper for Target specific information.
A one-byte section relative fixup.
Definition: MCFixup.h:40
Basic Alias true
static unsigned getRelaxedOpcode(const MCInst &Inst, bool is16BitMode)
A eight-byte section relative fixup.
Definition: MCFixup.h:43
unsigned getNumOperands() const
Definition: MCInst.h:166
StringRef getArchName() const
getArchName - Get the architecture (first) component of the triple.
Definition: Triple.cpp:903
APFloat abs(APFloat X)
Returns the absolute value of the argument.
Definition: APFloat.h:1099
MCSubtargetInfo - Generic base class for all target subtargets.
A eight-byte fixup.
Definition: MCFixup.h:27
MCAsmBackend * createX86_32AsmBackend(const Target &T, const MCRegisterInfo &MRI, const Triple &TT, StringRef CPU, const MCTargetOptions &Options)
Target independent information on a fixup kind.
EnvironmentType getEnvironment() const
getEnvironment - Get the parsed environment type of this triple.
Definition: Triple.h:288
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:333
const unsigned Kind
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:71
Generic interface to target specific assembler backends.
Definition: MCAsmBackend.h:36
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
virtual const MCFixupKindInfo & getFixupKindInfo(MCFixupKind Kind) const
Get information on a fixup kind.
A two-byte fixup.
Definition: MCFixup.h:25
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:164