1 //===-- ARMAsmBackend.cpp - ARM Assembler Backend -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MCTargetDesc/ARMMCTargetDesc.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "MCTargetDesc/ARMAsmBackend.h"
13 #include "MCTargetDesc/ARMAsmBackendDarwin.h"
14 #include "MCTargetDesc/ARMAsmBackendELF.h"
15 #include "MCTargetDesc/ARMAsmBackendWinCOFF.h"
16 #include "MCTargetDesc/ARMBaseInfo.h"
17 #include "MCTargetDesc/ARMFixupKinds.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/MC/MCAsmBackend.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCDirectives.h"
23 #include "llvm/MC/MCELFObjectWriter.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCFixupKindInfo.h"
26 #include "llvm/MC/MCMachObjectWriter.h"
27 #include "llvm/MC/MCObjectWriter.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSectionELF.h"
30 #include "llvm/MC/MCSectionMachO.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/MC/MCValue.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ELF.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/MachO.h"
38 #include "llvm/Support/TargetParser.h"
39 #include "llvm/Support/raw_ostream.h"
43 class ARMELFObjectWriter : public MCELFObjectTargetWriter {
45 ARMELFObjectWriter(uint8_t OSABI)
46 : MCELFObjectTargetWriter(/*Is64Bit*/ false, OSABI, ELF::EM_ARM,
47 /*HasRelocationAddend*/ false) {}
50 const MCFixupKindInfo &ARMAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
51 const static MCFixupKindInfo InfosLE[ARM::NumTargetFixupKinds] = {
52 // This table *must* be in the order that the fixup_* kinds are defined in
55 // Name Offset (bits) Size (bits) Flags
56 {"fixup_arm_ldst_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
57 {"fixup_t2_ldst_pcrel_12", 0, 32,
58 MCFixupKindInfo::FKF_IsPCRel |
59 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
60 {"fixup_arm_pcrel_10_unscaled", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
61 {"fixup_arm_pcrel_10", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
62 {"fixup_t2_pcrel_10", 0, 32,
63 MCFixupKindInfo::FKF_IsPCRel |
64 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
65 {"fixup_thumb_adr_pcrel_10", 0, 8,
66 MCFixupKindInfo::FKF_IsPCRel |
67 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
68 {"fixup_arm_adr_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
69 {"fixup_t2_adr_pcrel_12", 0, 32,
70 MCFixupKindInfo::FKF_IsPCRel |
71 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
72 {"fixup_arm_condbranch", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
73 {"fixup_arm_uncondbranch", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
74 {"fixup_t2_condbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
75 {"fixup_t2_uncondbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
76 {"fixup_arm_thumb_br", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
77 {"fixup_arm_uncondbl", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
78 {"fixup_arm_condbl", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
79 {"fixup_arm_blx", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
80 {"fixup_arm_thumb_bl", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
81 {"fixup_arm_thumb_blx", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
82 {"fixup_arm_thumb_cb", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
83 {"fixup_arm_thumb_cp", 0, 8,
84 MCFixupKindInfo::FKF_IsPCRel |
85 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
86 {"fixup_arm_thumb_bcc", 0, 8, MCFixupKindInfo::FKF_IsPCRel},
87 // movw / movt: 16-bits immediate but scattered into two chunks 0 - 12, 16
89 {"fixup_arm_movt_hi16", 0, 20, 0},
90 {"fixup_arm_movw_lo16", 0, 20, 0},
91 {"fixup_t2_movt_hi16", 0, 20, 0},
92 {"fixup_t2_movw_lo16", 0, 20, 0},
94 const static MCFixupKindInfo InfosBE[ARM::NumTargetFixupKinds] = {
95 // This table *must* be in the order that the fixup_* kinds are defined in
98 // Name Offset (bits) Size (bits) Flags
99 {"fixup_arm_ldst_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
100 {"fixup_t2_ldst_pcrel_12", 0, 32,
101 MCFixupKindInfo::FKF_IsPCRel |
102 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
103 {"fixup_arm_pcrel_10_unscaled", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
104 {"fixup_arm_pcrel_10", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
105 {"fixup_t2_pcrel_10", 0, 32,
106 MCFixupKindInfo::FKF_IsPCRel |
107 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
108 {"fixup_thumb_adr_pcrel_10", 8, 8,
109 MCFixupKindInfo::FKF_IsPCRel |
110 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
111 {"fixup_arm_adr_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
112 {"fixup_t2_adr_pcrel_12", 0, 32,
113 MCFixupKindInfo::FKF_IsPCRel |
114 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
115 {"fixup_arm_condbranch", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
116 {"fixup_arm_uncondbranch", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
117 {"fixup_t2_condbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
118 {"fixup_t2_uncondbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
119 {"fixup_arm_thumb_br", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
120 {"fixup_arm_uncondbl", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
121 {"fixup_arm_condbl", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
122 {"fixup_arm_blx", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
123 {"fixup_arm_thumb_bl", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
124 {"fixup_arm_thumb_blx", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
125 {"fixup_arm_thumb_cb", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
126 {"fixup_arm_thumb_cp", 8, 8,
127 MCFixupKindInfo::FKF_IsPCRel |
128 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
129 {"fixup_arm_thumb_bcc", 8, 8, MCFixupKindInfo::FKF_IsPCRel},
130 // movw / movt: 16-bits immediate but scattered into two chunks 0 - 12, 16
132 {"fixup_arm_movt_hi16", 12, 20, 0},
133 {"fixup_arm_movw_lo16", 12, 20, 0},
134 {"fixup_t2_movt_hi16", 12, 20, 0},
135 {"fixup_t2_movw_lo16", 12, 20, 0},
138 if (Kind < FirstTargetFixupKind)
139 return MCAsmBackend::getFixupKindInfo(Kind);
141 assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
143 return (IsLittleEndian ? InfosLE : InfosBE)[Kind - FirstTargetFixupKind];
146 void ARMAsmBackend::handleAssemblerFlag(MCAssemblerFlag Flag) {
158 } // end anonymous namespace
160 unsigned ARMAsmBackend::getRelaxedOpcode(unsigned Op) const {
161 bool HasThumb2 = STI->getFeatureBits()[ARM::FeatureThumb2];
167 return HasThumb2 ? (unsigned)ARM::t2Bcc : Op;
169 return HasThumb2 ? (unsigned)ARM::t2LDRpci : Op;
171 return HasThumb2 ? (unsigned)ARM::t2ADR : Op;
173 return HasThumb2 ? (unsigned)ARM::t2B : Op;
181 bool ARMAsmBackend::mayNeedRelaxation(const MCInst &Inst) const {
182 if (getRelaxedOpcode(Inst.getOpcode()) != Inst.getOpcode())
187 const char *ARMAsmBackend::reasonForFixupRelaxation(const MCFixup &Fixup,
188 uint64_t Value) const {
189 switch ((unsigned)Fixup.getKind()) {
190 case ARM::fixup_arm_thumb_br: {
191 // Relaxing tB to t2B. tB has a signed 12-bit displacement with the
192 // low bit being an implied zero. There's an implied +4 offset for the
193 // branch, so we adjust the other way here to determine what's
196 // Relax if the value is too big for a (signed) i8.
197 int64_t Offset = int64_t(Value) - 4;
198 if (Offset > 2046 || Offset < -2048)
199 return "out of range pc-relative fixup value";
202 case ARM::fixup_arm_thumb_bcc: {
203 // Relaxing tBcc to t2Bcc. tBcc has a signed 9-bit displacement with the
204 // low bit being an implied zero. There's an implied +4 offset for the
205 // branch, so we adjust the other way here to determine what's
208 // Relax if the value is too big for a (signed) i8.
209 int64_t Offset = int64_t(Value) - 4;
210 if (Offset > 254 || Offset < -256)
211 return "out of range pc-relative fixup value";
214 case ARM::fixup_thumb_adr_pcrel_10:
215 case ARM::fixup_arm_thumb_cp: {
216 // If the immediate is negative, greater than 1020, or not a multiple
217 // of four, the wide version of the instruction must be used.
218 int64_t Offset = int64_t(Value) - 4;
220 return "misaligned pc-relative fixup value";
221 else if (Offset > 1020 || Offset < 0)
222 return "out of range pc-relative fixup value";
225 case ARM::fixup_arm_thumb_cb: {
226 // If we have a Thumb CBZ or CBNZ instruction and its target is the next
227 // instruction it is is actually out of range for the instruction.
228 // It will be changed to a NOP.
229 int64_t Offset = (Value & ~1);
231 return "will be converted to nop";
235 llvm_unreachable("Unexpected fixup kind in reasonForFixupRelaxation()!");
240 bool ARMAsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
241 const MCRelaxableFragment *DF,
242 const MCAsmLayout &Layout) const {
243 return reasonForFixupRelaxation(Fixup, Value);
246 void ARMAsmBackend::relaxInstruction(const MCInst &Inst, MCInst &Res) const {
247 unsigned RelaxedOp = getRelaxedOpcode(Inst.getOpcode());
249 // Sanity check w/ diagnostic if we get here w/ a bogus instruction.
250 if (RelaxedOp == Inst.getOpcode()) {
251 SmallString<256> Tmp;
252 raw_svector_ostream OS(Tmp);
253 Inst.dump_pretty(OS);
255 report_fatal_error("unexpected instruction to relax: " + OS.str());
258 // If we are changing Thumb CBZ or CBNZ instruction to a NOP, aka tHINT, we
259 // have to change the operands too.
260 if ((Inst.getOpcode() == ARM::tCBZ || Inst.getOpcode() == ARM::tCBNZ) &&
261 RelaxedOp == ARM::tHINT) {
262 Res.setOpcode(RelaxedOp);
263 Res.addOperand(MCOperand::createImm(0));
264 Res.addOperand(MCOperand::createImm(14));
265 Res.addOperand(MCOperand::createReg(0));
269 // The rest of instructions we're relaxing have the same operands.
270 // We just need to update to the proper opcode.
272 Res.setOpcode(RelaxedOp);
275 bool ARMAsmBackend::writeNopData(uint64_t Count, MCObjectWriter *OW) const {
276 const uint16_t Thumb1_16bitNopEncoding = 0x46c0; // using MOV r8,r8
277 const uint16_t Thumb2_16bitNopEncoding = 0xbf00; // NOP
278 const uint32_t ARMv4_NopEncoding = 0xe1a00000; // using MOV r0,r0
279 const uint32_t ARMv6T2_NopEncoding = 0xe320f000; // NOP
281 const uint16_t nopEncoding =
282 hasNOP() ? Thumb2_16bitNopEncoding : Thumb1_16bitNopEncoding;
283 uint64_t NumNops = Count / 2;
284 for (uint64_t i = 0; i != NumNops; ++i)
285 OW->write16(nopEncoding);
291 const uint32_t nopEncoding =
292 hasNOP() ? ARMv6T2_NopEncoding : ARMv4_NopEncoding;
293 uint64_t NumNops = Count / 4;
294 for (uint64_t i = 0; i != NumNops; ++i)
295 OW->write32(nopEncoding);
296 // FIXME: should this function return false when unable to write exactly
297 // 'Count' bytes with NOP encodings?
300 break; // No leftover bytes to write
316 static uint32_t swapHalfWords(uint32_t Value, bool IsLittleEndian) {
317 if (IsLittleEndian) {
318 // Note that the halfwords are stored high first and low second in thumb;
319 // so we need to swap the fixup value here to map properly.
320 uint32_t Swapped = (Value & 0xFFFF0000) >> 16;
321 Swapped |= (Value & 0x0000FFFF) << 16;
327 static uint32_t joinHalfWords(uint32_t FirstHalf, uint32_t SecondHalf,
328 bool IsLittleEndian) {
331 if (IsLittleEndian) {
332 Value = (SecondHalf & 0xFFFF) << 16;
333 Value |= (FirstHalf & 0xFFFF);
335 Value = (SecondHalf & 0xFFFF);
336 Value |= (FirstHalf & 0xFFFF) << 16;
342 unsigned ARMAsmBackend::adjustFixupValue(const MCFixup &Fixup, uint64_t Value,
343 bool IsPCRel, MCContext *Ctx,
345 bool IsResolved) const {
346 unsigned Kind = Fixup.getKind();
349 llvm_unreachable("Unknown fixup kind!");
358 case ARM::fixup_arm_movt_hi16:
362 case ARM::fixup_arm_movw_lo16: {
363 unsigned Hi4 = (Value & 0xF000) >> 12;
364 unsigned Lo12 = Value & 0x0FFF;
365 // inst{19-16} = Hi4;
366 // inst{11-0} = Lo12;
367 Value = (Hi4 << 16) | (Lo12);
370 case ARM::fixup_t2_movt_hi16:
374 case ARM::fixup_t2_movw_lo16: {
375 unsigned Hi4 = (Value & 0xF000) >> 12;
376 unsigned i = (Value & 0x800) >> 11;
377 unsigned Mid3 = (Value & 0x700) >> 8;
378 unsigned Lo8 = Value & 0x0FF;
379 // inst{19-16} = Hi4;
381 // inst{14-12} = Mid3;
383 Value = (Hi4 << 16) | (i << 26) | (Mid3 << 12) | (Lo8);
384 return swapHalfWords(Value, IsLittleEndian);
386 case ARM::fixup_arm_ldst_pcrel_12:
387 // ARM PC-relative values are offset by 8.
390 case ARM::fixup_t2_ldst_pcrel_12: {
391 // Offset by 4, adjusted by two due to the half-word ordering of thumb.
394 if ((int64_t)Value < 0) {
398 if (Ctx && Value >= 4096) {
399 Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
402 Value |= isAdd << 23;
404 // Same addressing mode as fixup_arm_pcrel_10,
405 // but with 16-bit halfwords swapped.
406 if (Kind == ARM::fixup_t2_ldst_pcrel_12)
407 return swapHalfWords(Value, IsLittleEndian);
411 case ARM::fixup_arm_adr_pcrel_12: {
412 // ARM PC-relative values are offset by 8.
414 unsigned opc = 4; // bits {24-21}. Default to add: 0b0100
415 if ((int64_t)Value < 0) {
419 if (Ctx && ARM_AM::getSOImmVal(Value) == -1) {
420 Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
423 // Encode the immediate and shift the opcode into place.
424 return ARM_AM::getSOImmVal(Value) | (opc << 21);
427 case ARM::fixup_t2_adr_pcrel_12: {
430 if ((int64_t)Value < 0) {
435 uint32_t out = (opc << 21);
436 out |= (Value & 0x800) << 15;
437 out |= (Value & 0x700) << 4;
438 out |= (Value & 0x0FF);
440 return swapHalfWords(out, IsLittleEndian);
443 case ARM::fixup_arm_condbranch:
444 case ARM::fixup_arm_uncondbranch:
445 case ARM::fixup_arm_uncondbl:
446 case ARM::fixup_arm_condbl:
447 case ARM::fixup_arm_blx:
448 // These values don't encode the low two bits since they're always zero.
449 // Offset by 8 just as above.
450 if (const MCSymbolRefExpr *SRE =
451 dyn_cast<MCSymbolRefExpr>(Fixup.getValue()))
452 if (SRE->getKind() == MCSymbolRefExpr::VK_ARM_TLSCALL)
454 return 0xffffff & ((Value - 8) >> 2);
455 case ARM::fixup_t2_uncondbranch: {
457 Value >>= 1; // Low bit is not encoded.
460 bool I = Value & 0x800000;
461 bool J1 = Value & 0x400000;
462 bool J2 = Value & 0x200000;
466 out |= I << 26; // S bit
467 out |= !J1 << 13; // J1 bit
468 out |= !J2 << 11; // J2 bit
469 out |= (Value & 0x1FF800) << 5; // imm6 field
470 out |= (Value & 0x0007FF); // imm11 field
472 return swapHalfWords(out, IsLittleEndian);
474 case ARM::fixup_t2_condbranch: {
476 Value >>= 1; // Low bit is not encoded.
479 out |= (Value & 0x80000) << 7; // S bit
480 out |= (Value & 0x40000) >> 7; // J2 bit
481 out |= (Value & 0x20000) >> 4; // J1 bit
482 out |= (Value & 0x1F800) << 5; // imm6 field
483 out |= (Value & 0x007FF); // imm11 field
485 return swapHalfWords(out, IsLittleEndian);
487 case ARM::fixup_arm_thumb_bl: {
488 // The value doesn't encode the low bit (always zero) and is offset by
489 // four. The 32-bit immediate value is encoded as
490 // imm32 = SignExtend(S:I1:I2:imm10:imm11:0)
491 // where I1 = NOT(J1 ^ S) and I2 = NOT(J2 ^ S).
492 // The value is encoded into disjoint bit positions in the destination
493 // opcode. x = unchanged, I = immediate value bit, S = sign extension bit,
494 // J = either J1 or J2 bit
496 // BL: xxxxxSIIIIIIIIII xxJxJIIIIIIIIIII
498 // Note that the halfwords are stored high first, low second; so we need
499 // to transpose the fixup value here to map properly.
500 uint32_t offset = (Value - 4) >> 1;
501 uint32_t signBit = (offset & 0x800000) >> 23;
502 uint32_t I1Bit = (offset & 0x400000) >> 22;
503 uint32_t J1Bit = (I1Bit ^ 0x1) ^ signBit;
504 uint32_t I2Bit = (offset & 0x200000) >> 21;
505 uint32_t J2Bit = (I2Bit ^ 0x1) ^ signBit;
506 uint32_t imm10Bits = (offset & 0x1FF800) >> 11;
507 uint32_t imm11Bits = (offset & 0x000007FF);
509 uint32_t FirstHalf = (((uint16_t)signBit << 10) | (uint16_t)imm10Bits);
510 uint32_t SecondHalf = (((uint16_t)J1Bit << 13) | ((uint16_t)J2Bit << 11) |
511 (uint16_t)imm11Bits);
512 return joinHalfWords(FirstHalf, SecondHalf, IsLittleEndian);
514 case ARM::fixup_arm_thumb_blx: {
515 // The value doesn't encode the low two bits (always zero) and is offset by
516 // four (see fixup_arm_thumb_cp). The 32-bit immediate value is encoded as
517 // imm32 = SignExtend(S:I1:I2:imm10H:imm10L:00)
518 // where I1 = NOT(J1 ^ S) and I2 = NOT(J2 ^ S).
519 // The value is encoded into disjoint bit positions in the destination
520 // opcode. x = unchanged, I = immediate value bit, S = sign extension bit,
521 // J = either J1 or J2 bit, 0 = zero.
523 // BLX: xxxxxSIIIIIIIIII xxJxJIIIIIIIIII0
525 // Note that the halfwords are stored high first, low second; so we need
526 // to transpose the fixup value here to map properly.
527 uint32_t offset = (Value - 2) >> 2;
528 if (const MCSymbolRefExpr *SRE =
529 dyn_cast<MCSymbolRefExpr>(Fixup.getValue()))
530 if (SRE->getKind() == MCSymbolRefExpr::VK_ARM_TLSCALL)
532 uint32_t signBit = (offset & 0x400000) >> 22;
533 uint32_t I1Bit = (offset & 0x200000) >> 21;
534 uint32_t J1Bit = (I1Bit ^ 0x1) ^ signBit;
535 uint32_t I2Bit = (offset & 0x100000) >> 20;
536 uint32_t J2Bit = (I2Bit ^ 0x1) ^ signBit;
537 uint32_t imm10HBits = (offset & 0xFFC00) >> 10;
538 uint32_t imm10LBits = (offset & 0x3FF);
540 uint32_t FirstHalf = (((uint16_t)signBit << 10) | (uint16_t)imm10HBits);
541 uint32_t SecondHalf = (((uint16_t)J1Bit << 13) | ((uint16_t)J2Bit << 11) |
542 ((uint16_t)imm10LBits) << 1);
543 return joinHalfWords(FirstHalf, SecondHalf, IsLittleEndian);
545 case ARM::fixup_thumb_adr_pcrel_10:
546 case ARM::fixup_arm_thumb_cp:
547 // On CPUs supporting Thumb2, this will be relaxed to an ldr.w, otherwise we
548 // could have an error on our hands.
549 if (Ctx && !STI->getFeatureBits()[ARM::FeatureThumb2] && IsResolved) {
550 const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
551 if (FixupDiagnostic) {
552 Ctx->reportError(Fixup.getLoc(), FixupDiagnostic);
556 // Offset by 4, and don't encode the low two bits.
557 return ((Value - 4) >> 2) & 0xff;
558 case ARM::fixup_arm_thumb_cb: {
559 // Offset by 4 and don't encode the lower bit, which is always 0.
560 // FIXME: diagnose if no Thumb2
561 uint32_t Binary = (Value - 4) >> 1;
562 return ((Binary & 0x20) << 4) | ((Binary & 0x1f) << 3);
564 case ARM::fixup_arm_thumb_br:
565 // Offset by 4 and don't encode the lower bit, which is always 0.
566 if (Ctx && !STI->getFeatureBits()[ARM::FeatureThumb2]) {
567 const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
568 if (FixupDiagnostic) {
569 Ctx->reportError(Fixup.getLoc(), FixupDiagnostic);
573 return ((Value - 4) >> 1) & 0x7ff;
574 case ARM::fixup_arm_thumb_bcc:
575 // Offset by 4 and don't encode the lower bit, which is always 0.
576 if (Ctx && !STI->getFeatureBits()[ARM::FeatureThumb2]) {
577 const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
578 if (FixupDiagnostic) {
579 Ctx->reportError(Fixup.getLoc(), FixupDiagnostic);
583 return ((Value - 4) >> 1) & 0xff;
584 case ARM::fixup_arm_pcrel_10_unscaled: {
585 Value = Value - 8; // ARM fixups offset by an additional word and don't
586 // need to adjust for the half-word ordering.
588 if ((int64_t)Value < 0) {
592 // The value has the low 4 bits encoded in [3:0] and the high 4 in [11:8].
593 if (Ctx && Value >= 256) {
594 Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
597 Value = (Value & 0xf) | ((Value & 0xf0) << 4);
598 return Value | (isAdd << 23);
600 case ARM::fixup_arm_pcrel_10:
601 Value = Value - 4; // ARM fixups offset by an additional word and don't
602 // need to adjust for the half-word ordering.
604 case ARM::fixup_t2_pcrel_10: {
605 // Offset by 4, adjusted by two due to the half-word ordering of thumb.
608 if ((int64_t)Value < 0) {
612 // These values don't encode the low two bits since they're always zero.
614 if (Ctx && Value >= 256) {
615 Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
618 Value |= isAdd << 23;
620 // Same addressing mode as fixup_arm_pcrel_10, but with 16-bit halfwords
622 if (Kind == ARM::fixup_t2_pcrel_10)
623 return swapHalfWords(Value, IsLittleEndian);
630 void ARMAsmBackend::processFixupValue(const MCAssembler &Asm,
631 const MCAsmLayout &Layout,
632 const MCFixup &Fixup,
633 const MCFragment *DF,
634 const MCValue &Target, uint64_t &Value,
636 const MCSymbolRefExpr *A = Target.getSymA();
637 const MCSymbol *Sym = A ? &A->getSymbol() : nullptr;
638 // Some fixups to thumb function symbols need the low bit (thumb bit)
640 if ((unsigned)Fixup.getKind() != ARM::fixup_arm_ldst_pcrel_12 &&
641 (unsigned)Fixup.getKind() != ARM::fixup_t2_ldst_pcrel_12 &&
642 (unsigned)Fixup.getKind() != ARM::fixup_arm_adr_pcrel_12 &&
643 (unsigned)Fixup.getKind() != ARM::fixup_thumb_adr_pcrel_10 &&
644 (unsigned)Fixup.getKind() != ARM::fixup_t2_adr_pcrel_12 &&
645 (unsigned)Fixup.getKind() != ARM::fixup_arm_thumb_cp) {
647 if (Asm.isThumbFunc(Sym))
651 if (IsResolved && (unsigned)Fixup.getKind() == ARM::fixup_arm_thumb_bl) {
652 assert(Sym && "How did we resolve this?");
654 // If the symbol is external the linker will handle it.
655 // FIXME: Should we handle it as an optimization?
657 // If the symbol is out of range, produce a relocation and hope the
658 // linker can handle it. GNU AS produces an error in this case.
659 if (Sym->isExternal() || Value >= 0x400004)
662 // We must always generate a relocation for BL/BLX instructions if we have
663 // a symbol to reference, as the linker relies on knowing the destination
664 // symbol's thumb-ness to get interworking right.
665 if (A && ((unsigned)Fixup.getKind() == ARM::fixup_arm_thumb_blx ||
666 (unsigned)Fixup.getKind() == ARM::fixup_arm_blx ||
667 (unsigned)Fixup.getKind() == ARM::fixup_arm_uncondbl ||
668 (unsigned)Fixup.getKind() == ARM::fixup_arm_condbl))
671 // Try to get the encoded value for the fixup as-if we're mapping it into
672 // the instruction. This allows adjustFixupValue() to issue a diagnostic
673 // if the value aren't invalid.
674 (void)adjustFixupValue(Fixup, Value, false, &Asm.getContext(),
675 IsLittleEndian, IsResolved);
678 /// getFixupKindNumBytes - The number of bytes the fixup may change.
679 static unsigned getFixupKindNumBytes(unsigned Kind) {
682 llvm_unreachable("Unknown fixup kind!");
685 case ARM::fixup_arm_thumb_bcc:
686 case ARM::fixup_arm_thumb_cp:
687 case ARM::fixup_thumb_adr_pcrel_10:
691 case ARM::fixup_arm_thumb_br:
692 case ARM::fixup_arm_thumb_cb:
695 case ARM::fixup_arm_pcrel_10_unscaled:
696 case ARM::fixup_arm_ldst_pcrel_12:
697 case ARM::fixup_arm_pcrel_10:
698 case ARM::fixup_arm_adr_pcrel_12:
699 case ARM::fixup_arm_uncondbl:
700 case ARM::fixup_arm_condbl:
701 case ARM::fixup_arm_blx:
702 case ARM::fixup_arm_condbranch:
703 case ARM::fixup_arm_uncondbranch:
707 case ARM::fixup_t2_ldst_pcrel_12:
708 case ARM::fixup_t2_condbranch:
709 case ARM::fixup_t2_uncondbranch:
710 case ARM::fixup_t2_pcrel_10:
711 case ARM::fixup_t2_adr_pcrel_12:
712 case ARM::fixup_arm_thumb_bl:
713 case ARM::fixup_arm_thumb_blx:
714 case ARM::fixup_arm_movt_hi16:
715 case ARM::fixup_arm_movw_lo16:
716 case ARM::fixup_t2_movt_hi16:
717 case ARM::fixup_t2_movw_lo16:
727 /// getFixupKindContainerSizeBytes - The number of bytes of the
728 /// container involved in big endian.
729 static unsigned getFixupKindContainerSizeBytes(unsigned Kind) {
732 llvm_unreachable("Unknown fixup kind!");
741 case ARM::fixup_arm_thumb_bcc:
742 case ARM::fixup_arm_thumb_cp:
743 case ARM::fixup_thumb_adr_pcrel_10:
744 case ARM::fixup_arm_thumb_br:
745 case ARM::fixup_arm_thumb_cb:
746 // Instruction size is 2 bytes.
749 case ARM::fixup_arm_pcrel_10_unscaled:
750 case ARM::fixup_arm_ldst_pcrel_12:
751 case ARM::fixup_arm_pcrel_10:
752 case ARM::fixup_arm_adr_pcrel_12:
753 case ARM::fixup_arm_uncondbl:
754 case ARM::fixup_arm_condbl:
755 case ARM::fixup_arm_blx:
756 case ARM::fixup_arm_condbranch:
757 case ARM::fixup_arm_uncondbranch:
758 case ARM::fixup_t2_ldst_pcrel_12:
759 case ARM::fixup_t2_condbranch:
760 case ARM::fixup_t2_uncondbranch:
761 case ARM::fixup_t2_pcrel_10:
762 case ARM::fixup_t2_adr_pcrel_12:
763 case ARM::fixup_arm_thumb_bl:
764 case ARM::fixup_arm_thumb_blx:
765 case ARM::fixup_arm_movt_hi16:
766 case ARM::fixup_arm_movw_lo16:
767 case ARM::fixup_t2_movt_hi16:
768 case ARM::fixup_t2_movw_lo16:
769 // Instruction size is 4 bytes.
774 void ARMAsmBackend::applyFixup(const MCFixup &Fixup, char *Data,
775 unsigned DataSize, uint64_t Value,
776 bool IsPCRel) const {
777 unsigned NumBytes = getFixupKindNumBytes(Fixup.getKind());
779 adjustFixupValue(Fixup, Value, IsPCRel, nullptr, IsLittleEndian, true);
781 return; // Doesn't change encoding.
783 unsigned Offset = Fixup.getOffset();
784 assert(Offset + NumBytes <= DataSize && "Invalid fixup offset!");
786 // Used to point to big endian bytes.
787 unsigned FullSizeBytes;
788 if (!IsLittleEndian) {
789 FullSizeBytes = getFixupKindContainerSizeBytes(Fixup.getKind());
790 assert((Offset + FullSizeBytes) <= DataSize && "Invalid fixup size!");
791 assert(NumBytes <= FullSizeBytes && "Invalid fixup size!");
794 // For each byte of the fragment that the fixup touches, mask in the bits from
795 // the fixup value. The Value has been "split up" into the appropriate
797 for (unsigned i = 0; i != NumBytes; ++i) {
798 unsigned Idx = IsLittleEndian ? i : (FullSizeBytes - 1 - i);
799 Data[Offset + Idx] |= uint8_t((Value >> (i * 8)) & 0xff);
805 /// \brief Compact unwind encoding values.
806 enum CompactUnwindEncodings {
807 UNWIND_ARM_MODE_MASK = 0x0F000000,
808 UNWIND_ARM_MODE_FRAME = 0x01000000,
809 UNWIND_ARM_MODE_FRAME_D = 0x02000000,
810 UNWIND_ARM_MODE_DWARF = 0x04000000,
812 UNWIND_ARM_FRAME_STACK_ADJUST_MASK = 0x00C00000,
814 UNWIND_ARM_FRAME_FIRST_PUSH_R4 = 0x00000001,
815 UNWIND_ARM_FRAME_FIRST_PUSH_R5 = 0x00000002,
816 UNWIND_ARM_FRAME_FIRST_PUSH_R6 = 0x00000004,
818 UNWIND_ARM_FRAME_SECOND_PUSH_R8 = 0x00000008,
819 UNWIND_ARM_FRAME_SECOND_PUSH_R9 = 0x00000010,
820 UNWIND_ARM_FRAME_SECOND_PUSH_R10 = 0x00000020,
821 UNWIND_ARM_FRAME_SECOND_PUSH_R11 = 0x00000040,
822 UNWIND_ARM_FRAME_SECOND_PUSH_R12 = 0x00000080,
824 UNWIND_ARM_FRAME_D_REG_COUNT_MASK = 0x00000F00,
826 UNWIND_ARM_DWARF_SECTION_OFFSET = 0x00FFFFFF
829 } // end CU namespace
831 /// Generate compact unwind encoding for the function based on the CFI
832 /// instructions. If the CFI instructions describe a frame that cannot be
833 /// encoded in compact unwind, the method returns UNWIND_ARM_MODE_DWARF which
834 /// tells the runtime to fallback and unwind using dwarf.
835 uint32_t ARMAsmBackendDarwin::generateCompactUnwindEncoding(
836 ArrayRef<MCCFIInstruction> Instrs) const {
837 DEBUG_WITH_TYPE("compact-unwind", llvm::dbgs() << "generateCU()\n");
838 // Only armv7k uses CFI based unwinding.
839 if (Subtype != MachO::CPU_SUBTYPE_ARM_V7K)
841 // No .cfi directives means no frame.
844 // Start off assuming CFA is at SP+0.
845 int CFARegister = ARM::SP;
846 int CFARegisterOffset = 0;
847 // Mark savable registers as initially unsaved
848 DenseMap<unsigned, int> RegOffsets;
849 int FloatRegCount = 0;
850 // Process each .cfi directive and build up compact unwind info.
851 for (size_t i = 0, e = Instrs.size(); i != e; ++i) {
853 const MCCFIInstruction &Inst = Instrs[i];
854 switch (Inst.getOperation()) {
855 case MCCFIInstruction::OpDefCfa: // DW_CFA_def_cfa
856 CFARegisterOffset = -Inst.getOffset();
857 CFARegister = MRI.getLLVMRegNum(Inst.getRegister(), true);
859 case MCCFIInstruction::OpDefCfaOffset: // DW_CFA_def_cfa_offset
860 CFARegisterOffset = -Inst.getOffset();
862 case MCCFIInstruction::OpDefCfaRegister: // DW_CFA_def_cfa_register
863 CFARegister = MRI.getLLVMRegNum(Inst.getRegister(), true);
865 case MCCFIInstruction::OpOffset: // DW_CFA_offset
866 Reg = MRI.getLLVMRegNum(Inst.getRegister(), true);
867 if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
868 RegOffsets[Reg] = Inst.getOffset();
869 else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
870 RegOffsets[Reg] = Inst.getOffset();
873 DEBUG_WITH_TYPE("compact-unwind",
874 llvm::dbgs() << ".cfi_offset on unknown register="
875 << Inst.getRegister() << "\n");
876 return CU::UNWIND_ARM_MODE_DWARF;
879 case MCCFIInstruction::OpRelOffset: // DW_CFA_advance_loc
883 // Directive not convertable to compact unwind, bail out.
884 DEBUG_WITH_TYPE("compact-unwind",
886 << "CFI directive not compatiable with comact "
887 "unwind encoding, opcode=" << Inst.getOperation()
889 return CU::UNWIND_ARM_MODE_DWARF;
894 // If no frame set up, return no unwind info.
895 if ((CFARegister == ARM::SP) && (CFARegisterOffset == 0))
898 // Verify standard frame (lr/r7) was used.
899 if (CFARegister != ARM::R7) {
900 DEBUG_WITH_TYPE("compact-unwind", llvm::dbgs() << "frame register is "
902 << " instead of r7\n");
903 return CU::UNWIND_ARM_MODE_DWARF;
905 int StackAdjust = CFARegisterOffset - 8;
906 if (RegOffsets.lookup(ARM::LR) != (-4 - StackAdjust)) {
907 DEBUG_WITH_TYPE("compact-unwind",
909 << "LR not saved as standard frame, StackAdjust="
911 << ", CFARegisterOffset=" << CFARegisterOffset
912 << ", lr save at offset=" << RegOffsets[14] << "\n");
913 return CU::UNWIND_ARM_MODE_DWARF;
915 if (RegOffsets.lookup(ARM::R7) != (-8 - StackAdjust)) {
916 DEBUG_WITH_TYPE("compact-unwind",
917 llvm::dbgs() << "r7 not saved as standard frame\n");
918 return CU::UNWIND_ARM_MODE_DWARF;
920 uint32_t CompactUnwindEncoding = CU::UNWIND_ARM_MODE_FRAME;
922 // If var-args are used, there may be a stack adjust required.
923 switch (StackAdjust) {
927 CompactUnwindEncoding |= 0x00400000;
930 CompactUnwindEncoding |= 0x00800000;
933 CompactUnwindEncoding |= 0x00C00000;
936 DEBUG_WITH_TYPE("compact-unwind", llvm::dbgs()
937 << ".cfi_def_cfa stack adjust ("
938 << StackAdjust << ") out of range\n");
939 return CU::UNWIND_ARM_MODE_DWARF;
942 // If r6 is saved, it must be right below r7.
946 } GPRCSRegs[] = {{ARM::R6, CU::UNWIND_ARM_FRAME_FIRST_PUSH_R6},
947 {ARM::R5, CU::UNWIND_ARM_FRAME_FIRST_PUSH_R5},
948 {ARM::R4, CU::UNWIND_ARM_FRAME_FIRST_PUSH_R4},
949 {ARM::R12, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R12},
950 {ARM::R11, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R11},
951 {ARM::R10, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R10},
952 {ARM::R9, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R9},
953 {ARM::R8, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R8}};
955 int CurOffset = -8 - StackAdjust;
956 for (auto CSReg : GPRCSRegs) {
957 auto Offset = RegOffsets.find(CSReg.Reg);
958 if (Offset == RegOffsets.end())
961 int RegOffset = Offset->second;
962 if (RegOffset != CurOffset - 4) {
963 DEBUG_WITH_TYPE("compact-unwind",
964 llvm::dbgs() << MRI.getName(CSReg.Reg) << " saved at "
965 << RegOffset << " but only supported at "
966 << CurOffset << "\n");
967 return CU::UNWIND_ARM_MODE_DWARF;
969 CompactUnwindEncoding |= CSReg.Encoding;
973 // If no floats saved, we are done.
974 if (FloatRegCount == 0)
975 return CompactUnwindEncoding;
977 // Switch mode to include D register saving.
978 CompactUnwindEncoding &= ~CU::UNWIND_ARM_MODE_MASK;
979 CompactUnwindEncoding |= CU::UNWIND_ARM_MODE_FRAME_D;
981 // FIXME: supporting more than 4 saved D-registers compactly would be trivial,
982 // but needs coordination with the linker and libunwind.
983 if (FloatRegCount > 4) {
984 DEBUG_WITH_TYPE("compact-unwind",
985 llvm::dbgs() << "unsupported number of D registers saved ("
986 << FloatRegCount << ")\n");
987 return CU::UNWIND_ARM_MODE_DWARF;
990 // Floating point registers must either be saved sequentially, or we defer to
991 // DWARF. No gaps allowed here so check that each saved d-register is
992 // precisely where it should be.
993 static unsigned FPRCSRegs[] = { ARM::D8, ARM::D10, ARM::D12, ARM::D14 };
994 for (int Idx = FloatRegCount - 1; Idx >= 0; --Idx) {
995 auto Offset = RegOffsets.find(FPRCSRegs[Idx]);
996 if (Offset == RegOffsets.end()) {
997 DEBUG_WITH_TYPE("compact-unwind",
998 llvm::dbgs() << FloatRegCount << " D-regs saved, but "
999 << MRI.getName(FPRCSRegs[Idx])
1001 return CU::UNWIND_ARM_MODE_DWARF;
1002 } else if (Offset->second != CurOffset - 8) {
1003 DEBUG_WITH_TYPE("compact-unwind",
1004 llvm::dbgs() << FloatRegCount << " D-regs saved, but "
1005 << MRI.getName(FPRCSRegs[Idx])
1006 << " saved at " << Offset->second
1007 << ", expected at " << CurOffset - 8
1009 return CU::UNWIND_ARM_MODE_DWARF;
1014 return CompactUnwindEncoding | ((FloatRegCount - 1) << 8);
1017 static MachO::CPUSubTypeARM getMachOSubTypeFromArch(StringRef Arch) {
1018 unsigned AK = ARM::parseArch(Arch);
1021 return MachO::CPU_SUBTYPE_ARM_V7;
1022 case ARM::AK_ARMV4T:
1023 return MachO::CPU_SUBTYPE_ARM_V4T;
1024 case ARM::AK_ARMV5T:
1025 case ARM::AK_ARMV5TE:
1026 case ARM::AK_ARMV5TEJ:
1027 return MachO::CPU_SUBTYPE_ARM_V5;
1029 case ARM::AK_ARMV6K:
1030 return MachO::CPU_SUBTYPE_ARM_V6;
1031 case ARM::AK_ARMV7A:
1032 return MachO::CPU_SUBTYPE_ARM_V7;
1033 case ARM::AK_ARMV7S:
1034 return MachO::CPU_SUBTYPE_ARM_V7S;
1035 case ARM::AK_ARMV7K:
1036 return MachO::CPU_SUBTYPE_ARM_V7K;
1037 case ARM::AK_ARMV6M:
1038 return MachO::CPU_SUBTYPE_ARM_V6M;
1039 case ARM::AK_ARMV7M:
1040 return MachO::CPU_SUBTYPE_ARM_V7M;
1041 case ARM::AK_ARMV7EM:
1042 return MachO::CPU_SUBTYPE_ARM_V7EM;
1046 MCAsmBackend *llvm::createARMAsmBackend(const Target &T,
1047 const MCRegisterInfo &MRI,
1048 const Triple &TheTriple, StringRef CPU,
1050 switch (TheTriple.getObjectFormat()) {
1052 llvm_unreachable("unsupported object format");
1053 case Triple::MachO: {
1054 MachO::CPUSubTypeARM CS = getMachOSubTypeFromArch(TheTriple.getArchName());
1055 return new ARMAsmBackendDarwin(T, TheTriple, MRI, CS);
1058 assert(TheTriple.isOSWindows() && "non-Windows ARM COFF is not supported");
1059 return new ARMAsmBackendWinCOFF(T, TheTriple);
1061 assert(TheTriple.isOSBinFormatELF() && "using ELF for non-ELF target");
1062 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
1063 return new ARMAsmBackendELF(T, TheTriple, OSABI, isLittle);
1067 MCAsmBackend *llvm::createARMLEAsmBackend(const Target &T,
1068 const MCRegisterInfo &MRI,
1069 const Triple &TT, StringRef CPU) {
1070 return createARMAsmBackend(T, MRI, TT, CPU, true);
1073 MCAsmBackend *llvm::createARMBEAsmBackend(const Target &T,
1074 const MCRegisterInfo &MRI,
1075 const Triple &TT, StringRef CPU) {
1076 return createARMAsmBackend(T, MRI, TT, CPU, false);
1079 MCAsmBackend *llvm::createThumbLEAsmBackend(const Target &T,
1080 const MCRegisterInfo &MRI,
1081 const Triple &TT, StringRef CPU) {
1082 return createARMAsmBackend(T, MRI, TT, CPU, true);
1085 MCAsmBackend *llvm::createThumbBEAsmBackend(const Target &T,
1086 const MCRegisterInfo &MRI,
1087 const Triple &TT, StringRef CPU) {
1088 return createARMAsmBackend(T, MRI, TT, CPU, false);