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 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
75 #include "ARMArchName.def"
80 static const char *GetArchDefaultCPUName(unsigned ID) {
83 llvm_unreachable("Unknown ARCH kind");
85 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
86 case ARM::ID: return DEFAULT_CPU_NAME;
87 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
88 #include "ARMArchName.def"
93 static unsigned GetArchDefaultCPUArch(unsigned ID) {
96 llvm_unreachable("Unknown ARCH kind");
98 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
99 case ARM::ID: return ARMBuildAttrs::DEFAULT_CPU_ARCH;
100 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
101 #include "ARMArchName.def"
108 class ARMELFStreamer;
110 class ARMTargetAsmStreamer : public ARMTargetStreamer {
111 formatted_raw_ostream &OS;
112 MCInstPrinter &InstPrinter;
114 virtual void emitFnStart();
115 virtual void emitFnEnd();
116 virtual void emitCantUnwind();
117 virtual void emitPersonality(const MCSymbol *Personality);
118 virtual void emitHandlerData();
119 virtual void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
120 virtual void emitPad(int64_t Offset);
121 virtual void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
124 virtual void switchVendor(StringRef Vendor);
125 virtual void emitAttribute(unsigned Attribute, unsigned Value);
126 virtual void emitTextAttribute(unsigned Attribute, StringRef String);
127 virtual void emitArch(unsigned Arch);
128 virtual void emitFPU(unsigned FPU);
129 virtual void emitInst(uint32_t Inst, char Suffix = '\0');
130 virtual void finishAttributeSection();
133 ARMTargetAsmStreamer(formatted_raw_ostream &OS, MCInstPrinter &InstPrinter);
136 ARMTargetAsmStreamer::ARMTargetAsmStreamer(formatted_raw_ostream &OS,
137 MCInstPrinter &InstPrinter)
138 : OS(OS), InstPrinter(InstPrinter) {}
139 void ARMTargetAsmStreamer::emitFnStart() { OS << "\t.fnstart\n"; }
140 void ARMTargetAsmStreamer::emitFnEnd() { OS << "\t.fnend\n"; }
141 void ARMTargetAsmStreamer::emitCantUnwind() { OS << "\t.cantunwind\n"; }
142 void ARMTargetAsmStreamer::emitPersonality(const MCSymbol *Personality) {
143 OS << "\t.personality " << Personality->getName() << '\n';
145 void ARMTargetAsmStreamer::emitHandlerData() { OS << "\t.handlerdata\n"; }
146 void ARMTargetAsmStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
149 InstPrinter.printRegName(OS, FpReg);
151 InstPrinter.printRegName(OS, SpReg);
153 OS << ", #" << Offset;
156 void ARMTargetAsmStreamer::emitPad(int64_t Offset) {
157 OS << "\t.pad\t#" << Offset << '\n';
159 void ARMTargetAsmStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
161 assert(RegList.size() && "RegList should not be empty");
167 InstPrinter.printRegName(OS, RegList[0]);
169 for (unsigned i = 1, e = RegList.size(); i != e; ++i) {
171 InstPrinter.printRegName(OS, RegList[i]);
176 void ARMTargetAsmStreamer::switchVendor(StringRef Vendor) {
178 void ARMTargetAsmStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
179 OS << "\t.eabi_attribute\t" << Attribute << ", " << Twine(Value) << "\n";
181 void ARMTargetAsmStreamer::emitTextAttribute(unsigned Attribute,
184 default: llvm_unreachable("Unsupported Text attribute in ASM Mode");
185 case ARMBuildAttrs::CPU_name:
186 OS << "\t.cpu\t" << String.lower() << "\n";
190 void ARMTargetAsmStreamer::emitArch(unsigned Arch) {
191 OS << "\t.arch\t" << GetArchName(Arch) << "\n";
193 void ARMTargetAsmStreamer::emitFPU(unsigned FPU) {
194 OS << "\t.fpu\t" << GetFPUName(FPU) << "\n";
196 void ARMTargetAsmStreamer::finishAttributeSection() {
199 void ARMTargetAsmStreamer::emitInst(uint32_t Inst, char Suffix) {
203 OS << "\t0x" << utohexstr(Inst) << "\n";
206 class ARMTargetELFStreamer : public ARMTargetStreamer {
208 // This structure holds all attributes, accounting for
209 // their string/numeric value, so we can later emmit them
210 // in declaration order, keeping all in the same vector
211 struct AttributeItem {
219 StringRef StringValue;
221 static bool LessTag(const AttributeItem &LHS, const AttributeItem &RHS) {
222 return (LHS.Tag < RHS.Tag);
226 StringRef CurrentVendor;
229 SmallVector<AttributeItem, 64> Contents;
231 const MCSection *AttributeSection;
233 // FIXME: this should be in a more generic place, but
234 // getULEBSize() is in MCAsmInfo and will be moved to MCDwarf
235 static size_t getULEBSize(int Value) {
239 Size += sizeof(int8_t); // Is this really necessary?
244 AttributeItem *getAttributeItem(unsigned Attribute) {
245 for (size_t i = 0; i < Contents.size(); ++i)
246 if (Contents[i].Tag == Attribute)
251 void setAttributeItem(unsigned Attribute, unsigned Value,
252 bool OverwriteExisting) {
253 // Look for existing attribute item
254 if (AttributeItem *Item = getAttributeItem(Attribute)) {
255 if (!OverwriteExisting)
257 Item->IntValue = Value;
261 // Create new attribute item
262 AttributeItem Item = {
263 AttributeItem::NumericAttribute,
268 Contents.push_back(Item);
271 void setAttributeItem(unsigned Attribute, StringRef Value,
272 bool OverwriteExisting) {
273 // Look for existing attribute item
274 if (AttributeItem *Item = getAttributeItem(Attribute)) {
275 if (!OverwriteExisting)
277 Item->StringValue = Value;
281 // Create new attribute item
282 AttributeItem Item = {
283 AttributeItem::TextAttribute,
288 Contents.push_back(Item);
291 void emitArchDefaultAttributes();
292 void emitFPUDefaultAttributes();
294 ARMELFStreamer &getStreamer();
296 virtual void emitFnStart();
297 virtual void emitFnEnd();
298 virtual void emitCantUnwind();
299 virtual void emitPersonality(const MCSymbol *Personality);
300 virtual void emitHandlerData();
301 virtual void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
302 virtual void emitPad(int64_t Offset);
303 virtual void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
306 virtual void switchVendor(StringRef Vendor);
307 virtual void emitAttribute(unsigned Attribute, unsigned Value);
308 virtual void emitTextAttribute(unsigned Attribute, StringRef String);
309 virtual void emitArch(unsigned Arch);
310 virtual void emitFPU(unsigned FPU);
311 virtual void emitInst(uint32_t Inst, char Suffix = '\0');
312 virtual void finishAttributeSection();
314 size_t calculateContentSize() const;
317 ARMTargetELFStreamer()
318 : ARMTargetStreamer(), CurrentVendor("aeabi"), FPU(ARM::INVALID_FPU),
319 Arch(ARM::INVALID_ARCH), AttributeSection(0) {
323 /// Extend the generic ELFStreamer class so that it can emit mapping symbols at
324 /// the appropriate points in the object files. These symbols are defined in the
325 /// ARM ELF ABI: infocenter.arm.com/help/topic/com.arm.../IHI0044D_aaelf.pdf.
327 /// In brief: $a, $t or $d should be emitted at the start of each contiguous
328 /// region of ARM code, Thumb code or data in a section. In practice, this
329 /// emission does not rely on explicit assembler directives but on inherent
330 /// properties of the directives doing the emission (e.g. ".byte" is data, "add
331 /// r0, r0, r0" an instruction).
333 /// As a result this system is orthogonal to the DataRegion infrastructure used
334 /// by MachO. Beware!
335 class ARMELFStreamer : public MCELFStreamer {
337 friend class ARMTargetELFStreamer;
339 ARMELFStreamer(MCContext &Context, MCTargetStreamer *TargetStreamer,
340 MCAsmBackend &TAB, raw_ostream &OS, MCCodeEmitter *Emitter,
342 : MCELFStreamer(Context, TargetStreamer, TAB, OS, Emitter),
343 IsThumb(IsThumb), MappingSymbolCounter(0), LastEMS(EMS_None) {
349 virtual void FinishImpl();
351 // ARM exception handling directives
354 void emitCantUnwind();
355 void emitPersonality(const MCSymbol *Per);
356 void emitHandlerData();
357 void emitSetFP(unsigned NewFpReg, unsigned NewSpReg, int64_t Offset = 0);
358 void emitPad(int64_t Offset);
359 void emitRegSave(const SmallVectorImpl<unsigned> &RegList, bool isVector);
361 virtual void ChangeSection(const MCSection *Section,
362 const MCExpr *Subsection) {
363 // We have to keep track of the mapping symbol state of any sections we
364 // use. Each one should start off as EMS_None, which is provided as the
365 // default constructor by DenseMap::lookup.
366 LastMappingSymbols[getPreviousSection().first] = LastEMS;
367 LastEMS = LastMappingSymbols.lookup(Section);
369 MCELFStreamer::ChangeSection(Section, Subsection);
372 /// This function is the one used to emit instruction data into the ELF
373 /// streamer. We override it to add the appropriate mapping symbol if
375 virtual void EmitInstruction(const MCInst& Inst) {
377 EmitThumbMappingSymbol();
379 EmitARMMappingSymbol();
381 MCELFStreamer::EmitInstruction(Inst);
384 virtual void emitInst(uint32_t Inst, char Suffix) {
387 const bool LittleEndian = getContext().getAsmInfo()->isLittleEndian();
394 EmitARMMappingSymbol();
395 for (unsigned II = 0, IE = Size; II != IE; II++) {
396 const unsigned I = LittleEndian ? (Size - II - 1) : II;
397 Buffer[Size - II - 1] = uint8_t(Inst >> I * CHAR_BIT);
403 Size = (Suffix == 'n' ? 2 : 4);
406 EmitThumbMappingSymbol();
407 for (unsigned II = 0, IE = Size; II != IE; II = II + 2) {
408 const unsigned I0 = LittleEndian ? II + 0 : (Size - II - 1);
409 const unsigned I1 = LittleEndian ? II + 1 : (Size - II - 2);
410 Buffer[Size - II - 2] = uint8_t(Inst >> I0 * CHAR_BIT);
411 Buffer[Size - II - 1] = uint8_t(Inst >> I1 * CHAR_BIT);
416 llvm_unreachable("Invalid Suffix");
419 MCELFStreamer::EmitBytes(StringRef(Buffer, Size));
422 /// This is one of the functions used to emit data into an ELF section, so the
423 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
425 virtual void EmitBytes(StringRef Data) {
426 EmitDataMappingSymbol();
427 MCELFStreamer::EmitBytes(Data);
430 /// This is one of the functions used to emit data into an ELF section, so the
431 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
433 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {
434 EmitDataMappingSymbol();
435 MCELFStreamer::EmitValueImpl(Value, Size);
438 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {
439 MCELFStreamer::EmitAssemblerFlag(Flag);
442 case MCAF_SyntaxUnified:
443 return; // no-op here.
446 return; // Change to Thumb mode
449 return; // Change to ARM mode
452 case MCAF_SubsectionsViaSymbols:
458 enum ElfMappingSymbol {
465 void EmitDataMappingSymbol() {
466 if (LastEMS == EMS_Data) return;
467 EmitMappingSymbol("$d");
471 void EmitThumbMappingSymbol() {
472 if (LastEMS == EMS_Thumb) return;
473 EmitMappingSymbol("$t");
477 void EmitARMMappingSymbol() {
478 if (LastEMS == EMS_ARM) return;
479 EmitMappingSymbol("$a");
483 void EmitMappingSymbol(StringRef Name) {
484 MCSymbol *Start = getContext().CreateTempSymbol();
488 getContext().GetOrCreateSymbol(Name + "." +
489 Twine(MappingSymbolCounter++));
491 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
492 MCELF::SetType(SD, ELF::STT_NOTYPE);
493 MCELF::SetBinding(SD, ELF::STB_LOCAL);
494 SD.setExternal(false);
495 AssignSection(Symbol, getCurrentSection().first);
497 const MCExpr *Value = MCSymbolRefExpr::Create(Start, getContext());
498 Symbol->setVariableValue(Value);
501 void EmitThumbFunc(MCSymbol *Func) {
502 // FIXME: Anything needed here to flag the function as thumb?
504 getAssembler().setIsThumbFunc(Func);
506 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Func);
507 SD.setFlags(SD.getFlags() | ELF_Other_ThumbFunc);
510 // Helper functions for ARM exception handling directives
513 void EmitPersonalityFixup(StringRef Name);
514 void FlushPendingOffset();
515 void FlushUnwindOpcodes(bool NoHandlerData);
517 void SwitchToEHSection(const char *Prefix, unsigned Type, unsigned Flags,
518 SectionKind Kind, const MCSymbol &Fn);
519 void SwitchToExTabSection(const MCSymbol &FnStart);
520 void SwitchToExIdxSection(const MCSymbol &FnStart);
523 int64_t MappingSymbolCounter;
525 DenseMap<const MCSection *, ElfMappingSymbol> LastMappingSymbols;
526 ElfMappingSymbol LastEMS;
528 // ARM Exception Handling Frame Information
531 const MCSymbol *Personality;
532 unsigned PersonalityIndex;
533 unsigned FPReg; // Frame pointer register
534 int64_t FPOffset; // Offset: (final frame pointer) - (initial $sp)
535 int64_t SPOffset; // Offset: (final $sp) - (initial $sp)
536 int64_t PendingOffset; // Offset: (final $sp) - (emitted $sp)
539 SmallVector<uint8_t, 64> Opcodes;
540 UnwindOpcodeAssembler UnwindOpAsm;
542 } // end anonymous namespace
544 ARMELFStreamer &ARMTargetELFStreamer::getStreamer() {
545 ARMELFStreamer *S = static_cast<ARMELFStreamer *>(Streamer);
549 void ARMTargetELFStreamer::emitFnStart() { getStreamer().emitFnStart(); }
550 void ARMTargetELFStreamer::emitFnEnd() { getStreamer().emitFnEnd(); }
551 void ARMTargetELFStreamer::emitCantUnwind() { getStreamer().emitCantUnwind(); }
552 void ARMTargetELFStreamer::emitPersonality(const MCSymbol *Personality) {
553 getStreamer().emitPersonality(Personality);
555 void ARMTargetELFStreamer::emitHandlerData() {
556 getStreamer().emitHandlerData();
558 void ARMTargetELFStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
560 getStreamer().emitSetFP(FpReg, SpReg, Offset);
562 void ARMTargetELFStreamer::emitPad(int64_t Offset) {
563 getStreamer().emitPad(Offset);
565 void ARMTargetELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
567 getStreamer().emitRegSave(RegList, isVector);
569 void ARMTargetELFStreamer::switchVendor(StringRef Vendor) {
570 assert(!Vendor.empty() && "Vendor cannot be empty.");
572 if (CurrentVendor == Vendor)
575 if (!CurrentVendor.empty())
576 finishAttributeSection();
578 assert(Contents.empty() &&
579 ".ARM.attributes should be flushed before changing vendor");
580 CurrentVendor = Vendor;
583 void ARMTargetELFStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
584 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
586 void ARMTargetELFStreamer::emitTextAttribute(unsigned Attribute,
588 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
590 void ARMTargetELFStreamer::emitArch(unsigned Value) {
593 void ARMTargetELFStreamer::emitArchDefaultAttributes() {
594 using namespace ARMBuildAttrs;
595 setAttributeItem(CPU_name, GetArchDefaultCPUName(Arch), false);
596 setAttributeItem(CPU_arch, GetArchDefaultCPUArch(Arch), false);
605 setAttributeItem(ARM_ISA_use, Allowed, false);
613 setAttributeItem(ARM_ISA_use, Allowed, false);
614 setAttributeItem(THUMB_ISA_use, Allowed, false);
618 setAttributeItem(ARM_ISA_use, Allowed, false);
619 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
624 setAttributeItem(ARM_ISA_use, Allowed, false);
625 setAttributeItem(THUMB_ISA_use, Allowed, false);
626 setAttributeItem(Virtualization_use, AllowTZ, false);
630 setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
631 setAttributeItem(THUMB_ISA_use, Allowed, false);
635 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
639 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
640 setAttributeItem(ARM_ISA_use, Allowed, false);
641 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
645 setAttributeItem(CPU_arch_profile, RealTimeProfile, false);
646 setAttributeItem(ARM_ISA_use, Allowed, false);
647 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
651 setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
652 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
656 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
657 setAttributeItem(ARM_ISA_use, Allowed, false);
658 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
659 setAttributeItem(MPextension_use, Allowed, false);
660 setAttributeItem(Virtualization_use, AllowTZVirtualization, false);
664 setAttributeItem(ARM_ISA_use, Allowed, false);
665 setAttributeItem(THUMB_ISA_use, Allowed, false);
666 setAttributeItem(WMMX_arch, AllowWMMXv1, false);
670 setAttributeItem(ARM_ISA_use, Allowed, false);
671 setAttributeItem(THUMB_ISA_use, Allowed, false);
672 setAttributeItem(WMMX_arch, AllowWMMXv2, false);
676 report_fatal_error("Unknown Arch: " + Twine(Arch));
680 void ARMTargetELFStreamer::emitFPU(unsigned Value) {
683 void ARMTargetELFStreamer::emitFPUDefaultAttributes() {
687 setAttributeItem(ARMBuildAttrs::FP_arch,
688 ARMBuildAttrs::AllowFPv2,
689 /* OverwriteExisting= */ false);
693 setAttributeItem(ARMBuildAttrs::FP_arch,
694 ARMBuildAttrs::AllowFPv3A,
695 /* OverwriteExisting= */ false);
699 setAttributeItem(ARMBuildAttrs::FP_arch,
700 ARMBuildAttrs::AllowFPv3B,
701 /* OverwriteExisting= */ false);
705 setAttributeItem(ARMBuildAttrs::FP_arch,
706 ARMBuildAttrs::AllowFPv4A,
707 /* OverwriteExisting= */ false);
711 setAttributeItem(ARMBuildAttrs::FP_arch,
712 ARMBuildAttrs::AllowFPv4B,
713 /* OverwriteExisting= */ false);
717 setAttributeItem(ARMBuildAttrs::FP_arch,
718 ARMBuildAttrs::AllowFPARMv8A,
719 /* OverwriteExisting= */ false);
723 setAttributeItem(ARMBuildAttrs::FP_arch,
724 ARMBuildAttrs::AllowFPv3A,
725 /* OverwriteExisting= */ false);
726 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
727 ARMBuildAttrs::AllowNeon,
728 /* OverwriteExisting= */ false);
731 case ARM::NEON_VFPV4:
732 setAttributeItem(ARMBuildAttrs::FP_arch,
733 ARMBuildAttrs::AllowFPv4A,
734 /* OverwriteExisting= */ false);
735 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
736 ARMBuildAttrs::AllowNeon2,
737 /* OverwriteExisting= */ false);
740 case ARM::NEON_FP_ARMV8:
741 case ARM::CRYPTO_NEON_FP_ARMV8:
742 setAttributeItem(ARMBuildAttrs::FP_arch,
743 ARMBuildAttrs::AllowFPARMv8A,
744 /* OverwriteExisting= */ false);
745 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
746 ARMBuildAttrs::AllowNeonARMv8,
747 /* OverwriteExisting= */ false);
751 report_fatal_error("Unknown FPU: " + Twine(FPU));
755 size_t ARMTargetELFStreamer::calculateContentSize() const {
757 for (size_t i = 0; i < Contents.size(); ++i) {
758 AttributeItem item = Contents[i];
760 case AttributeItem::HiddenAttribute:
762 case AttributeItem::NumericAttribute:
763 Result += getULEBSize(item.Tag);
764 Result += getULEBSize(item.IntValue);
766 case AttributeItem::TextAttribute:
767 Result += getULEBSize(item.Tag);
768 Result += item.StringValue.size() + 1; // string + '\0'
774 void ARMTargetELFStreamer::finishAttributeSection() {
776 // [ <section-length> "vendor-name"
777 // [ <file-tag> <size> <attribute>*
778 // | <section-tag> <size> <section-number>* 0 <attribute>*
779 // | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
783 if (FPU != ARM::INVALID_FPU)
784 emitFPUDefaultAttributes();
786 if (Arch != ARM::INVALID_ARCH)
787 emitArchDefaultAttributes();
789 if (Contents.empty())
792 std::sort(Contents.begin(), Contents.end(), AttributeItem::LessTag);
794 ARMELFStreamer &Streamer = getStreamer();
796 // Switch to .ARM.attributes section
797 if (AttributeSection) {
798 Streamer.SwitchSection(AttributeSection);
801 Streamer.getContext().getELFSection(".ARM.attributes",
802 ELF::SHT_ARM_ATTRIBUTES,
804 SectionKind::getMetadata());
805 Streamer.SwitchSection(AttributeSection);
808 Streamer.EmitIntValue(0x41, 1);
811 // Vendor size + Vendor name + '\0'
812 const size_t VendorHeaderSize = 4 + CurrentVendor.size() + 1;
815 const size_t TagHeaderSize = 1 + 4;
817 const size_t ContentsSize = calculateContentSize();
819 Streamer.EmitIntValue(VendorHeaderSize + TagHeaderSize + ContentsSize, 4);
820 Streamer.EmitBytes(CurrentVendor);
821 Streamer.EmitIntValue(0, 1); // '\0'
823 Streamer.EmitIntValue(ARMBuildAttrs::File, 1);
824 Streamer.EmitIntValue(TagHeaderSize + ContentsSize, 4);
826 // Size should have been accounted for already, now
827 // emit each field as its type (ULEB or String)
828 for (size_t i = 0; i < Contents.size(); ++i) {
829 AttributeItem item = Contents[i];
830 Streamer.EmitULEB128IntValue(item.Tag);
832 default: llvm_unreachable("Invalid attribute type");
833 case AttributeItem::NumericAttribute:
834 Streamer.EmitULEB128IntValue(item.IntValue);
836 case AttributeItem::TextAttribute:
837 Streamer.EmitBytes(item.StringValue.upper());
838 Streamer.EmitIntValue(0, 1); // '\0'
844 FPU = ARM::INVALID_FPU;
846 void ARMTargetELFStreamer::emitInst(uint32_t Inst, char Suffix) {
847 getStreamer().emitInst(Inst, Suffix);
850 void ARMELFStreamer::FinishImpl() {
851 MCTargetStreamer &TS = getTargetStreamer();
852 ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
853 ATS.finishAttributeSection();
855 MCELFStreamer::FinishImpl();
858 inline void ARMELFStreamer::SwitchToEHSection(const char *Prefix,
862 const MCSymbol &Fn) {
863 const MCSectionELF &FnSection =
864 static_cast<const MCSectionELF &>(Fn.getSection());
866 // Create the name for new section
867 StringRef FnSecName(FnSection.getSectionName());
868 SmallString<128> EHSecName(Prefix);
869 if (FnSecName != ".text") {
870 EHSecName += FnSecName;
873 // Get .ARM.extab or .ARM.exidx section
874 const MCSectionELF *EHSection = NULL;
875 if (const MCSymbol *Group = FnSection.getGroup()) {
876 EHSection = getContext().getELFSection(
877 EHSecName, Type, Flags | ELF::SHF_GROUP, Kind,
878 FnSection.getEntrySize(), Group->getName());
880 EHSection = getContext().getELFSection(EHSecName, Type, Flags, Kind);
882 assert(EHSection && "Failed to get the required EH section");
884 // Switch to .ARM.extab or .ARM.exidx section
885 SwitchSection(EHSection);
886 EmitCodeAlignment(4, 0);
889 inline void ARMELFStreamer::SwitchToExTabSection(const MCSymbol &FnStart) {
890 SwitchToEHSection(".ARM.extab",
893 SectionKind::getDataRel(),
897 inline void ARMELFStreamer::SwitchToExIdxSection(const MCSymbol &FnStart) {
898 SwitchToEHSection(".ARM.exidx",
900 ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER,
901 SectionKind::getDataRel(),
905 void ARMELFStreamer::Reset() {
909 PersonalityIndex = NUM_PERSONALITY_INDEX;
921 void ARMELFStreamer::emitFnStart() {
922 assert(FnStart == 0);
923 FnStart = getContext().CreateTempSymbol();
927 void ARMELFStreamer::emitFnEnd() {
928 assert(FnStart && ".fnstart must preceeds .fnend");
930 // Emit unwind opcodes if there is no .handlerdata directive
931 if (!ExTab && !CantUnwind)
932 FlushUnwindOpcodes(true);
934 // Emit the exception index table entry
935 SwitchToExIdxSection(*FnStart);
937 if (PersonalityIndex < NUM_PERSONALITY_INDEX)
938 EmitPersonalityFixup(GetAEABIUnwindPersonalityName(PersonalityIndex));
940 const MCSymbolRefExpr *FnStartRef =
941 MCSymbolRefExpr::Create(FnStart,
942 MCSymbolRefExpr::VK_ARM_PREL31,
945 EmitValue(FnStartRef, 4);
948 EmitIntValue(EXIDX_CANTUNWIND, 4);
950 // Emit a reference to the unwind opcodes in the ".ARM.extab" section.
951 const MCSymbolRefExpr *ExTabEntryRef =
952 MCSymbolRefExpr::Create(ExTab,
953 MCSymbolRefExpr::VK_ARM_PREL31,
955 EmitValue(ExTabEntryRef, 4);
957 // For the __aeabi_unwind_cpp_pr0, we have to emit the unwind opcodes in
958 // the second word of exception index table entry. The size of the unwind
959 // opcodes should always be 4 bytes.
960 assert(PersonalityIndex == AEABI_UNWIND_CPP_PR0 &&
961 "Compact model must use __aeabi_cpp_unwind_pr0 as personality");
962 assert(Opcodes.size() == 4u &&
963 "Unwind opcode size for __aeabi_cpp_unwind_pr0 must be equal to 4");
964 EmitBytes(StringRef(reinterpret_cast<const char*>(Opcodes.data()),
968 // Switch to the section containing FnStart
969 SwitchSection(&FnStart->getSection());
971 // Clean exception handling frame information
975 void ARMELFStreamer::emitCantUnwind() { CantUnwind = true; }
977 // Add the R_ARM_NONE fixup at the same position
978 void ARMELFStreamer::EmitPersonalityFixup(StringRef Name) {
979 const MCSymbol *PersonalitySym = getContext().GetOrCreateSymbol(Name);
981 const MCSymbolRefExpr *PersonalityRef = MCSymbolRefExpr::Create(
982 PersonalitySym, MCSymbolRefExpr::VK_ARM_NONE, getContext());
984 AddValueSymbols(PersonalityRef);
985 MCDataFragment *DF = getOrCreateDataFragment();
986 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
988 MCFixup::getKindForSize(4, false)));
991 void ARMELFStreamer::FlushPendingOffset() {
992 if (PendingOffset != 0) {
993 UnwindOpAsm.EmitSPOffset(-PendingOffset);
998 void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) {
999 // Emit the unwind opcode to restore $sp.
1001 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1002 int64_t LastRegSaveSPOffset = SPOffset - PendingOffset;
1003 UnwindOpAsm.EmitSPOffset(LastRegSaveSPOffset - FPOffset);
1004 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1006 FlushPendingOffset();
1009 // Finalize the unwind opcode sequence
1010 UnwindOpAsm.Finalize(PersonalityIndex, Opcodes);
1012 // For compact model 0, we have to emit the unwind opcodes in the .ARM.exidx
1013 // section. Thus, we don't have to create an entry in the .ARM.extab
1015 if (NoHandlerData && PersonalityIndex == AEABI_UNWIND_CPP_PR0)
1018 // Switch to .ARM.extab section.
1019 SwitchToExTabSection(*FnStart);
1021 // Create .ARM.extab label for offset in .ARM.exidx
1023 ExTab = getContext().CreateTempSymbol();
1028 const MCSymbolRefExpr *PersonalityRef =
1029 MCSymbolRefExpr::Create(Personality,
1030 MCSymbolRefExpr::VK_ARM_PREL31,
1033 EmitValue(PersonalityRef, 4);
1036 // Emit unwind opcodes
1037 EmitBytes(StringRef(reinterpret_cast<const char *>(Opcodes.data()),
1040 // According to ARM EHABI section 9.2, if the __aeabi_unwind_cpp_pr1() or
1041 // __aeabi_unwind_cpp_pr2() is used, then the handler data must be emitted
1042 // after the unwind opcodes. The handler data consists of several 32-bit
1043 // words, and should be terminated by zero.
1045 // In case that the .handlerdata directive is not specified by the
1046 // programmer, we should emit zero to terminate the handler data.
1047 if (NoHandlerData && !Personality)
1051 void ARMELFStreamer::emitHandlerData() { FlushUnwindOpcodes(false); }
1053 void ARMELFStreamer::emitPersonality(const MCSymbol *Per) {
1055 UnwindOpAsm.setPersonality(Per);
1058 void ARMELFStreamer::emitSetFP(unsigned NewFPReg, unsigned NewSPReg,
1060 assert((NewSPReg == ARM::SP || NewSPReg == FPReg) &&
1061 "the operand of .setfp directive should be either $sp or $fp");
1066 if (NewSPReg == ARM::SP)
1067 FPOffset = SPOffset + Offset;
1072 void ARMELFStreamer::emitPad(int64_t Offset) {
1073 // Track the change of the $sp offset
1076 // To squash multiple .pad directives, we should delay the unwind opcode
1077 // until the .save, .vsave, .handlerdata, or .fnend directives.
1078 PendingOffset -= Offset;
1081 void ARMELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
1083 // Collect the registers in the register list
1086 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1087 for (size_t i = 0; i < RegList.size(); ++i) {
1088 unsigned Reg = MRI->getEncodingValue(RegList[i]);
1089 assert(Reg < (IsVector ? 32U : 16U) && "Register out of range");
1090 unsigned Bit = (1u << Reg);
1091 if ((Mask & Bit) == 0) {
1097 // Track the change the $sp offset: For the .save directive, the
1098 // corresponding push instruction will decrease the $sp by (4 * Count).
1099 // For the .vsave directive, the corresponding vpush instruction will
1100 // decrease $sp by (8 * Count).
1101 SPOffset -= Count * (IsVector ? 8 : 4);
1104 FlushPendingOffset();
1106 UnwindOpAsm.EmitVFPRegSave(Mask);
1108 UnwindOpAsm.EmitRegSave(Mask);
1113 MCStreamer *createMCAsmStreamer(MCContext &Ctx, formatted_raw_ostream &OS,
1114 bool isVerboseAsm, bool useLoc, bool useCFI,
1115 bool useDwarfDirectory,
1116 MCInstPrinter *InstPrint, MCCodeEmitter *CE,
1117 MCAsmBackend *TAB, bool ShowInst) {
1118 ARMTargetAsmStreamer *S = new ARMTargetAsmStreamer(OS, *InstPrint);
1120 return llvm::createAsmStreamer(Ctx, S, OS, isVerboseAsm, useLoc, useCFI,
1121 useDwarfDirectory, InstPrint, CE, TAB,
1125 MCELFStreamer* createARMELFStreamer(MCContext &Context, MCAsmBackend &TAB,
1126 raw_ostream &OS, MCCodeEmitter *Emitter,
1127 bool RelaxAll, bool NoExecStack,
1129 ARMTargetELFStreamer *TS = new ARMTargetELFStreamer();
1131 new ARMELFStreamer(Context, TS, TAB, OS, Emitter, IsThumb);
1132 // FIXME: This should eventually end up somewhere else where more
1133 // intelligent flag decisions can be made. For now we are just maintaining
1134 // the status quo for ARM and setting EF_ARM_EABI_VER5 as the default.
1135 S->getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
1138 S->getAssembler().setRelaxAll(true);
1140 S->getAssembler().setNoExecStack(true);