1 //===-- AArch64AsmBackend.cpp - AArch64 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 //===----------------------------------------------------------------------===//
11 #include "AArch64RegisterInfo.h"
12 #include "MCTargetDesc/AArch64FixupKinds.h"
13 #include "llvm/ADT/Triple.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCDirectives.h"
16 #include "llvm/MC/MCELFObjectWriter.h"
17 #include "llvm/MC/MCFixupKindInfo.h"
18 #include "llvm/MC/MCObjectWriter.h"
19 #include "llvm/MC/MCSectionELF.h"
20 #include "llvm/MC/MCSectionMachO.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MachO.h"
27 class AArch64AsmBackend : public MCAsmBackend {
28 static const unsigned PCRelFlagVal =
29 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits | MCFixupKindInfo::FKF_IsPCRel;
32 AArch64AsmBackend(const Target &T) : MCAsmBackend() {}
34 unsigned getNumFixupKinds() const override {
35 return AArch64::NumTargetFixupKinds;
38 const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override {
39 const static MCFixupKindInfo Infos[AArch64::NumTargetFixupKinds] = {
40 // This table *must* be in the order that the fixup_* kinds are defined in
41 // AArch64FixupKinds.h.
43 // Name Offset (bits) Size (bits) Flags
44 { "fixup_aarch64_pcrel_adr_imm21", 0, 32, PCRelFlagVal },
45 { "fixup_aarch64_pcrel_adrp_imm21", 0, 32, PCRelFlagVal },
46 { "fixup_aarch64_add_imm12", 10, 12, 0 },
47 { "fixup_aarch64_ldst_imm12_scale1", 10, 12, 0 },
48 { "fixup_aarch64_ldst_imm12_scale2", 10, 12, 0 },
49 { "fixup_aarch64_ldst_imm12_scale4", 10, 12, 0 },
50 { "fixup_aarch64_ldst_imm12_scale8", 10, 12, 0 },
51 { "fixup_aarch64_ldst_imm12_scale16", 10, 12, 0 },
52 { "fixup_aarch64_ldr_pcrel_imm19", 5, 19, PCRelFlagVal },
53 { "fixup_aarch64_movw", 5, 16, 0 },
54 { "fixup_aarch64_pcrel_branch14", 5, 14, PCRelFlagVal },
55 { "fixup_aarch64_pcrel_branch19", 5, 19, PCRelFlagVal },
56 { "fixup_aarch64_pcrel_branch26", 0, 26, PCRelFlagVal },
57 { "fixup_aarch64_pcrel_call26", 0, 26, PCRelFlagVal },
58 { "fixup_aarch64_tlsdesc_call", 0, 0, 0 }
61 if (Kind < FirstTargetFixupKind)
62 return MCAsmBackend::getFixupKindInfo(Kind);
64 assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
66 return Infos[Kind - FirstTargetFixupKind];
69 void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
70 uint64_t Value, bool IsPCRel) const override;
72 bool mayNeedRelaxation(const MCInst &Inst) const override;
73 bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
74 const MCRelaxableFragment *DF,
75 const MCAsmLayout &Layout) const override;
76 void relaxInstruction(const MCInst &Inst, MCInst &Res) const override;
77 bool writeNopData(uint64_t Count, MCObjectWriter *OW) const override;
79 void HandleAssemblerFlag(MCAssemblerFlag Flag) {}
81 unsigned getPointerSize() const { return 8; }
84 } // end anonymous namespace
86 /// \brief The number of bytes the fixup may change.
87 static unsigned getFixupKindNumBytes(unsigned Kind) {
90 llvm_unreachable("Unknown fixup kind!");
92 case AArch64::fixup_aarch64_tlsdesc_call:
99 case AArch64::fixup_aarch64_movw:
102 case AArch64::fixup_aarch64_pcrel_branch14:
103 case AArch64::fixup_aarch64_add_imm12:
104 case AArch64::fixup_aarch64_ldst_imm12_scale1:
105 case AArch64::fixup_aarch64_ldst_imm12_scale2:
106 case AArch64::fixup_aarch64_ldst_imm12_scale4:
107 case AArch64::fixup_aarch64_ldst_imm12_scale8:
108 case AArch64::fixup_aarch64_ldst_imm12_scale16:
109 case AArch64::fixup_aarch64_ldr_pcrel_imm19:
110 case AArch64::fixup_aarch64_pcrel_branch19:
113 case AArch64::fixup_aarch64_pcrel_adr_imm21:
114 case AArch64::fixup_aarch64_pcrel_adrp_imm21:
115 case AArch64::fixup_aarch64_pcrel_branch26:
116 case AArch64::fixup_aarch64_pcrel_call26:
125 static unsigned AdrImmBits(unsigned Value) {
126 unsigned lo2 = Value & 0x3;
127 unsigned hi19 = (Value & 0x1ffffc) >> 2;
128 return (hi19 << 5) | (lo2 << 29);
131 static uint64_t adjustFixupValue(unsigned Kind, uint64_t Value) {
132 int64_t SignedValue = static_cast<int64_t>(Value);
135 llvm_unreachable("Unknown fixup kind!");
136 case AArch64::fixup_aarch64_pcrel_adr_imm21:
137 if (SignedValue > 2097151 || SignedValue < -2097152)
138 report_fatal_error("fixup value out of range");
139 return AdrImmBits(Value & 0x1fffffULL);
140 case AArch64::fixup_aarch64_pcrel_adrp_imm21:
141 return AdrImmBits((Value & 0x1fffff000ULL) >> 12);
142 case AArch64::fixup_aarch64_ldr_pcrel_imm19:
143 case AArch64::fixup_aarch64_pcrel_branch19:
144 // Signed 21-bit immediate
145 if (SignedValue > 2097151 || SignedValue < -2097152)
146 report_fatal_error("fixup value out of range");
147 // Low two bits are not encoded.
148 return (Value >> 2) & 0x7ffff;
149 case AArch64::fixup_aarch64_add_imm12:
150 case AArch64::fixup_aarch64_ldst_imm12_scale1:
151 // Unsigned 12-bit immediate
153 report_fatal_error("invalid imm12 fixup value");
155 case AArch64::fixup_aarch64_ldst_imm12_scale2:
156 // Unsigned 12-bit immediate which gets multiplied by 2
157 if (Value & 1 || Value >= 0x2000)
158 report_fatal_error("invalid imm12 fixup value");
160 case AArch64::fixup_aarch64_ldst_imm12_scale4:
161 // Unsigned 12-bit immediate which gets multiplied by 4
162 if (Value & 3 || Value >= 0x4000)
163 report_fatal_error("invalid imm12 fixup value");
165 case AArch64::fixup_aarch64_ldst_imm12_scale8:
166 // Unsigned 12-bit immediate which gets multiplied by 8
167 if (Value & 7 || Value >= 0x8000)
168 report_fatal_error("invalid imm12 fixup value");
170 case AArch64::fixup_aarch64_ldst_imm12_scale16:
171 // Unsigned 12-bit immediate which gets multiplied by 16
172 if (Value & 15 || Value >= 0x10000)
173 report_fatal_error("invalid imm12 fixup value");
175 case AArch64::fixup_aarch64_movw:
176 report_fatal_error("no resolvable MOVZ/MOVK fixups supported yet");
178 case AArch64::fixup_aarch64_pcrel_branch14:
179 // Signed 16-bit immediate
180 if (SignedValue > 32767 || SignedValue < -32768)
181 report_fatal_error("fixup value out of range");
182 // Low two bits are not encoded (4-byte alignment assumed).
184 report_fatal_error("fixup not sufficiently aligned");
185 return (Value >> 2) & 0x3fff;
186 case AArch64::fixup_aarch64_pcrel_branch26:
187 case AArch64::fixup_aarch64_pcrel_call26:
188 // Signed 28-bit immediate
189 if (SignedValue > 134217727 || SignedValue < -134217728)
190 report_fatal_error("fixup value out of range");
191 // Low two bits are not encoded (4-byte alignment assumed).
193 report_fatal_error("fixup not sufficiently aligned");
194 return (Value >> 2) & 0x3ffffff;
203 void AArch64AsmBackend::applyFixup(const MCFixup &Fixup, char *Data,
204 unsigned DataSize, uint64_t Value,
205 bool IsPCRel) const {
206 unsigned NumBytes = getFixupKindNumBytes(Fixup.getKind());
208 return; // Doesn't change encoding.
209 MCFixupKindInfo Info = getFixupKindInfo(Fixup.getKind());
210 // Apply any target-specific value adjustments.
211 Value = adjustFixupValue(Fixup.getKind(), Value);
213 // Shift the value into position.
214 Value <<= Info.TargetOffset;
216 unsigned Offset = Fixup.getOffset();
217 assert(Offset + NumBytes <= DataSize && "Invalid fixup offset!");
219 // For each byte of the fragment that the fixup touches, mask in the
220 // bits from the fixup value.
221 for (unsigned i = 0; i != NumBytes; ++i)
222 Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
225 bool AArch64AsmBackend::mayNeedRelaxation(const MCInst &Inst) const {
229 bool AArch64AsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
231 const MCRelaxableFragment *DF,
232 const MCAsmLayout &Layout) const {
233 // FIXME: This isn't correct for AArch64. Just moving the "generic" logic
234 // into the targets for now.
236 // Relax if the value is too big for a (signed) i8.
237 return int64_t(Value) != int64_t(int8_t(Value));
240 void AArch64AsmBackend::relaxInstruction(const MCInst &Inst,
242 llvm_unreachable("AArch64AsmBackend::relaxInstruction() unimplemented");
245 bool AArch64AsmBackend::writeNopData(uint64_t Count, MCObjectWriter *OW) const {
246 // If the count is not 4-byte aligned, we must be writing data into the text
247 // section (otherwise we have unaligned instructions, and thus have far
248 // bigger problems), so just write zeros instead.
249 if ((Count & 3) != 0) {
250 for (uint64_t i = 0, e = (Count & 3); i != e; ++i)
254 // We are properly aligned, so write NOPs as requested.
256 for (uint64_t i = 0; i != Count; ++i)
257 OW->Write32(0xd503201f);
265 /// \brief Compact unwind encoding values.
266 enum CompactUnwindEncodings {
267 /// \brief A "frameless" leaf function, where no non-volatile registers are
268 /// saved. The return remains in LR throughout the function.
269 UNWIND_AArch64_MODE_FRAMELESS = 0x02000000,
271 /// \brief No compact unwind encoding available. Instead the low 23-bits of
272 /// the compact unwind encoding is the offset of the DWARF FDE in the
273 /// __eh_frame section. This mode is never used in object files. It is only
274 /// generated by the linker in final linked images, which have only DWARF info
276 UNWIND_AArch64_MODE_DWARF = 0x03000000,
278 /// \brief This is a standard arm64 prologue where FP/LR are immediately
279 /// pushed on the stack, then SP is copied to FP. If there are any
280 /// non-volatile register saved, they are copied into the stack fame in pairs
281 /// in a contiguous ranger right below the saved FP/LR pair. Any subset of the
282 /// five X pairs and four D pairs can be saved, but the memory layout must be
283 /// in register number order.
284 UNWIND_AArch64_MODE_FRAME = 0x04000000,
286 /// \brief Frame register pair encodings.
287 UNWIND_AArch64_FRAME_X19_X20_PAIR = 0x00000001,
288 UNWIND_AArch64_FRAME_X21_X22_PAIR = 0x00000002,
289 UNWIND_AArch64_FRAME_X23_X24_PAIR = 0x00000004,
290 UNWIND_AArch64_FRAME_X25_X26_PAIR = 0x00000008,
291 UNWIND_AArch64_FRAME_X27_X28_PAIR = 0x00000010,
292 UNWIND_AArch64_FRAME_D8_D9_PAIR = 0x00000100,
293 UNWIND_AArch64_FRAME_D10_D11_PAIR = 0x00000200,
294 UNWIND_AArch64_FRAME_D12_D13_PAIR = 0x00000400,
295 UNWIND_AArch64_FRAME_D14_D15_PAIR = 0x00000800
298 } // end CU namespace
300 // FIXME: This should be in a separate file.
301 class DarwinAArch64AsmBackend : public AArch64AsmBackend {
302 const MCRegisterInfo &MRI;
304 /// \brief Encode compact unwind stack adjustment for frameless functions.
305 /// See UNWIND_AArch64_FRAMELESS_STACK_SIZE_MASK in compact_unwind_encoding.h.
306 /// The stack size always needs to be 16 byte aligned.
307 uint32_t encodeStackAdjustment(uint32_t StackSize) const {
308 return (StackSize / 16) << 12;
312 DarwinAArch64AsmBackend(const Target &T, const MCRegisterInfo &MRI)
313 : AArch64AsmBackend(T), MRI(MRI) {}
315 MCObjectWriter *createObjectWriter(raw_ostream &OS) const override {
316 return createAArch64MachObjectWriter(OS, MachO::CPU_TYPE_ARM64,
317 MachO::CPU_SUBTYPE_ARM64_ALL);
320 /// \brief Generate the compact unwind encoding from the CFI directives.
321 uint32_t generateCompactUnwindEncoding(
322 ArrayRef<MCCFIInstruction> Instrs) const override {
324 return CU::UNWIND_AArch64_MODE_FRAMELESS;
327 unsigned StackSize = 0;
329 uint32_t CompactUnwindEncoding = 0;
330 for (size_t i = 0, e = Instrs.size(); i != e; ++i) {
331 const MCCFIInstruction &Inst = Instrs[i];
333 switch (Inst.getOperation()) {
335 // Cannot handle this directive: bail out.
336 return CU::UNWIND_AArch64_MODE_DWARF;
337 case MCCFIInstruction::OpDefCfa: {
338 // Defines a frame pointer.
339 assert(getXRegFromWReg(MRI.getLLVMRegNum(Inst.getRegister(), true)) ==
341 "Invalid frame pointer!");
342 assert(i + 2 < e && "Insufficient CFI instructions to define a frame!");
344 const MCCFIInstruction &LRPush = Instrs[++i];
345 assert(LRPush.getOperation() == MCCFIInstruction::OpOffset &&
346 "Link register not pushed!");
347 const MCCFIInstruction &FPPush = Instrs[++i];
348 assert(FPPush.getOperation() == MCCFIInstruction::OpOffset &&
349 "Frame pointer not pushed!");
351 unsigned LRReg = MRI.getLLVMRegNum(LRPush.getRegister(), true);
352 unsigned FPReg = MRI.getLLVMRegNum(FPPush.getRegister(), true);
354 LRReg = getXRegFromWReg(LRReg);
355 FPReg = getXRegFromWReg(FPReg);
357 assert(LRReg == AArch64::LR && FPReg == AArch64::FP &&
358 "Pushing invalid registers for frame!");
360 // Indicate that the function has a frame.
361 CompactUnwindEncoding |= CU::UNWIND_AArch64_MODE_FRAME;
365 case MCCFIInstruction::OpDefCfaOffset: {
366 assert(StackSize == 0 && "We already have the CFA offset!");
367 StackSize = std::abs(Inst.getOffset());
370 case MCCFIInstruction::OpOffset: {
371 // Registers are saved in pairs. We expect there to be two consecutive
372 // `.cfi_offset' instructions with the appropriate registers specified.
373 unsigned Reg1 = MRI.getLLVMRegNum(Inst.getRegister(), true);
375 return CU::UNWIND_AArch64_MODE_DWARF;
377 const MCCFIInstruction &Inst2 = Instrs[++i];
378 if (Inst2.getOperation() != MCCFIInstruction::OpOffset)
379 return CU::UNWIND_AArch64_MODE_DWARF;
380 unsigned Reg2 = MRI.getLLVMRegNum(Inst2.getRegister(), true);
382 // N.B. The encodings must be in register number order, and the X
383 // registers before the D registers.
385 // X19/X20 pair = 0x00000001,
386 // X21/X22 pair = 0x00000002,
387 // X23/X24 pair = 0x00000004,
388 // X25/X26 pair = 0x00000008,
389 // X27/X28 pair = 0x00000010
390 Reg1 = getXRegFromWReg(Reg1);
391 Reg2 = getXRegFromWReg(Reg2);
393 if (Reg1 == AArch64::X19 && Reg2 == AArch64::X20 &&
394 (CompactUnwindEncoding & 0xF1E) == 0)
395 CompactUnwindEncoding |= CU::UNWIND_AArch64_FRAME_X19_X20_PAIR;
396 else if (Reg1 == AArch64::X21 && Reg2 == AArch64::X22 &&
397 (CompactUnwindEncoding & 0xF1C) == 0)
398 CompactUnwindEncoding |= CU::UNWIND_AArch64_FRAME_X21_X22_PAIR;
399 else if (Reg1 == AArch64::X23 && Reg2 == AArch64::X24 &&
400 (CompactUnwindEncoding & 0xF18) == 0)
401 CompactUnwindEncoding |= CU::UNWIND_AArch64_FRAME_X23_X24_PAIR;
402 else if (Reg1 == AArch64::X25 && Reg2 == AArch64::X26 &&
403 (CompactUnwindEncoding & 0xF10) == 0)
404 CompactUnwindEncoding |= CU::UNWIND_AArch64_FRAME_X25_X26_PAIR;
405 else if (Reg1 == AArch64::X27 && Reg2 == AArch64::X28 &&
406 (CompactUnwindEncoding & 0xF00) == 0)
407 CompactUnwindEncoding |= CU::UNWIND_AArch64_FRAME_X27_X28_PAIR;
409 Reg1 = getDRegFromBReg(Reg1);
410 Reg2 = getDRegFromBReg(Reg2);
412 // D8/D9 pair = 0x00000100,
413 // D10/D11 pair = 0x00000200,
414 // D12/D13 pair = 0x00000400,
415 // D14/D15 pair = 0x00000800
416 if (Reg1 == AArch64::D8 && Reg2 == AArch64::D9 &&
417 (CompactUnwindEncoding & 0xE00) == 0)
418 CompactUnwindEncoding |= CU::UNWIND_AArch64_FRAME_D8_D9_PAIR;
419 else if (Reg1 == AArch64::D10 && Reg2 == AArch64::D11 &&
420 (CompactUnwindEncoding & 0xC00) == 0)
421 CompactUnwindEncoding |= CU::UNWIND_AArch64_FRAME_D10_D11_PAIR;
422 else if (Reg1 == AArch64::D12 && Reg2 == AArch64::D13 &&
423 (CompactUnwindEncoding & 0x800) == 0)
424 CompactUnwindEncoding |= CU::UNWIND_AArch64_FRAME_D12_D13_PAIR;
425 else if (Reg1 == AArch64::D14 && Reg2 == AArch64::D15)
426 CompactUnwindEncoding |= CU::UNWIND_AArch64_FRAME_D14_D15_PAIR;
428 // A pair was pushed which we cannot handle.
429 return CU::UNWIND_AArch64_MODE_DWARF;
438 // With compact unwind info we can only represent stack adjustments of up
440 if (StackSize > 65520)
441 return CU::UNWIND_AArch64_MODE_DWARF;
443 CompactUnwindEncoding |= CU::UNWIND_AArch64_MODE_FRAMELESS;
444 CompactUnwindEncoding |= encodeStackAdjustment(StackSize);
447 return CompactUnwindEncoding;
451 } // end anonymous namespace
455 class ELFAArch64AsmBackend : public AArch64AsmBackend {
460 ELFAArch64AsmBackend(const Target &T, uint8_t OSABI, bool IsLittleEndian)
461 : AArch64AsmBackend(T), OSABI(OSABI), IsLittleEndian(IsLittleEndian) {}
463 MCObjectWriter *createObjectWriter(raw_ostream &OS) const override {
464 return createAArch64ELFObjectWriter(OS, OSABI, IsLittleEndian);
467 void processFixupValue(const MCAssembler &Asm, const MCAsmLayout &Layout,
468 const MCFixup &Fixup, const MCFragment *DF,
469 const MCValue &Target, uint64_t &Value,
470 bool &IsResolved) override;
472 void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
473 uint64_t Value, bool IsPCRel) const override;
476 void ELFAArch64AsmBackend::processFixupValue(
477 const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFixup &Fixup,
478 const MCFragment *DF, const MCValue &Target, uint64_t &Value,
480 // The ADRP instruction adds some multiple of 0x1000 to the current PC &
481 // ~0xfff. This means that the required offset to reach a symbol can vary by
482 // up to one step depending on where the ADRP is in memory. For example:
487 // If the ADRP occurs at address 0xffc then "there" will be at 0x1000 and
488 // we'll need that as an offset. At any other address "there" will be in the
489 // same page as the ADRP and the instruction should encode 0x0. Assuming the
490 // section isn't 0x1000-aligned, we therefore need to delegate this decision
491 // to the linker -- a relocation!
492 if ((uint32_t)Fixup.getKind() == AArch64::fixup_aarch64_pcrel_adrp_imm21)
496 void ELFAArch64AsmBackend::applyFixup(const MCFixup &Fixup, char *Data,
497 unsigned DataSize, uint64_t Value,
498 bool IsPCRel) const {
499 // store fixups in .eh_frame section in big endian order
500 if (!IsLittleEndian && Fixup.getKind() == FK_Data_4) {
501 const MCSection *Sec = Fixup.getValue()->FindAssociatedSection();
502 const MCSectionELF *SecELF = dyn_cast_or_null<const MCSectionELF>(Sec);
503 if (SecELF && SecELF->getSectionName() == ".eh_frame")
504 Value = ByteSwap_32(unsigned(Value));
506 AArch64AsmBackend::applyFixup (Fixup, Data, DataSize, Value, IsPCRel);
510 MCAsmBackend *llvm::createAArch64leAsmBackend(const Target &T,
511 const MCRegisterInfo &MRI,
512 StringRef TT, StringRef CPU) {
513 Triple TheTriple(TT);
515 if (TheTriple.isOSDarwin())
516 return new DarwinAArch64AsmBackend(T, MRI);
518 assert(TheTriple.isOSBinFormatELF() && "Expect either MachO or ELF target");
519 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
520 return new ELFAArch64AsmBackend(T, OSABI, /*IsLittleEndian=*/true);
523 MCAsmBackend *llvm::createAArch64beAsmBackend(const Target &T,
524 const MCRegisterInfo &MRI,
525 StringRef TT, StringRef CPU) {
526 Triple TheTriple(TT);
528 assert(TheTriple.isOSBinFormatELF() &&
529 "Big endian is only supported for ELF targets!");
530 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
531 return new ELFAArch64AsmBackend(T, OSABI,
532 /*IsLittleEndian=*/false);