1 //===- lib/MC/ARMELFStreamer.cpp - ELF Object Output for ARM --------------===//
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 // This file assembles .s files and emits ARM ELF .o object files. Different
11 // from generic ELF streamer in emitting mapping symbols ($a, $t and $d) to
12 // delimit regions of data and code.
14 //===----------------------------------------------------------------------===//
16 #include "ARMRegisterInfo.h"
17 #include "ARMUnwindOpAsm.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/MC/MCAsmBackend.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCCodeEmitter.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCELFStreamer.h"
26 #include "llvm/MC/MCELFSymbolFlags.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCInstPrinter.h"
30 #include "llvm/MC/MCObjectFileInfo.h"
31 #include "llvm/MC/MCObjectStreamer.h"
32 #include "llvm/MC/MCRegisterInfo.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCSectionELF.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbolELF.h"
37 #include "llvm/MC/MCValue.h"
38 #include "llvm/Support/ARMBuildAttributes.h"
39 #include "llvm/Support/ARMEHABI.h"
40 #include "llvm/Support/TargetParser.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ELF.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/LEB128.h"
45 #include "llvm/Support/raw_ostream.h"
50 static std::string GetAEABIUnwindPersonalityName(unsigned Index) {
51 assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX &&
52 "Invalid personality index");
53 return (Twine("__aeabi_unwind_cpp_pr") + Twine(Index)).str();
60 class ARMTargetAsmStreamer : public ARMTargetStreamer {
61 formatted_raw_ostream &OS;
62 MCInstPrinter &InstPrinter;
65 void emitFnStart() override;
66 void emitFnEnd() override;
67 void emitCantUnwind() override;
68 void emitPersonality(const MCSymbol *Personality) override;
69 void emitPersonalityIndex(unsigned Index) override;
70 void emitHandlerData() override;
71 void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
72 void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
73 void emitPad(int64_t Offset) override;
74 void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
75 bool isVector) override;
76 void emitUnwindRaw(int64_t Offset,
77 const SmallVectorImpl<uint8_t> &Opcodes) override;
79 void switchVendor(StringRef Vendor) override;
80 void emitAttribute(unsigned Attribute, unsigned Value) override;
81 void emitTextAttribute(unsigned Attribute, StringRef String) override;
82 void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
83 StringRef StrinValue) override;
84 void emitArch(unsigned Arch) override;
85 void emitArchExtension(unsigned ArchExt) override;
86 void emitObjectArch(unsigned Arch) override;
87 void emitFPU(unsigned FPU) override;
88 void emitInst(uint32_t Inst, char Suffix = '\0') override;
89 void finishAttributeSection() override;
91 void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
92 void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
95 ARMTargetAsmStreamer(MCStreamer &S, formatted_raw_ostream &OS,
96 MCInstPrinter &InstPrinter, bool VerboseAsm);
99 ARMTargetAsmStreamer::ARMTargetAsmStreamer(MCStreamer &S,
100 formatted_raw_ostream &OS,
101 MCInstPrinter &InstPrinter,
103 : ARMTargetStreamer(S), OS(OS), InstPrinter(InstPrinter),
104 IsVerboseAsm(VerboseAsm) {}
105 void ARMTargetAsmStreamer::emitFnStart() { OS << "\t.fnstart\n"; }
106 void ARMTargetAsmStreamer::emitFnEnd() { OS << "\t.fnend\n"; }
107 void ARMTargetAsmStreamer::emitCantUnwind() { OS << "\t.cantunwind\n"; }
108 void ARMTargetAsmStreamer::emitPersonality(const MCSymbol *Personality) {
109 OS << "\t.personality " << Personality->getName() << '\n';
111 void ARMTargetAsmStreamer::emitPersonalityIndex(unsigned Index) {
112 OS << "\t.personalityindex " << Index << '\n';
114 void ARMTargetAsmStreamer::emitHandlerData() { OS << "\t.handlerdata\n"; }
115 void ARMTargetAsmStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
118 InstPrinter.printRegName(OS, FpReg);
120 InstPrinter.printRegName(OS, SpReg);
122 OS << ", #" << Offset;
125 void ARMTargetAsmStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
126 assert((Reg != ARM::SP && Reg != ARM::PC) &&
127 "the operand of .movsp cannot be either sp or pc");
130 InstPrinter.printRegName(OS, Reg);
132 OS << ", #" << Offset;
135 void ARMTargetAsmStreamer::emitPad(int64_t Offset) {
136 OS << "\t.pad\t#" << Offset << '\n';
138 void ARMTargetAsmStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
140 assert(RegList.size() && "RegList should not be empty");
146 InstPrinter.printRegName(OS, RegList[0]);
148 for (unsigned i = 1, e = RegList.size(); i != e; ++i) {
150 InstPrinter.printRegName(OS, RegList[i]);
155 void ARMTargetAsmStreamer::switchVendor(StringRef Vendor) {
157 void ARMTargetAsmStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
158 OS << "\t.eabi_attribute\t" << Attribute << ", " << Twine(Value);
160 StringRef Name = ARMBuildAttrs::AttrTypeAsString(Attribute);
162 OS << "\t@ " << Name;
166 void ARMTargetAsmStreamer::emitTextAttribute(unsigned Attribute,
169 case ARMBuildAttrs::CPU_name:
170 OS << "\t.cpu\t" << String.lower();
173 OS << "\t.eabi_attribute\t" << Attribute << ", \"" << String << "\"";
175 StringRef Name = ARMBuildAttrs::AttrTypeAsString(Attribute);
177 OS << "\t@ " << Name;
183 void ARMTargetAsmStreamer::emitIntTextAttribute(unsigned Attribute,
185 StringRef StringValue) {
187 default: llvm_unreachable("unsupported multi-value attribute in asm mode");
188 case ARMBuildAttrs::compatibility:
189 OS << "\t.eabi_attribute\t" << Attribute << ", " << IntValue;
190 if (!StringValue.empty())
191 OS << ", \"" << StringValue << "\"";
193 OS << "\t@ " << ARMBuildAttrs::AttrTypeAsString(Attribute);
198 void ARMTargetAsmStreamer::emitArch(unsigned Arch) {
199 OS << "\t.arch\t" << ARMTargetParser::getArchName(Arch) << "\n";
201 void ARMTargetAsmStreamer::emitArchExtension(unsigned ArchExt) {
202 OS << "\t.arch_extension\t" << ARMTargetParser::getArchExtName(ArchExt) << "\n";
204 void ARMTargetAsmStreamer::emitObjectArch(unsigned Arch) {
205 OS << "\t.object_arch\t" << ARMTargetParser::getArchName(Arch) << '\n';
207 void ARMTargetAsmStreamer::emitFPU(unsigned FPU) {
208 OS << "\t.fpu\t" << ARMTargetParser::getFPUName(FPU) << "\n";
210 void ARMTargetAsmStreamer::finishAttributeSection() {
213 ARMTargetAsmStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
214 OS << "\t.tlsdescseq\t" << S->getSymbol().getName();
217 void ARMTargetAsmStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
218 OS << "\t.thumb_set\t" << *Symbol << ", " << *Value << '\n';
221 void ARMTargetAsmStreamer::emitInst(uint32_t Inst, char Suffix) {
225 OS << "\t0x" << Twine::utohexstr(Inst) << "\n";
228 void ARMTargetAsmStreamer::emitUnwindRaw(int64_t Offset,
229 const SmallVectorImpl<uint8_t> &Opcodes) {
230 OS << "\t.unwind_raw " << Offset;
231 for (SmallVectorImpl<uint8_t>::const_iterator OCI = Opcodes.begin(),
234 OS << ", 0x" << Twine::utohexstr(*OCI);
238 class ARMTargetELFStreamer : public ARMTargetStreamer {
240 // This structure holds all attributes, accounting for
241 // their string/numeric value, so we can later emmit them
242 // in declaration order, keeping all in the same vector
243 struct AttributeItem {
248 NumericAndTextAttributes
252 StringRef StringValue;
254 static bool LessTag(const AttributeItem &LHS, const AttributeItem &RHS) {
255 // The conformance tag must be emitted first when serialised
256 // into an object file. Specifically, the addenda to the ARM ABI
257 // states that (2.3.7.4):
259 // "To simplify recognition by consumers in the common case of
260 // claiming conformity for the whole file, this tag should be
261 // emitted first in a file-scope sub-subsection of the first
262 // public subsection of the attributes section."
264 // So it is special-cased in this comparison predicate when the
265 // attributes are sorted in finishAttributeSection().
266 return (RHS.Tag != ARMBuildAttrs::conformance) &&
267 ((LHS.Tag == ARMBuildAttrs::conformance) || (LHS.Tag < RHS.Tag));
271 StringRef CurrentVendor;
274 unsigned EmittedArch;
275 SmallVector<AttributeItem, 64> Contents;
277 MCSection *AttributeSection;
279 AttributeItem *getAttributeItem(unsigned Attribute) {
280 for (size_t i = 0; i < Contents.size(); ++i)
281 if (Contents[i].Tag == Attribute)
286 void setAttributeItem(unsigned Attribute, unsigned Value,
287 bool OverwriteExisting) {
288 // Look for existing attribute item
289 if (AttributeItem *Item = getAttributeItem(Attribute)) {
290 if (!OverwriteExisting)
292 Item->Type = AttributeItem::NumericAttribute;
293 Item->IntValue = Value;
297 // Create new attribute item
298 AttributeItem Item = {
299 AttributeItem::NumericAttribute,
304 Contents.push_back(Item);
307 void setAttributeItem(unsigned Attribute, StringRef Value,
308 bool OverwriteExisting) {
309 // Look for existing attribute item
310 if (AttributeItem *Item = getAttributeItem(Attribute)) {
311 if (!OverwriteExisting)
313 Item->Type = AttributeItem::TextAttribute;
314 Item->StringValue = Value;
318 // Create new attribute item
319 AttributeItem Item = {
320 AttributeItem::TextAttribute,
325 Contents.push_back(Item);
328 void setAttributeItems(unsigned Attribute, unsigned IntValue,
329 StringRef StringValue, bool OverwriteExisting) {
330 // Look for existing attribute item
331 if (AttributeItem *Item = getAttributeItem(Attribute)) {
332 if (!OverwriteExisting)
334 Item->Type = AttributeItem::NumericAndTextAttributes;
335 Item->IntValue = IntValue;
336 Item->StringValue = StringValue;
340 // Create new attribute item
341 AttributeItem Item = {
342 AttributeItem::NumericAndTextAttributes,
347 Contents.push_back(Item);
350 void emitArchDefaultAttributes();
351 void emitFPUDefaultAttributes();
353 ARMELFStreamer &getStreamer();
355 void emitFnStart() override;
356 void emitFnEnd() override;
357 void emitCantUnwind() override;
358 void emitPersonality(const MCSymbol *Personality) override;
359 void emitPersonalityIndex(unsigned Index) override;
360 void emitHandlerData() override;
361 void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
362 void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
363 void emitPad(int64_t Offset) override;
364 void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
365 bool isVector) override;
366 void emitUnwindRaw(int64_t Offset,
367 const SmallVectorImpl<uint8_t> &Opcodes) override;
369 void switchVendor(StringRef Vendor) override;
370 void emitAttribute(unsigned Attribute, unsigned Value) override;
371 void emitTextAttribute(unsigned Attribute, StringRef String) override;
372 void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
373 StringRef StringValue) override;
374 void emitArch(unsigned Arch) override;
375 void emitObjectArch(unsigned Arch) override;
376 void emitFPU(unsigned FPU) override;
377 void emitInst(uint32_t Inst, char Suffix = '\0') override;
378 void finishAttributeSection() override;
379 void emitLabel(MCSymbol *Symbol) override;
381 void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
382 void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
384 size_t calculateContentSize() const;
387 ARMTargetELFStreamer(MCStreamer &S)
388 : ARMTargetStreamer(S), CurrentVendor("aeabi"), FPU(ARM::FK_INVALID),
389 Arch(ARM::AK_INVALID), EmittedArch(ARM::AK_INVALID),
390 AttributeSection(nullptr) {}
393 /// Extend the generic ELFStreamer class so that it can emit mapping symbols at
394 /// the appropriate points in the object files. These symbols are defined in the
395 /// ARM ELF ABI: infocenter.arm.com/help/topic/com.arm.../IHI0044D_aaelf.pdf.
397 /// In brief: $a, $t or $d should be emitted at the start of each contiguous
398 /// region of ARM code, Thumb code or data in a section. In practice, this
399 /// emission does not rely on explicit assembler directives but on inherent
400 /// properties of the directives doing the emission (e.g. ".byte" is data, "add
401 /// r0, r0, r0" an instruction).
403 /// As a result this system is orthogonal to the DataRegion infrastructure used
404 /// by MachO. Beware!
405 class ARMELFStreamer : public MCELFStreamer {
407 friend class ARMTargetELFStreamer;
409 ARMELFStreamer(MCContext &Context, MCAsmBackend &TAB, raw_pwrite_stream &OS,
410 MCCodeEmitter *Emitter, bool IsThumb)
411 : MCELFStreamer(Context, TAB, OS, Emitter), IsThumb(IsThumb),
412 MappingSymbolCounter(0), LastEMS(EMS_None) {
418 void FinishImpl() override;
420 // ARM exception handling directives
423 void emitCantUnwind();
424 void emitPersonality(const MCSymbol *Per);
425 void emitPersonalityIndex(unsigned index);
426 void emitHandlerData();
427 void emitSetFP(unsigned NewFpReg, unsigned NewSpReg, int64_t Offset = 0);
428 void emitMovSP(unsigned Reg, int64_t Offset = 0);
429 void emitPad(int64_t Offset);
430 void emitRegSave(const SmallVectorImpl<unsigned> &RegList, bool isVector);
431 void emitUnwindRaw(int64_t Offset, const SmallVectorImpl<uint8_t> &Opcodes);
433 void ChangeSection(MCSection *Section, const MCExpr *Subsection) override {
434 // We have to keep track of the mapping symbol state of any sections we
435 // use. Each one should start off as EMS_None, which is provided as the
436 // default constructor by DenseMap::lookup.
437 LastMappingSymbols[getPreviousSection().first] = LastEMS;
438 LastEMS = LastMappingSymbols.lookup(Section);
440 MCELFStreamer::ChangeSection(Section, Subsection);
443 /// This function is the one used to emit instruction data into the ELF
444 /// streamer. We override it to add the appropriate mapping symbol if
446 void EmitInstruction(const MCInst& Inst,
447 const MCSubtargetInfo &STI) override {
449 EmitThumbMappingSymbol();
451 EmitARMMappingSymbol();
453 MCELFStreamer::EmitInstruction(Inst, STI);
456 void emitInst(uint32_t Inst, char Suffix) {
459 const bool LittleEndian = getContext().getAsmInfo()->isLittleEndian();
466 EmitARMMappingSymbol();
467 for (unsigned II = 0, IE = Size; II != IE; II++) {
468 const unsigned I = LittleEndian ? (Size - II - 1) : II;
469 Buffer[Size - II - 1] = uint8_t(Inst >> I * CHAR_BIT);
475 Size = (Suffix == 'n' ? 2 : 4);
478 EmitThumbMappingSymbol();
479 for (unsigned II = 0, IE = Size; II != IE; II = II + 2) {
480 const unsigned I0 = LittleEndian ? II + 0 : (Size - II - 1);
481 const unsigned I1 = LittleEndian ? II + 1 : (Size - II - 2);
482 Buffer[Size - II - 2] = uint8_t(Inst >> I0 * CHAR_BIT);
483 Buffer[Size - II - 1] = uint8_t(Inst >> I1 * CHAR_BIT);
488 llvm_unreachable("Invalid Suffix");
491 MCELFStreamer::EmitBytes(StringRef(Buffer, Size));
494 /// This is one of the functions used to emit data into an ELF section, so the
495 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
497 void EmitBytes(StringRef Data) override {
498 EmitDataMappingSymbol();
499 MCELFStreamer::EmitBytes(Data);
502 /// This is one of the functions used to emit data into an ELF section, so the
503 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
505 void EmitValueImpl(const MCExpr *Value, unsigned Size,
506 const SMLoc &Loc) override {
507 if (const MCSymbolRefExpr *SRE = dyn_cast_or_null<MCSymbolRefExpr>(Value))
508 if (SRE->getKind() == MCSymbolRefExpr::VK_ARM_SBREL && !(Size == 4))
509 getContext().reportFatalError(Loc, "relocated expression must be 32-bit");
511 EmitDataMappingSymbol();
512 MCELFStreamer::EmitValueImpl(Value, Size);
515 void EmitAssemblerFlag(MCAssemblerFlag Flag) override {
516 MCELFStreamer::EmitAssemblerFlag(Flag);
519 case MCAF_SyntaxUnified:
520 return; // no-op here.
523 return; // Change to Thumb mode
526 return; // Change to ARM mode
529 case MCAF_SubsectionsViaSymbols:
535 enum ElfMappingSymbol {
542 void EmitDataMappingSymbol() {
543 if (LastEMS == EMS_Data) return;
544 EmitMappingSymbol("$d");
548 void EmitThumbMappingSymbol() {
549 if (LastEMS == EMS_Thumb) return;
550 EmitMappingSymbol("$t");
554 void EmitARMMappingSymbol() {
555 if (LastEMS == EMS_ARM) return;
556 EmitMappingSymbol("$a");
560 void EmitMappingSymbol(StringRef Name) {
561 MCSymbol *Start = getContext().createTempSymbol();
564 auto *Symbol = cast<MCSymbolELF>(getContext().getOrCreateSymbol(
565 Name + "." + Twine(MappingSymbolCounter++)));
567 getAssembler().registerSymbol(*Symbol);
568 Symbol->setType(ELF::STT_NOTYPE);
569 Symbol->setBinding(ELF::STB_LOCAL);
570 Symbol->setExternal(false);
571 AssignSection(Symbol, getCurrentSection().first);
573 const MCExpr *Value = MCSymbolRefExpr::create(Start, getContext());
574 Symbol->setVariableValue(Value);
577 void EmitThumbFunc(MCSymbol *Func) override {
578 getAssembler().setIsThumbFunc(Func);
579 EmitSymbolAttribute(Func, MCSA_ELF_TypeFunction);
582 // Helper functions for ARM exception handling directives
585 void EmitPersonalityFixup(StringRef Name);
586 void FlushPendingOffset();
587 void FlushUnwindOpcodes(bool NoHandlerData);
589 void SwitchToEHSection(const char *Prefix, unsigned Type, unsigned Flags,
590 SectionKind Kind, const MCSymbol &Fn);
591 void SwitchToExTabSection(const MCSymbol &FnStart);
592 void SwitchToExIdxSection(const MCSymbol &FnStart);
594 void EmitFixup(const MCExpr *Expr, MCFixupKind Kind);
597 int64_t MappingSymbolCounter;
599 DenseMap<const MCSection *, ElfMappingSymbol> LastMappingSymbols;
600 ElfMappingSymbol LastEMS;
602 // ARM Exception Handling Frame Information
605 const MCSymbol *Personality;
606 unsigned PersonalityIndex;
607 unsigned FPReg; // Frame pointer register
608 int64_t FPOffset; // Offset: (final frame pointer) - (initial $sp)
609 int64_t SPOffset; // Offset: (final $sp) - (initial $sp)
610 int64_t PendingOffset; // Offset: (final $sp) - (emitted $sp)
613 SmallVector<uint8_t, 64> Opcodes;
614 UnwindOpcodeAssembler UnwindOpAsm;
616 } // end anonymous namespace
618 ARMELFStreamer &ARMTargetELFStreamer::getStreamer() {
619 return static_cast<ARMELFStreamer &>(Streamer);
622 void ARMTargetELFStreamer::emitFnStart() { getStreamer().emitFnStart(); }
623 void ARMTargetELFStreamer::emitFnEnd() { getStreamer().emitFnEnd(); }
624 void ARMTargetELFStreamer::emitCantUnwind() { getStreamer().emitCantUnwind(); }
625 void ARMTargetELFStreamer::emitPersonality(const MCSymbol *Personality) {
626 getStreamer().emitPersonality(Personality);
628 void ARMTargetELFStreamer::emitPersonalityIndex(unsigned Index) {
629 getStreamer().emitPersonalityIndex(Index);
631 void ARMTargetELFStreamer::emitHandlerData() {
632 getStreamer().emitHandlerData();
634 void ARMTargetELFStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
636 getStreamer().emitSetFP(FpReg, SpReg, Offset);
638 void ARMTargetELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
639 getStreamer().emitMovSP(Reg, Offset);
641 void ARMTargetELFStreamer::emitPad(int64_t Offset) {
642 getStreamer().emitPad(Offset);
644 void ARMTargetELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
646 getStreamer().emitRegSave(RegList, isVector);
648 void ARMTargetELFStreamer::emitUnwindRaw(int64_t Offset,
649 const SmallVectorImpl<uint8_t> &Opcodes) {
650 getStreamer().emitUnwindRaw(Offset, Opcodes);
652 void ARMTargetELFStreamer::switchVendor(StringRef Vendor) {
653 assert(!Vendor.empty() && "Vendor cannot be empty.");
655 if (CurrentVendor == Vendor)
658 if (!CurrentVendor.empty())
659 finishAttributeSection();
661 assert(Contents.empty() &&
662 ".ARM.attributes should be flushed before changing vendor");
663 CurrentVendor = Vendor;
666 void ARMTargetELFStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
667 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
669 void ARMTargetELFStreamer::emitTextAttribute(unsigned Attribute,
671 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
673 void ARMTargetELFStreamer::emitIntTextAttribute(unsigned Attribute,
675 StringRef StringValue) {
676 setAttributeItems(Attribute, IntValue, StringValue,
677 /* OverwriteExisting= */ true);
679 void ARMTargetELFStreamer::emitArch(unsigned Value) {
682 void ARMTargetELFStreamer::emitObjectArch(unsigned Value) {
685 void ARMTargetELFStreamer::emitArchDefaultAttributes() {
686 using namespace ARMBuildAttrs;
688 setAttributeItem(CPU_name,
689 ARMTargetParser::getCPUAttr(Arch),
692 if (EmittedArch == ARM::AK_INVALID)
693 setAttributeItem(CPU_arch,
694 ARMTargetParser::getArchAttr(Arch),
697 setAttributeItem(CPU_arch,
698 ARMTargetParser::getArchAttr(EmittedArch),
708 setAttributeItem(ARM_ISA_use, Allowed, false);
713 case ARM::AK_ARMV5TE:
716 setAttributeItem(ARM_ISA_use, Allowed, false);
717 setAttributeItem(THUMB_ISA_use, Allowed, false);
720 case ARM::AK_ARMV6T2:
721 setAttributeItem(ARM_ISA_use, Allowed, false);
722 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
727 case ARM::AK_ARMV6ZK:
728 setAttributeItem(ARM_ISA_use, Allowed, false);
729 setAttributeItem(THUMB_ISA_use, Allowed, false);
730 setAttributeItem(Virtualization_use, AllowTZ, false);
734 setAttributeItem(THUMB_ISA_use, Allowed, false);
738 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
742 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
743 setAttributeItem(ARM_ISA_use, Allowed, false);
744 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
748 setAttributeItem(CPU_arch_profile, RealTimeProfile, false);
749 setAttributeItem(ARM_ISA_use, Allowed, false);
750 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
754 setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
755 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
759 case ARM::AK_ARMV8_1A:
760 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
761 setAttributeItem(ARM_ISA_use, Allowed, false);
762 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
763 setAttributeItem(MPextension_use, Allowed, false);
764 setAttributeItem(Virtualization_use, AllowTZVirtualization, false);
768 setAttributeItem(ARM_ISA_use, Allowed, false);
769 setAttributeItem(THUMB_ISA_use, Allowed, false);
770 setAttributeItem(WMMX_arch, AllowWMMXv1, false);
773 case ARM::AK_IWMMXT2:
774 setAttributeItem(ARM_ISA_use, Allowed, false);
775 setAttributeItem(THUMB_ISA_use, Allowed, false);
776 setAttributeItem(WMMX_arch, AllowWMMXv2, false);
780 report_fatal_error("Unknown Arch: " + Twine(Arch));
784 void ARMTargetELFStreamer::emitFPU(unsigned Value) {
787 void ARMTargetELFStreamer::emitFPUDefaultAttributes() {
791 setAttributeItem(ARMBuildAttrs::FP_arch,
792 ARMBuildAttrs::AllowFPv2,
793 /* OverwriteExisting= */ false);
797 setAttributeItem(ARMBuildAttrs::FP_arch,
798 ARMBuildAttrs::AllowFPv3A,
799 /* OverwriteExisting= */ false);
802 case ARM::FK_VFPV3_D16:
803 setAttributeItem(ARMBuildAttrs::FP_arch,
804 ARMBuildAttrs::AllowFPv3B,
805 /* OverwriteExisting= */ false);
809 setAttributeItem(ARMBuildAttrs::FP_arch,
810 ARMBuildAttrs::AllowFPv4A,
811 /* OverwriteExisting= */ false);
814 case ARM::FK_VFPV4_D16:
815 setAttributeItem(ARMBuildAttrs::FP_arch,
816 ARMBuildAttrs::AllowFPv4B,
817 /* OverwriteExisting= */ false);
820 case ARM::FK_FP_ARMV8:
821 setAttributeItem(ARMBuildAttrs::FP_arch,
822 ARMBuildAttrs::AllowFPARMv8A,
823 /* OverwriteExisting= */ false);
826 // FPV5_D16 is identical to FP_ARMV8 except for the number of D registers, so
827 // uses the FP_ARMV8_D16 build attribute.
828 case ARM::FK_FPV5_D16:
829 setAttributeItem(ARMBuildAttrs::FP_arch,
830 ARMBuildAttrs::AllowFPARMv8B,
831 /* OverwriteExisting= */ false);
835 setAttributeItem(ARMBuildAttrs::FP_arch,
836 ARMBuildAttrs::AllowFPv3A,
837 /* OverwriteExisting= */ false);
838 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
839 ARMBuildAttrs::AllowNeon,
840 /* OverwriteExisting= */ false);
843 case ARM::FK_NEON_VFPV4:
844 setAttributeItem(ARMBuildAttrs::FP_arch,
845 ARMBuildAttrs::AllowFPv4A,
846 /* OverwriteExisting= */ false);
847 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
848 ARMBuildAttrs::AllowNeon2,
849 /* OverwriteExisting= */ false);
852 case ARM::FK_NEON_FP_ARMV8:
853 case ARM::FK_CRYPTO_NEON_FP_ARMV8:
854 setAttributeItem(ARMBuildAttrs::FP_arch,
855 ARMBuildAttrs::AllowFPARMv8A,
856 /* OverwriteExisting= */ false);
857 // 'Advanced_SIMD_arch' must be emitted not here, but within
858 // ARMAsmPrinter::emitAttributes(), depending on hasV8Ops() and hasV8_1a()
861 case ARM::FK_SOFTVFP:
865 report_fatal_error("Unknown FPU: " + Twine(FPU));
869 size_t ARMTargetELFStreamer::calculateContentSize() const {
871 for (size_t i = 0; i < Contents.size(); ++i) {
872 AttributeItem item = Contents[i];
874 case AttributeItem::HiddenAttribute:
876 case AttributeItem::NumericAttribute:
877 Result += getULEB128Size(item.Tag);
878 Result += getULEB128Size(item.IntValue);
880 case AttributeItem::TextAttribute:
881 Result += getULEB128Size(item.Tag);
882 Result += item.StringValue.size() + 1; // string + '\0'
884 case AttributeItem::NumericAndTextAttributes:
885 Result += getULEB128Size(item.Tag);
886 Result += getULEB128Size(item.IntValue);
887 Result += item.StringValue.size() + 1; // string + '\0';
893 void ARMTargetELFStreamer::finishAttributeSection() {
895 // [ <section-length> "vendor-name"
896 // [ <file-tag> <size> <attribute>*
897 // | <section-tag> <size> <section-number>* 0 <attribute>*
898 // | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
902 if (FPU != ARM::FK_INVALID)
903 emitFPUDefaultAttributes();
905 if (Arch != ARM::AK_INVALID)
906 emitArchDefaultAttributes();
908 if (Contents.empty())
911 std::sort(Contents.begin(), Contents.end(), AttributeItem::LessTag);
913 ARMELFStreamer &Streamer = getStreamer();
915 // Switch to .ARM.attributes section
916 if (AttributeSection) {
917 Streamer.SwitchSection(AttributeSection);
919 AttributeSection = Streamer.getContext().getELFSection(
920 ".ARM.attributes", ELF::SHT_ARM_ATTRIBUTES, 0);
921 Streamer.SwitchSection(AttributeSection);
924 Streamer.EmitIntValue(0x41, 1);
927 // Vendor size + Vendor name + '\0'
928 const size_t VendorHeaderSize = 4 + CurrentVendor.size() + 1;
931 const size_t TagHeaderSize = 1 + 4;
933 const size_t ContentsSize = calculateContentSize();
935 Streamer.EmitIntValue(VendorHeaderSize + TagHeaderSize + ContentsSize, 4);
936 Streamer.EmitBytes(CurrentVendor);
937 Streamer.EmitIntValue(0, 1); // '\0'
939 Streamer.EmitIntValue(ARMBuildAttrs::File, 1);
940 Streamer.EmitIntValue(TagHeaderSize + ContentsSize, 4);
942 // Size should have been accounted for already, now
943 // emit each field as its type (ULEB or String)
944 for (size_t i = 0; i < Contents.size(); ++i) {
945 AttributeItem item = Contents[i];
946 Streamer.EmitULEB128IntValue(item.Tag);
948 default: llvm_unreachable("Invalid attribute type");
949 case AttributeItem::NumericAttribute:
950 Streamer.EmitULEB128IntValue(item.IntValue);
952 case AttributeItem::TextAttribute:
953 Streamer.EmitBytes(item.StringValue);
954 Streamer.EmitIntValue(0, 1); // '\0'
956 case AttributeItem::NumericAndTextAttributes:
957 Streamer.EmitULEB128IntValue(item.IntValue);
958 Streamer.EmitBytes(item.StringValue);
959 Streamer.EmitIntValue(0, 1); // '\0'
965 FPU = ARM::FK_INVALID;
968 void ARMTargetELFStreamer::emitLabel(MCSymbol *Symbol) {
969 ARMELFStreamer &Streamer = getStreamer();
970 if (!Streamer.IsThumb)
973 Streamer.getOrCreateSymbolData(Symbol);
974 unsigned Type = cast<MCSymbolELF>(Symbol)->getType();
975 if (Type == ELF_STT_Func || Type == ELF_STT_GnuIFunc)
976 Streamer.EmitThumbFunc(Symbol);
980 ARMTargetELFStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
981 getStreamer().EmitFixup(S, FK_Data_4);
984 void ARMTargetELFStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
985 if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(Value)) {
986 const MCSymbol &Sym = SRE->getSymbol();
987 if (!Sym.isDefined()) {
988 getStreamer().EmitAssignment(Symbol, Value);
993 getStreamer().EmitThumbFunc(Symbol);
994 getStreamer().EmitAssignment(Symbol, Value);
997 void ARMTargetELFStreamer::emitInst(uint32_t Inst, char Suffix) {
998 getStreamer().emitInst(Inst, Suffix);
1001 void ARMELFStreamer::FinishImpl() {
1002 MCTargetStreamer &TS = *getTargetStreamer();
1003 ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1004 ATS.finishAttributeSection();
1006 MCELFStreamer::FinishImpl();
1009 inline void ARMELFStreamer::SwitchToEHSection(const char *Prefix,
1013 const MCSymbol &Fn) {
1014 const MCSectionELF &FnSection =
1015 static_cast<const MCSectionELF &>(Fn.getSection());
1017 // Create the name for new section
1018 StringRef FnSecName(FnSection.getSectionName());
1019 SmallString<128> EHSecName(Prefix);
1020 if (FnSecName != ".text") {
1021 EHSecName += FnSecName;
1024 // Get .ARM.extab or .ARM.exidx section
1025 const MCSymbol *Group = FnSection.getGroup();
1027 Flags |= ELF::SHF_GROUP;
1028 MCSectionELF *EHSection =
1029 getContext().getELFSection(EHSecName, Type, Flags, 0, Group,
1030 FnSection.getUniqueID(), nullptr, &FnSection);
1032 assert(EHSection && "Failed to get the required EH section");
1034 // Switch to .ARM.extab or .ARM.exidx section
1035 SwitchSection(EHSection);
1036 EmitCodeAlignment(4);
1039 inline void ARMELFStreamer::SwitchToExTabSection(const MCSymbol &FnStart) {
1040 SwitchToEHSection(".ARM.extab",
1043 SectionKind::getDataRel(),
1047 inline void ARMELFStreamer::SwitchToExIdxSection(const MCSymbol &FnStart) {
1048 SwitchToEHSection(".ARM.exidx",
1050 ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER,
1051 SectionKind::getDataRel(),
1054 void ARMELFStreamer::EmitFixup(const MCExpr *Expr, MCFixupKind Kind) {
1055 MCDataFragment *Frag = getOrCreateDataFragment();
1056 Frag->getFixups().push_back(MCFixup::create(Frag->getContents().size(), Expr,
1060 void ARMELFStreamer::Reset() {
1063 Personality = nullptr;
1064 PersonalityIndex = ARM::EHABI::NUM_PERSONALITY_INDEX;
1073 UnwindOpAsm.Reset();
1076 void ARMELFStreamer::emitFnStart() {
1077 assert(FnStart == nullptr);
1078 FnStart = getContext().createTempSymbol();
1082 void ARMELFStreamer::emitFnEnd() {
1083 assert(FnStart && ".fnstart must precedes .fnend");
1085 // Emit unwind opcodes if there is no .handlerdata directive
1086 if (!ExTab && !CantUnwind)
1087 FlushUnwindOpcodes(true);
1089 // Emit the exception index table entry
1090 SwitchToExIdxSection(*FnStart);
1092 if (PersonalityIndex < ARM::EHABI::NUM_PERSONALITY_INDEX)
1093 EmitPersonalityFixup(GetAEABIUnwindPersonalityName(PersonalityIndex));
1095 const MCSymbolRefExpr *FnStartRef =
1096 MCSymbolRefExpr::create(FnStart,
1097 MCSymbolRefExpr::VK_ARM_PREL31,
1100 EmitValue(FnStartRef, 4);
1103 EmitIntValue(ARM::EHABI::EXIDX_CANTUNWIND, 4);
1105 // Emit a reference to the unwind opcodes in the ".ARM.extab" section.
1106 const MCSymbolRefExpr *ExTabEntryRef =
1107 MCSymbolRefExpr::create(ExTab,
1108 MCSymbolRefExpr::VK_ARM_PREL31,
1110 EmitValue(ExTabEntryRef, 4);
1112 // For the __aeabi_unwind_cpp_pr0, we have to emit the unwind opcodes in
1113 // the second word of exception index table entry. The size of the unwind
1114 // opcodes should always be 4 bytes.
1115 assert(PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0 &&
1116 "Compact model must use __aeabi_unwind_cpp_pr0 as personality");
1117 assert(Opcodes.size() == 4u &&
1118 "Unwind opcode size for __aeabi_unwind_cpp_pr0 must be equal to 4");
1119 uint64_t Intval = Opcodes[0] |
1123 EmitIntValue(Intval, Opcodes.size());
1126 // Switch to the section containing FnStart
1127 SwitchSection(&FnStart->getSection());
1129 // Clean exception handling frame information
1133 void ARMELFStreamer::emitCantUnwind() { CantUnwind = true; }
1135 // Add the R_ARM_NONE fixup at the same position
1136 void ARMELFStreamer::EmitPersonalityFixup(StringRef Name) {
1137 const MCSymbol *PersonalitySym = getContext().getOrCreateSymbol(Name);
1139 const MCSymbolRefExpr *PersonalityRef = MCSymbolRefExpr::create(
1140 PersonalitySym, MCSymbolRefExpr::VK_ARM_NONE, getContext());
1142 visitUsedExpr(*PersonalityRef);
1143 MCDataFragment *DF = getOrCreateDataFragment();
1144 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
1146 MCFixup::getKindForSize(4, false)));
1149 void ARMELFStreamer::FlushPendingOffset() {
1150 if (PendingOffset != 0) {
1151 UnwindOpAsm.EmitSPOffset(-PendingOffset);
1156 void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) {
1157 // Emit the unwind opcode to restore $sp.
1159 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1160 int64_t LastRegSaveSPOffset = SPOffset - PendingOffset;
1161 UnwindOpAsm.EmitSPOffset(LastRegSaveSPOffset - FPOffset);
1162 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1164 FlushPendingOffset();
1167 // Finalize the unwind opcode sequence
1168 UnwindOpAsm.Finalize(PersonalityIndex, Opcodes);
1170 // For compact model 0, we have to emit the unwind opcodes in the .ARM.exidx
1171 // section. Thus, we don't have to create an entry in the .ARM.extab
1173 if (NoHandlerData && PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0)
1176 // Switch to .ARM.extab section.
1177 SwitchToExTabSection(*FnStart);
1179 // Create .ARM.extab label for offset in .ARM.exidx
1181 ExTab = getContext().createTempSymbol();
1186 const MCSymbolRefExpr *PersonalityRef =
1187 MCSymbolRefExpr::create(Personality,
1188 MCSymbolRefExpr::VK_ARM_PREL31,
1191 EmitValue(PersonalityRef, 4);
1194 // Emit unwind opcodes
1195 assert((Opcodes.size() % 4) == 0 &&
1196 "Unwind opcode size for __aeabi_cpp_unwind_pr0 must be multiple of 4");
1197 for (unsigned I = 0; I != Opcodes.size(); I += 4) {
1198 uint64_t Intval = Opcodes[I] |
1199 Opcodes[I + 1] << 8 |
1200 Opcodes[I + 2] << 16 |
1201 Opcodes[I + 3] << 24;
1202 EmitIntValue(Intval, 4);
1205 // According to ARM EHABI section 9.2, if the __aeabi_unwind_cpp_pr1() or
1206 // __aeabi_unwind_cpp_pr2() is used, then the handler data must be emitted
1207 // after the unwind opcodes. The handler data consists of several 32-bit
1208 // words, and should be terminated by zero.
1210 // In case that the .handlerdata directive is not specified by the
1211 // programmer, we should emit zero to terminate the handler data.
1212 if (NoHandlerData && !Personality)
1216 void ARMELFStreamer::emitHandlerData() { FlushUnwindOpcodes(false); }
1218 void ARMELFStreamer::emitPersonality(const MCSymbol *Per) {
1220 UnwindOpAsm.setPersonality(Per);
1223 void ARMELFStreamer::emitPersonalityIndex(unsigned Index) {
1224 assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX && "invalid index");
1225 PersonalityIndex = Index;
1228 void ARMELFStreamer::emitSetFP(unsigned NewFPReg, unsigned NewSPReg,
1230 assert((NewSPReg == ARM::SP || NewSPReg == FPReg) &&
1231 "the operand of .setfp directive should be either $sp or $fp");
1236 if (NewSPReg == ARM::SP)
1237 FPOffset = SPOffset + Offset;
1242 void ARMELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
1243 assert((Reg != ARM::SP && Reg != ARM::PC) &&
1244 "the operand of .movsp cannot be either sp or pc");
1245 assert(FPReg == ARM::SP && "current FP must be SP");
1247 FlushPendingOffset();
1250 FPOffset = SPOffset + Offset;
1252 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1253 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1256 void ARMELFStreamer::emitPad(int64_t Offset) {
1257 // Track the change of the $sp offset
1260 // To squash multiple .pad directives, we should delay the unwind opcode
1261 // until the .save, .vsave, .handlerdata, or .fnend directives.
1262 PendingOffset -= Offset;
1265 void ARMELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
1267 // Collect the registers in the register list
1270 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1271 for (size_t i = 0; i < RegList.size(); ++i) {
1272 unsigned Reg = MRI->getEncodingValue(RegList[i]);
1273 assert(Reg < (IsVector ? 32U : 16U) && "Register out of range");
1274 unsigned Bit = (1u << Reg);
1275 if ((Mask & Bit) == 0) {
1281 // Track the change the $sp offset: For the .save directive, the
1282 // corresponding push instruction will decrease the $sp by (4 * Count).
1283 // For the .vsave directive, the corresponding vpush instruction will
1284 // decrease $sp by (8 * Count).
1285 SPOffset -= Count * (IsVector ? 8 : 4);
1288 FlushPendingOffset();
1290 UnwindOpAsm.EmitVFPRegSave(Mask);
1292 UnwindOpAsm.EmitRegSave(Mask);
1295 void ARMELFStreamer::emitUnwindRaw(int64_t Offset,
1296 const SmallVectorImpl<uint8_t> &Opcodes) {
1297 FlushPendingOffset();
1298 SPOffset = SPOffset - Offset;
1299 UnwindOpAsm.EmitRaw(Opcodes);
1304 MCTargetStreamer *createARMTargetAsmStreamer(MCStreamer &S,
1305 formatted_raw_ostream &OS,
1306 MCInstPrinter *InstPrint,
1307 bool isVerboseAsm) {
1308 return new ARMTargetAsmStreamer(S, OS, *InstPrint, isVerboseAsm);
1311 MCTargetStreamer *createARMNullTargetStreamer(MCStreamer &S) {
1312 return new ARMTargetStreamer(S);
1315 MCTargetStreamer *createARMObjectTargetStreamer(MCStreamer &S,
1316 const MCSubtargetInfo &STI) {
1317 Triple TT(STI.getTargetTriple());
1318 if (TT.getObjectFormat() == Triple::ELF)
1319 return new ARMTargetELFStreamer(S);
1320 return new ARMTargetStreamer(S);
1323 MCELFStreamer *createARMELFStreamer(MCContext &Context, MCAsmBackend &TAB,
1324 raw_pwrite_stream &OS,
1325 MCCodeEmitter *Emitter, bool RelaxAll,
1327 ARMELFStreamer *S = new ARMELFStreamer(Context, TAB, OS, Emitter, IsThumb);
1328 // FIXME: This should eventually end up somewhere else where more
1329 // intelligent flag decisions can be made. For now we are just maintaining
1330 // the status quo for ARM and setting EF_ARM_EABI_VER5 as the default.
1331 S->getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
1334 S->getAssembler().setRelaxAll(true);