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 "ARMBuildAttrs.h"
17 #include "ARMArchName.h"
18 #include "ARMFPUName.h"
19 #include "ARMRegisterInfo.h"
20 #include "ARMUnwindOp.h"
21 #include "ARMUnwindOpAsm.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/MC/MCAsmBackend.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCAssembler.h"
28 #include "llvm/MC/MCCodeEmitter.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCELF.h"
31 #include "llvm/MC/MCELFStreamer.h"
32 #include "llvm/MC/MCELFSymbolFlags.h"
33 #include "llvm/MC/MCExpr.h"
34 #include "llvm/MC/MCInst.h"
35 #include "llvm/MC/MCInstPrinter.h"
36 #include "llvm/MC/MCObjectStreamer.h"
37 #include "llvm/MC/MCRegisterInfo.h"
38 #include "llvm/MC/MCSection.h"
39 #include "llvm/MC/MCSectionELF.h"
40 #include "llvm/MC/MCStreamer.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/MC/MCValue.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ELF.h"
45 #include "llvm/Support/FormattedStream.h"
46 #include "llvm/Support/raw_ostream.h"
51 static std::string GetAEABIUnwindPersonalityName(unsigned Index) {
52 assert(Index < NUM_PERSONALITY_INDEX && "Invalid personality index");
53 return (Twine("__aeabi_unwind_cpp_pr") + Twine(Index)).str();
56 static const char *GetFPUName(unsigned ID) {
59 llvm_unreachable("Unknown FPU kind");
61 #define ARM_FPU_NAME(NAME, ID) case ARM::ID: return NAME;
62 #include "ARMFPUName.def"
67 static const char *GetArchName(unsigned ID) {
70 llvm_unreachable("Unknown ARCH kind");
72 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
73 case ARM::ID: return NAME;
74 #include "ARMArchName.def"
79 static const char *GetArchDefaultCPUName(unsigned ID) {
82 llvm_unreachable("Unknown ARCH kind");
84 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
85 case ARM::ID: return DEFAULT_CPU_NAME;
86 #include "ARMArchName.def"
91 static unsigned GetArchDefaultCPUArch(unsigned ID) {
94 llvm_unreachable("Unknown ARCH kind");
96 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
97 case ARM::ID: return ARMBuildAttrs::DEFAULT_CPU_ARCH;
98 #include "ARMArchName.def"
105 class ARMELFStreamer;
107 class ARMTargetAsmStreamer : public ARMTargetStreamer {
108 formatted_raw_ostream &OS;
109 MCInstPrinter &InstPrinter;
111 virtual void emitFnStart();
112 virtual void emitFnEnd();
113 virtual void emitCantUnwind();
114 virtual void emitPersonality(const MCSymbol *Personality);
115 virtual void emitHandlerData();
116 virtual void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
117 virtual void emitPad(int64_t Offset);
118 virtual void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
121 virtual void switchVendor(StringRef Vendor);
122 virtual void emitAttribute(unsigned Attribute, unsigned Value);
123 virtual void emitTextAttribute(unsigned Attribute, StringRef String);
124 virtual void emitArch(unsigned Arch);
125 virtual void emitFPU(unsigned FPU);
126 virtual void emitInst(uint32_t Inst, char Suffix = '\0');
127 virtual void finishAttributeSection();
130 ARMTargetAsmStreamer(formatted_raw_ostream &OS, MCInstPrinter &InstPrinter);
133 ARMTargetAsmStreamer::ARMTargetAsmStreamer(formatted_raw_ostream &OS,
134 MCInstPrinter &InstPrinter)
135 : OS(OS), InstPrinter(InstPrinter) {}
136 void ARMTargetAsmStreamer::emitFnStart() { OS << "\t.fnstart\n"; }
137 void ARMTargetAsmStreamer::emitFnEnd() { OS << "\t.fnend\n"; }
138 void ARMTargetAsmStreamer::emitCantUnwind() { OS << "\t.cantunwind\n"; }
139 void ARMTargetAsmStreamer::emitPersonality(const MCSymbol *Personality) {
140 OS << "\t.personality " << Personality->getName() << '\n';
142 void ARMTargetAsmStreamer::emitHandlerData() { OS << "\t.handlerdata\n"; }
143 void ARMTargetAsmStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
146 InstPrinter.printRegName(OS, FpReg);
148 InstPrinter.printRegName(OS, SpReg);
150 OS << ", #" << Offset;
153 void ARMTargetAsmStreamer::emitPad(int64_t Offset) {
154 OS << "\t.pad\t#" << Offset << '\n';
156 void ARMTargetAsmStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
158 assert(RegList.size() && "RegList should not be empty");
164 InstPrinter.printRegName(OS, RegList[0]);
166 for (unsigned i = 1, e = RegList.size(); i != e; ++i) {
168 InstPrinter.printRegName(OS, RegList[i]);
173 void ARMTargetAsmStreamer::switchVendor(StringRef Vendor) {
175 void ARMTargetAsmStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
176 OS << "\t.eabi_attribute\t" << Attribute << ", " << Twine(Value) << "\n";
178 void ARMTargetAsmStreamer::emitTextAttribute(unsigned Attribute,
181 default: llvm_unreachable("Unsupported Text attribute in ASM Mode");
182 case ARMBuildAttrs::CPU_name:
183 OS << "\t.cpu\t" << String.lower() << "\n";
187 void ARMTargetAsmStreamer::emitArch(unsigned Arch) {
188 OS << "\t.arch\t" << GetArchName(Arch) << "\n";
190 void ARMTargetAsmStreamer::emitFPU(unsigned FPU) {
191 OS << "\t.fpu\t" << GetFPUName(FPU) << "\n";
193 void ARMTargetAsmStreamer::finishAttributeSection() {
196 void ARMTargetAsmStreamer::emitInst(uint32_t Inst, char Suffix) {
200 OS << "\t0x" << utohexstr(Inst) << "\n";
203 class ARMTargetELFStreamer : public ARMTargetStreamer {
205 // This structure holds all attributes, accounting for
206 // their string/numeric value, so we can later emmit them
207 // in declaration order, keeping all in the same vector
208 struct AttributeItem {
216 StringRef StringValue;
218 static bool LessTag(const AttributeItem &LHS, const AttributeItem &RHS) {
219 return (LHS.Tag < RHS.Tag);
223 StringRef CurrentVendor;
226 SmallVector<AttributeItem, 64> Contents;
228 const MCSection *AttributeSection;
230 // FIXME: this should be in a more generic place, but
231 // getULEBSize() is in MCAsmInfo and will be moved to MCDwarf
232 static size_t getULEBSize(int Value) {
236 Size += sizeof(int8_t); // Is this really necessary?
241 AttributeItem *getAttributeItem(unsigned Attribute) {
242 for (size_t i = 0; i < Contents.size(); ++i)
243 if (Contents[i].Tag == Attribute)
248 void setAttributeItem(unsigned Attribute, unsigned Value,
249 bool OverwriteExisting) {
250 // Look for existing attribute item
251 if (AttributeItem *Item = getAttributeItem(Attribute)) {
252 if (!OverwriteExisting)
254 Item->IntValue = Value;
258 // Create new attribute item
259 AttributeItem Item = {
260 AttributeItem::NumericAttribute,
265 Contents.push_back(Item);
268 void setAttributeItem(unsigned Attribute, StringRef Value,
269 bool OverwriteExisting) {
270 // Look for existing attribute item
271 if (AttributeItem *Item = getAttributeItem(Attribute)) {
272 if (!OverwriteExisting)
274 Item->StringValue = Value;
278 // Create new attribute item
279 AttributeItem Item = {
280 AttributeItem::TextAttribute,
285 Contents.push_back(Item);
288 void emitArchDefaultAttributes();
289 void emitFPUDefaultAttributes();
291 ARMELFStreamer &getStreamer();
293 virtual void emitFnStart();
294 virtual void emitFnEnd();
295 virtual void emitCantUnwind();
296 virtual void emitPersonality(const MCSymbol *Personality);
297 virtual void emitHandlerData();
298 virtual void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
299 virtual void emitPad(int64_t Offset);
300 virtual void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
303 virtual void switchVendor(StringRef Vendor);
304 virtual void emitAttribute(unsigned Attribute, unsigned Value);
305 virtual void emitTextAttribute(unsigned Attribute, StringRef String);
306 virtual void emitArch(unsigned Arch);
307 virtual void emitFPU(unsigned FPU);
308 virtual void emitInst(uint32_t Inst, char Suffix = '\0');
309 virtual void finishAttributeSection();
311 size_t calculateContentSize() const;
314 ARMTargetELFStreamer()
315 : ARMTargetStreamer(), CurrentVendor("aeabi"), FPU(ARM::INVALID_FPU),
316 Arch(ARM::INVALID_ARCH), AttributeSection(0) {
320 /// Extend the generic ELFStreamer class so that it can emit mapping symbols at
321 /// the appropriate points in the object files. These symbols are defined in the
322 /// ARM ELF ABI: infocenter.arm.com/help/topic/com.arm.../IHI0044D_aaelf.pdf.
324 /// In brief: $a, $t or $d should be emitted at the start of each contiguous
325 /// region of ARM code, Thumb code or data in a section. In practice, this
326 /// emission does not rely on explicit assembler directives but on inherent
327 /// properties of the directives doing the emission (e.g. ".byte" is data, "add
328 /// r0, r0, r0" an instruction).
330 /// As a result this system is orthogonal to the DataRegion infrastructure used
331 /// by MachO. Beware!
332 class ARMELFStreamer : public MCELFStreamer {
334 friend class ARMTargetELFStreamer;
336 ARMELFStreamer(MCContext &Context, MCTargetStreamer *TargetStreamer,
337 MCAsmBackend &TAB, raw_ostream &OS, MCCodeEmitter *Emitter,
339 : MCELFStreamer(Context, TargetStreamer, TAB, OS, Emitter),
340 IsThumb(IsThumb), MappingSymbolCounter(0), LastEMS(EMS_None) {
346 virtual void FinishImpl();
348 // ARM exception handling directives
351 void emitCantUnwind();
352 void emitPersonality(const MCSymbol *Per);
353 void emitHandlerData();
354 void emitSetFP(unsigned NewFpReg, unsigned NewSpReg, int64_t Offset = 0);
355 void emitPad(int64_t Offset);
356 void emitRegSave(const SmallVectorImpl<unsigned> &RegList, bool isVector);
358 virtual void ChangeSection(const MCSection *Section,
359 const MCExpr *Subsection) {
360 // We have to keep track of the mapping symbol state of any sections we
361 // use. Each one should start off as EMS_None, which is provided as the
362 // default constructor by DenseMap::lookup.
363 LastMappingSymbols[getPreviousSection().first] = LastEMS;
364 LastEMS = LastMappingSymbols.lookup(Section);
366 MCELFStreamer::ChangeSection(Section, Subsection);
369 /// This function is the one used to emit instruction data into the ELF
370 /// streamer. We override it to add the appropriate mapping symbol if
372 virtual void EmitInstruction(const MCInst& Inst) {
374 EmitThumbMappingSymbol();
376 EmitARMMappingSymbol();
378 MCELFStreamer::EmitInstruction(Inst);
381 virtual void emitInst(uint32_t Inst, char Suffix) {
384 const bool LittleEndian = getContext().getAsmInfo()->isLittleEndian();
391 EmitARMMappingSymbol();
392 for (unsigned II = 0, IE = Size; II != IE; II++) {
393 const unsigned I = LittleEndian ? (Size - II - 1) : II;
394 Buffer[Size - II - 1] = uint8_t(Inst >> I * CHAR_BIT);
400 Size = (Suffix == 'n' ? 2 : 4);
403 EmitThumbMappingSymbol();
404 for (unsigned II = 0, IE = Size; II != IE; II = II + 2) {
405 const unsigned I0 = LittleEndian ? II + 0 : (Size - II - 1);
406 const unsigned I1 = LittleEndian ? II + 1 : (Size - II - 2);
407 Buffer[Size - II - 2] = uint8_t(Inst >> I0 * CHAR_BIT);
408 Buffer[Size - II - 1] = uint8_t(Inst >> I1 * CHAR_BIT);
413 llvm_unreachable("Invalid Suffix");
416 MCELFStreamer::EmitBytes(StringRef(Buffer, Size));
419 /// This is one of the functions used to emit data into an ELF section, so the
420 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
422 virtual void EmitBytes(StringRef Data) {
423 EmitDataMappingSymbol();
424 MCELFStreamer::EmitBytes(Data);
427 /// This is one of the functions used to emit data into an ELF section, so the
428 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
430 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {
431 EmitDataMappingSymbol();
432 MCELFStreamer::EmitValueImpl(Value, Size);
435 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {
436 MCELFStreamer::EmitAssemblerFlag(Flag);
439 case MCAF_SyntaxUnified:
440 return; // no-op here.
443 return; // Change to Thumb mode
446 return; // Change to ARM mode
449 case MCAF_SubsectionsViaSymbols:
455 enum ElfMappingSymbol {
462 void EmitDataMappingSymbol() {
463 if (LastEMS == EMS_Data) return;
464 EmitMappingSymbol("$d");
468 void EmitThumbMappingSymbol() {
469 if (LastEMS == EMS_Thumb) return;
470 EmitMappingSymbol("$t");
474 void EmitARMMappingSymbol() {
475 if (LastEMS == EMS_ARM) return;
476 EmitMappingSymbol("$a");
480 void EmitMappingSymbol(StringRef Name) {
481 MCSymbol *Start = getContext().CreateTempSymbol();
485 getContext().GetOrCreateSymbol(Name + "." +
486 Twine(MappingSymbolCounter++));
488 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
489 MCELF::SetType(SD, ELF::STT_NOTYPE);
490 MCELF::SetBinding(SD, ELF::STB_LOCAL);
491 SD.setExternal(false);
492 AssignSection(Symbol, getCurrentSection().first);
494 const MCExpr *Value = MCSymbolRefExpr::Create(Start, getContext());
495 Symbol->setVariableValue(Value);
498 void EmitThumbFunc(MCSymbol *Func) {
499 // FIXME: Anything needed here to flag the function as thumb?
501 getAssembler().setIsThumbFunc(Func);
503 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Func);
504 SD.setFlags(SD.getFlags() | ELF_Other_ThumbFunc);
507 // Helper functions for ARM exception handling directives
510 void EmitPersonalityFixup(StringRef Name);
511 void FlushPendingOffset();
512 void FlushUnwindOpcodes(bool NoHandlerData);
514 void SwitchToEHSection(const char *Prefix, unsigned Type, unsigned Flags,
515 SectionKind Kind, const MCSymbol &Fn);
516 void SwitchToExTabSection(const MCSymbol &FnStart);
517 void SwitchToExIdxSection(const MCSymbol &FnStart);
520 int64_t MappingSymbolCounter;
522 DenseMap<const MCSection *, ElfMappingSymbol> LastMappingSymbols;
523 ElfMappingSymbol LastEMS;
525 // ARM Exception Handling Frame Information
528 const MCSymbol *Personality;
529 unsigned PersonalityIndex;
530 unsigned FPReg; // Frame pointer register
531 int64_t FPOffset; // Offset: (final frame pointer) - (initial $sp)
532 int64_t SPOffset; // Offset: (final $sp) - (initial $sp)
533 int64_t PendingOffset; // Offset: (final $sp) - (emitted $sp)
536 SmallVector<uint8_t, 64> Opcodes;
537 UnwindOpcodeAssembler UnwindOpAsm;
539 } // end anonymous namespace
541 ARMELFStreamer &ARMTargetELFStreamer::getStreamer() {
542 ARMELFStreamer *S = static_cast<ARMELFStreamer *>(Streamer);
546 void ARMTargetELFStreamer::emitFnStart() { getStreamer().emitFnStart(); }
547 void ARMTargetELFStreamer::emitFnEnd() { getStreamer().emitFnEnd(); }
548 void ARMTargetELFStreamer::emitCantUnwind() { getStreamer().emitCantUnwind(); }
549 void ARMTargetELFStreamer::emitPersonality(const MCSymbol *Personality) {
550 getStreamer().emitPersonality(Personality);
552 void ARMTargetELFStreamer::emitHandlerData() {
553 getStreamer().emitHandlerData();
555 void ARMTargetELFStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
557 getStreamer().emitSetFP(FpReg, SpReg, Offset);
559 void ARMTargetELFStreamer::emitPad(int64_t Offset) {
560 getStreamer().emitPad(Offset);
562 void ARMTargetELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
564 getStreamer().emitRegSave(RegList, isVector);
566 void ARMTargetELFStreamer::switchVendor(StringRef Vendor) {
567 assert(!Vendor.empty() && "Vendor cannot be empty.");
569 if (CurrentVendor == Vendor)
572 if (!CurrentVendor.empty())
573 finishAttributeSection();
575 assert(Contents.empty() &&
576 ".ARM.attributes should be flushed before changing vendor");
577 CurrentVendor = Vendor;
580 void ARMTargetELFStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
581 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
583 void ARMTargetELFStreamer::emitTextAttribute(unsigned Attribute,
585 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
587 void ARMTargetELFStreamer::emitArch(unsigned Value) {
590 void ARMTargetELFStreamer::emitArchDefaultAttributes() {
591 using namespace ARMBuildAttrs;
592 setAttributeItem(CPU_name, GetArchDefaultCPUName(Arch), false);
593 setAttributeItem(CPU_arch, GetArchDefaultCPUArch(Arch), false);
602 setAttributeItem(ARM_ISA_use, Allowed, false);
610 setAttributeItem(ARM_ISA_use, Allowed, false);
611 setAttributeItem(THUMB_ISA_use, Allowed, false);
615 setAttributeItem(ARM_ISA_use, Allowed, false);
616 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
621 setAttributeItem(ARM_ISA_use, Allowed, false);
622 setAttributeItem(THUMB_ISA_use, Allowed, false);
623 setAttributeItem(Virtualization_use, AllowTZ, false);
627 setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
628 setAttributeItem(THUMB_ISA_use, Allowed, false);
632 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
636 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
637 setAttributeItem(ARM_ISA_use, Allowed, false);
638 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
642 setAttributeItem(CPU_arch_profile, RealTimeProfile, false);
643 setAttributeItem(ARM_ISA_use, Allowed, false);
644 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
648 setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
649 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
653 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
654 setAttributeItem(ARM_ISA_use, Allowed, false);
655 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
656 setAttributeItem(MPextension_use, Allowed, false);
657 setAttributeItem(Virtualization_use, AllowTZVirtualization, false);
661 setAttributeItem(ARM_ISA_use, Allowed, false);
662 setAttributeItem(THUMB_ISA_use, Allowed, false);
663 setAttributeItem(WMMX_arch, AllowWMMXv1, false);
667 setAttributeItem(ARM_ISA_use, Allowed, false);
668 setAttributeItem(THUMB_ISA_use, Allowed, false);
669 setAttributeItem(WMMX_arch, AllowWMMXv2, false);
673 report_fatal_error("Unknown Arch: " + Twine(Arch));
677 void ARMTargetELFStreamer::emitFPU(unsigned Value) {
680 void ARMTargetELFStreamer::emitFPUDefaultAttributes() {
684 setAttributeItem(ARMBuildAttrs::FP_arch,
685 ARMBuildAttrs::AllowFPv2,
686 /* OverwriteExisting= */ false);
690 setAttributeItem(ARMBuildAttrs::FP_arch,
691 ARMBuildAttrs::AllowFPv3A,
692 /* OverwriteExisting= */ false);
696 setAttributeItem(ARMBuildAttrs::FP_arch,
697 ARMBuildAttrs::AllowFPv3B,
698 /* OverwriteExisting= */ false);
702 setAttributeItem(ARMBuildAttrs::FP_arch,
703 ARMBuildAttrs::AllowFPv4A,
704 /* OverwriteExisting= */ false);
708 setAttributeItem(ARMBuildAttrs::FP_arch,
709 ARMBuildAttrs::AllowFPv4B,
710 /* OverwriteExisting= */ false);
714 setAttributeItem(ARMBuildAttrs::FP_arch,
715 ARMBuildAttrs::AllowFPARMv8A,
716 /* OverwriteExisting= */ false);
720 setAttributeItem(ARMBuildAttrs::FP_arch,
721 ARMBuildAttrs::AllowFPv3A,
722 /* OverwriteExisting= */ false);
723 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
724 ARMBuildAttrs::AllowNeon,
725 /* OverwriteExisting= */ false);
728 case ARM::NEON_VFPV4:
729 setAttributeItem(ARMBuildAttrs::FP_arch,
730 ARMBuildAttrs::AllowFPv4A,
731 /* OverwriteExisting= */ false);
732 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
733 ARMBuildAttrs::AllowNeon2,
734 /* OverwriteExisting= */ false);
737 case ARM::NEON_FP_ARMV8:
738 case ARM::CRYPTO_NEON_FP_ARMV8:
739 setAttributeItem(ARMBuildAttrs::FP_arch,
740 ARMBuildAttrs::AllowFPARMv8A,
741 /* OverwriteExisting= */ false);
742 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
743 ARMBuildAttrs::AllowNeonARMv8,
744 /* OverwriteExisting= */ false);
748 report_fatal_error("Unknown FPU: " + Twine(FPU));
752 size_t ARMTargetELFStreamer::calculateContentSize() const {
754 for (size_t i = 0; i < Contents.size(); ++i) {
755 AttributeItem item = Contents[i];
757 case AttributeItem::HiddenAttribute:
759 case AttributeItem::NumericAttribute:
760 Result += getULEBSize(item.Tag);
761 Result += getULEBSize(item.IntValue);
763 case AttributeItem::TextAttribute:
764 Result += getULEBSize(item.Tag);
765 Result += item.StringValue.size() + 1; // string + '\0'
771 void ARMTargetELFStreamer::finishAttributeSection() {
773 // [ <section-length> "vendor-name"
774 // [ <file-tag> <size> <attribute>*
775 // | <section-tag> <size> <section-number>* 0 <attribute>*
776 // | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
780 if (FPU != ARM::INVALID_FPU)
781 emitFPUDefaultAttributes();
783 if (Arch != ARM::INVALID_ARCH)
784 emitArchDefaultAttributes();
786 if (Contents.empty())
789 std::sort(Contents.begin(), Contents.end(), AttributeItem::LessTag);
791 ARMELFStreamer &Streamer = getStreamer();
793 // Switch to .ARM.attributes section
794 if (AttributeSection) {
795 Streamer.SwitchSection(AttributeSection);
798 Streamer.getContext().getELFSection(".ARM.attributes",
799 ELF::SHT_ARM_ATTRIBUTES,
801 SectionKind::getMetadata());
802 Streamer.SwitchSection(AttributeSection);
805 Streamer.EmitIntValue(0x41, 1);
808 // Vendor size + Vendor name + '\0'
809 const size_t VendorHeaderSize = 4 + CurrentVendor.size() + 1;
812 const size_t TagHeaderSize = 1 + 4;
814 const size_t ContentsSize = calculateContentSize();
816 Streamer.EmitIntValue(VendorHeaderSize + TagHeaderSize + ContentsSize, 4);
817 Streamer.EmitBytes(CurrentVendor);
818 Streamer.EmitIntValue(0, 1); // '\0'
820 Streamer.EmitIntValue(ARMBuildAttrs::File, 1);
821 Streamer.EmitIntValue(TagHeaderSize + ContentsSize, 4);
823 // Size should have been accounted for already, now
824 // emit each field as its type (ULEB or String)
825 for (size_t i = 0; i < Contents.size(); ++i) {
826 AttributeItem item = Contents[i];
827 Streamer.EmitULEB128IntValue(item.Tag);
829 default: llvm_unreachable("Invalid attribute type");
830 case AttributeItem::NumericAttribute:
831 Streamer.EmitULEB128IntValue(item.IntValue);
833 case AttributeItem::TextAttribute:
834 Streamer.EmitBytes(item.StringValue.upper());
835 Streamer.EmitIntValue(0, 1); // '\0'
841 FPU = ARM::INVALID_FPU;
843 void ARMTargetELFStreamer::emitInst(uint32_t Inst, char Suffix) {
844 getStreamer().emitInst(Inst, Suffix);
847 void ARMELFStreamer::FinishImpl() {
848 MCTargetStreamer &TS = getTargetStreamer();
849 ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
850 ATS.finishAttributeSection();
852 MCELFStreamer::FinishImpl();
855 inline void ARMELFStreamer::SwitchToEHSection(const char *Prefix,
859 const MCSymbol &Fn) {
860 const MCSectionELF &FnSection =
861 static_cast<const MCSectionELF &>(Fn.getSection());
863 // Create the name for new section
864 StringRef FnSecName(FnSection.getSectionName());
865 SmallString<128> EHSecName(Prefix);
866 if (FnSecName != ".text") {
867 EHSecName += FnSecName;
870 // Get .ARM.extab or .ARM.exidx section
871 const MCSectionELF *EHSection = NULL;
872 if (const MCSymbol *Group = FnSection.getGroup()) {
873 EHSection = getContext().getELFSection(
874 EHSecName, Type, Flags | ELF::SHF_GROUP, Kind,
875 FnSection.getEntrySize(), Group->getName());
877 EHSection = getContext().getELFSection(EHSecName, Type, Flags, Kind);
879 assert(EHSection && "Failed to get the required EH section");
881 // Switch to .ARM.extab or .ARM.exidx section
882 SwitchSection(EHSection);
883 EmitCodeAlignment(4, 0);
886 inline void ARMELFStreamer::SwitchToExTabSection(const MCSymbol &FnStart) {
887 SwitchToEHSection(".ARM.extab",
890 SectionKind::getDataRel(),
894 inline void ARMELFStreamer::SwitchToExIdxSection(const MCSymbol &FnStart) {
895 SwitchToEHSection(".ARM.exidx",
897 ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER,
898 SectionKind::getDataRel(),
902 void ARMELFStreamer::Reset() {
906 PersonalityIndex = NUM_PERSONALITY_INDEX;
918 void ARMELFStreamer::emitFnStart() {
919 assert(FnStart == 0);
920 FnStart = getContext().CreateTempSymbol();
924 void ARMELFStreamer::emitFnEnd() {
925 assert(FnStart && ".fnstart must preceeds .fnend");
927 // Emit unwind opcodes if there is no .handlerdata directive
928 if (!ExTab && !CantUnwind)
929 FlushUnwindOpcodes(true);
931 // Emit the exception index table entry
932 SwitchToExIdxSection(*FnStart);
934 if (PersonalityIndex < NUM_PERSONALITY_INDEX)
935 EmitPersonalityFixup(GetAEABIUnwindPersonalityName(PersonalityIndex));
937 const MCSymbolRefExpr *FnStartRef =
938 MCSymbolRefExpr::Create(FnStart,
939 MCSymbolRefExpr::VK_ARM_PREL31,
942 EmitValue(FnStartRef, 4);
945 EmitIntValue(EXIDX_CANTUNWIND, 4);
947 // Emit a reference to the unwind opcodes in the ".ARM.extab" section.
948 const MCSymbolRefExpr *ExTabEntryRef =
949 MCSymbolRefExpr::Create(ExTab,
950 MCSymbolRefExpr::VK_ARM_PREL31,
952 EmitValue(ExTabEntryRef, 4);
954 // For the __aeabi_unwind_cpp_pr0, we have to emit the unwind opcodes in
955 // the second word of exception index table entry. The size of the unwind
956 // opcodes should always be 4 bytes.
957 assert(PersonalityIndex == AEABI_UNWIND_CPP_PR0 &&
958 "Compact model must use __aeabi_cpp_unwind_pr0 as personality");
959 assert(Opcodes.size() == 4u &&
960 "Unwind opcode size for __aeabi_cpp_unwind_pr0 must be equal to 4");
961 EmitBytes(StringRef(reinterpret_cast<const char*>(Opcodes.data()),
965 // Switch to the section containing FnStart
966 SwitchSection(&FnStart->getSection());
968 // Clean exception handling frame information
972 void ARMELFStreamer::emitCantUnwind() { CantUnwind = true; }
974 // Add the R_ARM_NONE fixup at the same position
975 void ARMELFStreamer::EmitPersonalityFixup(StringRef Name) {
976 const MCSymbol *PersonalitySym = getContext().GetOrCreateSymbol(Name);
978 const MCSymbolRefExpr *PersonalityRef = MCSymbolRefExpr::Create(
979 PersonalitySym, MCSymbolRefExpr::VK_ARM_NONE, getContext());
981 AddValueSymbols(PersonalityRef);
982 MCDataFragment *DF = getOrCreateDataFragment();
983 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
985 MCFixup::getKindForSize(4, false)));
988 void ARMELFStreamer::FlushPendingOffset() {
989 if (PendingOffset != 0) {
990 UnwindOpAsm.EmitSPOffset(-PendingOffset);
995 void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) {
996 // Emit the unwind opcode to restore $sp.
998 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
999 int64_t LastRegSaveSPOffset = SPOffset - PendingOffset;
1000 UnwindOpAsm.EmitSPOffset(LastRegSaveSPOffset - FPOffset);
1001 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1003 FlushPendingOffset();
1006 // Finalize the unwind opcode sequence
1007 UnwindOpAsm.Finalize(PersonalityIndex, Opcodes);
1009 // For compact model 0, we have to emit the unwind opcodes in the .ARM.exidx
1010 // section. Thus, we don't have to create an entry in the .ARM.extab
1012 if (NoHandlerData && PersonalityIndex == AEABI_UNWIND_CPP_PR0)
1015 // Switch to .ARM.extab section.
1016 SwitchToExTabSection(*FnStart);
1018 // Create .ARM.extab label for offset in .ARM.exidx
1020 ExTab = getContext().CreateTempSymbol();
1025 const MCSymbolRefExpr *PersonalityRef =
1026 MCSymbolRefExpr::Create(Personality,
1027 MCSymbolRefExpr::VK_ARM_PREL31,
1030 EmitValue(PersonalityRef, 4);
1033 // Emit unwind opcodes
1034 EmitBytes(StringRef(reinterpret_cast<const char *>(Opcodes.data()),
1037 // According to ARM EHABI section 9.2, if the __aeabi_unwind_cpp_pr1() or
1038 // __aeabi_unwind_cpp_pr2() is used, then the handler data must be emitted
1039 // after the unwind opcodes. The handler data consists of several 32-bit
1040 // words, and should be terminated by zero.
1042 // In case that the .handlerdata directive is not specified by the
1043 // programmer, we should emit zero to terminate the handler data.
1044 if (NoHandlerData && !Personality)
1048 void ARMELFStreamer::emitHandlerData() { FlushUnwindOpcodes(false); }
1050 void ARMELFStreamer::emitPersonality(const MCSymbol *Per) {
1052 UnwindOpAsm.setPersonality(Per);
1055 void ARMELFStreamer::emitSetFP(unsigned NewFPReg, unsigned NewSPReg,
1057 assert((NewSPReg == ARM::SP || NewSPReg == FPReg) &&
1058 "the operand of .setfp directive should be either $sp or $fp");
1063 if (NewSPReg == ARM::SP)
1064 FPOffset = SPOffset + Offset;
1069 void ARMELFStreamer::emitPad(int64_t Offset) {
1070 // Track the change of the $sp offset
1073 // To squash multiple .pad directives, we should delay the unwind opcode
1074 // until the .save, .vsave, .handlerdata, or .fnend directives.
1075 PendingOffset -= Offset;
1078 void ARMELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
1080 // Collect the registers in the register list
1083 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1084 for (size_t i = 0; i < RegList.size(); ++i) {
1085 unsigned Reg = MRI->getEncodingValue(RegList[i]);
1086 assert(Reg < (IsVector ? 32U : 16U) && "Register out of range");
1087 unsigned Bit = (1u << Reg);
1088 if ((Mask & Bit) == 0) {
1094 // Track the change the $sp offset: For the .save directive, the
1095 // corresponding push instruction will decrease the $sp by (4 * Count).
1096 // For the .vsave directive, the corresponding vpush instruction will
1097 // decrease $sp by (8 * Count).
1098 SPOffset -= Count * (IsVector ? 8 : 4);
1101 FlushPendingOffset();
1103 UnwindOpAsm.EmitVFPRegSave(Mask);
1105 UnwindOpAsm.EmitRegSave(Mask);
1110 MCStreamer *createMCAsmStreamer(MCContext &Ctx, formatted_raw_ostream &OS,
1111 bool isVerboseAsm, bool useLoc, bool useCFI,
1112 bool useDwarfDirectory,
1113 MCInstPrinter *InstPrint, MCCodeEmitter *CE,
1114 MCAsmBackend *TAB, bool ShowInst) {
1115 ARMTargetAsmStreamer *S = new ARMTargetAsmStreamer(OS, *InstPrint);
1117 return llvm::createAsmStreamer(Ctx, S, OS, isVerboseAsm, useLoc, useCFI,
1118 useDwarfDirectory, InstPrint, CE, TAB,
1122 MCELFStreamer* createARMELFStreamer(MCContext &Context, MCAsmBackend &TAB,
1123 raw_ostream &OS, MCCodeEmitter *Emitter,
1124 bool RelaxAll, bool NoExecStack,
1126 ARMTargetELFStreamer *TS = new ARMTargetELFStreamer();
1128 new ARMELFStreamer(Context, TS, TAB, OS, Emitter, IsThumb);
1129 // FIXME: This should eventually end up somewhere else where more
1130 // intelligent flag decisions can be made. For now we are just maintaining
1131 // the status quo for ARM and setting EF_ARM_EABI_VER5 as the default.
1132 S->getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
1135 S->getAssembler().setRelaxAll(true);
1137 S->getAssembler().setNoExecStack(true);