Coverage Report

Created: 2025-07-18 06:59

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