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 "ARMArchName.h"
17 #include "ARMFPUName.h"
18 #include "ARMRegisterInfo.h"
19 #include "ARMUnwindOpAsm.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/MC/MCAsmBackend.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCAssembler.h"
25 #include "llvm/MC/MCCodeEmitter.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCELF.h"
28 #include "llvm/MC/MCELFStreamer.h"
29 #include "llvm/MC/MCELFSymbolFlags.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCInstPrinter.h"
33 #include "llvm/MC/MCObjectFileInfo.h"
34 #include "llvm/MC/MCObjectStreamer.h"
35 #include "llvm/MC/MCRegisterInfo.h"
36 #include "llvm/MC/MCSection.h"
37 #include "llvm/MC/MCSectionELF.h"
38 #include "llvm/MC/MCStreamer.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/MC/MCValue.h"
41 #include "llvm/Support/ARMBuildAttributes.h"
42 #include "llvm/Support/ARMEHABI.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ELF.h"
45 #include "llvm/Support/FormattedStream.h"
46 #include "llvm/Support/LEB128.h"
47 #include "llvm/Support/raw_ostream.h"
52 static std::string GetAEABIUnwindPersonalityName(unsigned Index) {
53 assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX &&
54 "Invalid personality index");
55 return (Twine("__aeabi_unwind_cpp_pr") + Twine(Index)).str();
58 static const char *GetFPUName(unsigned ID) {
61 llvm_unreachable("Unknown FPU kind");
63 #define ARM_FPU_NAME(NAME, ID) case ARM::ID: return NAME;
64 #include "ARMFPUName.def"
69 static const char *GetArchName(unsigned ID) {
72 llvm_unreachable("Unknown ARCH kind");
74 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
75 case ARM::ID: return NAME;
76 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
77 #include "ARMArchName.def"
82 static const char *GetArchDefaultCPUName(unsigned ID) {
85 llvm_unreachable("Unknown ARCH kind");
87 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
88 case ARM::ID: return DEFAULT_CPU_NAME;
89 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
90 #include "ARMArchName.def"
95 static unsigned GetArchDefaultCPUArch(unsigned ID) {
98 llvm_unreachable("Unknown ARCH kind");
100 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
101 case ARM::ID: return ARMBuildAttrs::DEFAULT_CPU_ARCH;
102 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
103 #include "ARMArchName.def"
110 class ARMELFStreamer;
112 class ARMTargetAsmStreamer : public ARMTargetStreamer {
113 formatted_raw_ostream &OS;
114 MCInstPrinter &InstPrinter;
117 void emitFnStart() override;
118 void emitFnEnd() override;
119 void emitCantUnwind() override;
120 void emitPersonality(const MCSymbol *Personality) override;
121 void emitPersonalityIndex(unsigned Index) override;
122 void emitHandlerData() override;
123 void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
124 void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
125 void emitPad(int64_t Offset) override;
126 void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
127 bool isVector) override;
128 void emitUnwindRaw(int64_t Offset,
129 const SmallVectorImpl<uint8_t> &Opcodes) override;
131 void switchVendor(StringRef Vendor) override;
132 void emitAttribute(unsigned Attribute, unsigned Value) override;
133 void emitTextAttribute(unsigned Attribute, StringRef String) override;
134 void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
135 StringRef StrinValue) override;
136 void emitArch(unsigned Arch) override;
137 void emitObjectArch(unsigned Arch) override;
138 void emitFPU(unsigned FPU) override;
139 void emitInst(uint32_t Inst, char Suffix = '\0') override;
140 void finishAttributeSection() override;
142 void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
143 void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
146 ARMTargetAsmStreamer(MCStreamer &S, formatted_raw_ostream &OS,
147 MCInstPrinter &InstPrinter, bool VerboseAsm);
150 ARMTargetAsmStreamer::ARMTargetAsmStreamer(MCStreamer &S,
151 formatted_raw_ostream &OS,
152 MCInstPrinter &InstPrinter,
154 : ARMTargetStreamer(S), OS(OS), InstPrinter(InstPrinter),
155 IsVerboseAsm(VerboseAsm) {}
156 void ARMTargetAsmStreamer::emitFnStart() { OS << "\t.fnstart\n"; }
157 void ARMTargetAsmStreamer::emitFnEnd() { OS << "\t.fnend\n"; }
158 void ARMTargetAsmStreamer::emitCantUnwind() { OS << "\t.cantunwind\n"; }
159 void ARMTargetAsmStreamer::emitPersonality(const MCSymbol *Personality) {
160 OS << "\t.personality " << Personality->getName() << '\n';
162 void ARMTargetAsmStreamer::emitPersonalityIndex(unsigned Index) {
163 OS << "\t.personalityindex " << Index << '\n';
165 void ARMTargetAsmStreamer::emitHandlerData() { OS << "\t.handlerdata\n"; }
166 void ARMTargetAsmStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
169 InstPrinter.printRegName(OS, FpReg);
171 InstPrinter.printRegName(OS, SpReg);
173 OS << ", #" << Offset;
176 void ARMTargetAsmStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
177 assert((Reg != ARM::SP && Reg != ARM::PC) &&
178 "the operand of .movsp cannot be either sp or pc");
181 InstPrinter.printRegName(OS, Reg);
183 OS << ", #" << Offset;
186 void ARMTargetAsmStreamer::emitPad(int64_t Offset) {
187 OS << "\t.pad\t#" << Offset << '\n';
189 void ARMTargetAsmStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
191 assert(RegList.size() && "RegList should not be empty");
197 InstPrinter.printRegName(OS, RegList[0]);
199 for (unsigned i = 1, e = RegList.size(); i != e; ++i) {
201 InstPrinter.printRegName(OS, RegList[i]);
206 void ARMTargetAsmStreamer::switchVendor(StringRef Vendor) {
208 void ARMTargetAsmStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
209 OS << "\t.eabi_attribute\t" << Attribute << ", " << Twine(Value);
211 StringRef Name = ARMBuildAttrs::AttrTypeAsString(Attribute);
213 OS << "\t@ " << Name;
217 void ARMTargetAsmStreamer::emitTextAttribute(unsigned Attribute,
220 case ARMBuildAttrs::CPU_name:
221 OS << "\t.cpu\t" << String.lower();
224 OS << "\t.eabi_attribute\t" << Attribute << ", \"" << String << "\"";
226 StringRef Name = ARMBuildAttrs::AttrTypeAsString(Attribute);
228 OS << "\t@ " << Name;
234 void ARMTargetAsmStreamer::emitIntTextAttribute(unsigned Attribute,
236 StringRef StringValue) {
238 default: llvm_unreachable("unsupported multi-value attribute in asm mode");
239 case ARMBuildAttrs::compatibility:
240 OS << "\t.eabi_attribute\t" << Attribute << ", " << IntValue;
241 if (!StringValue.empty())
242 OS << ", \"" << StringValue << "\"";
244 OS << "\t@ " << ARMBuildAttrs::AttrTypeAsString(Attribute);
249 void ARMTargetAsmStreamer::emitArch(unsigned Arch) {
250 OS << "\t.arch\t" << GetArchName(Arch) << "\n";
252 void ARMTargetAsmStreamer::emitObjectArch(unsigned Arch) {
253 OS << "\t.object_arch\t" << GetArchName(Arch) << '\n';
255 void ARMTargetAsmStreamer::emitFPU(unsigned FPU) {
256 OS << "\t.fpu\t" << GetFPUName(FPU) << "\n";
258 void ARMTargetAsmStreamer::finishAttributeSection() {
261 ARMTargetAsmStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
262 OS << "\t.tlsdescseq\t" << S->getSymbol().getName();
265 void ARMTargetAsmStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
266 OS << "\t.thumb_set\t" << *Symbol << ", " << *Value << '\n';
269 void ARMTargetAsmStreamer::emitInst(uint32_t Inst, char Suffix) {
273 OS << "\t0x" << utohexstr(Inst) << "\n";
276 void ARMTargetAsmStreamer::emitUnwindRaw(int64_t Offset,
277 const SmallVectorImpl<uint8_t> &Opcodes) {
278 OS << "\t.unwind_raw " << Offset;
279 for (SmallVectorImpl<uint8_t>::const_iterator OCI = Opcodes.begin(),
282 OS << ", 0x" << utohexstr(*OCI);
286 class ARMTargetELFStreamer : public ARMTargetStreamer {
288 // This structure holds all attributes, accounting for
289 // their string/numeric value, so we can later emmit them
290 // in declaration order, keeping all in the same vector
291 struct AttributeItem {
296 NumericAndTextAttributes
300 StringRef StringValue;
302 static bool LessTag(const AttributeItem &LHS, const AttributeItem &RHS) {
303 // The conformance tag must be emitted first when serialised
304 // into an object file. Specifically, the addenda to the ARM ABI
305 // states that (2.3.7.4):
307 // "To simplify recognition by consumers in the common case of
308 // claiming conformity for the whole file, this tag should be
309 // emitted first in a file-scope sub-subsection of the first
310 // public subsection of the attributes section."
312 // So it is special-cased in this comparison predicate when the
313 // attributes are sorted in finishAttributeSection().
314 return (RHS.Tag != ARMBuildAttrs::conformance) &&
315 ((LHS.Tag == ARMBuildAttrs::conformance) || (LHS.Tag < RHS.Tag));
319 StringRef CurrentVendor;
322 unsigned EmittedArch;
323 SmallVector<AttributeItem, 64> Contents;
325 const MCSection *AttributeSection;
327 AttributeItem *getAttributeItem(unsigned Attribute) {
328 for (size_t i = 0; i < Contents.size(); ++i)
329 if (Contents[i].Tag == Attribute)
334 void setAttributeItem(unsigned Attribute, unsigned Value,
335 bool OverwriteExisting) {
336 // Look for existing attribute item
337 if (AttributeItem *Item = getAttributeItem(Attribute)) {
338 if (!OverwriteExisting)
340 Item->Type = AttributeItem::NumericAttribute;
341 Item->IntValue = Value;
345 // Create new attribute item
346 AttributeItem Item = {
347 AttributeItem::NumericAttribute,
352 Contents.push_back(Item);
355 void setAttributeItem(unsigned Attribute, StringRef Value,
356 bool OverwriteExisting) {
357 // Look for existing attribute item
358 if (AttributeItem *Item = getAttributeItem(Attribute)) {
359 if (!OverwriteExisting)
361 Item->Type = AttributeItem::TextAttribute;
362 Item->StringValue = Value;
366 // Create new attribute item
367 AttributeItem Item = {
368 AttributeItem::TextAttribute,
373 Contents.push_back(Item);
376 void setAttributeItems(unsigned Attribute, unsigned IntValue,
377 StringRef StringValue, bool OverwriteExisting) {
378 // Look for existing attribute item
379 if (AttributeItem *Item = getAttributeItem(Attribute)) {
380 if (!OverwriteExisting)
382 Item->Type = AttributeItem::NumericAndTextAttributes;
383 Item->IntValue = IntValue;
384 Item->StringValue = StringValue;
388 // Create new attribute item
389 AttributeItem Item = {
390 AttributeItem::NumericAndTextAttributes,
395 Contents.push_back(Item);
398 void emitArchDefaultAttributes();
399 void emitFPUDefaultAttributes();
401 ARMELFStreamer &getStreamer();
403 void emitFnStart() override;
404 void emitFnEnd() override;
405 void emitCantUnwind() override;
406 void emitPersonality(const MCSymbol *Personality) override;
407 void emitPersonalityIndex(unsigned Index) override;
408 void emitHandlerData() override;
409 void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
410 void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
411 void emitPad(int64_t Offset) override;
412 void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
413 bool isVector) override;
414 void emitUnwindRaw(int64_t Offset,
415 const SmallVectorImpl<uint8_t> &Opcodes) override;
417 void switchVendor(StringRef Vendor) override;
418 void emitAttribute(unsigned Attribute, unsigned Value) override;
419 void emitTextAttribute(unsigned Attribute, StringRef String) override;
420 void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
421 StringRef StringValue) override;
422 void emitArch(unsigned Arch) override;
423 void emitObjectArch(unsigned Arch) override;
424 void emitFPU(unsigned FPU) override;
425 void emitInst(uint32_t Inst, char Suffix = '\0') override;
426 void finishAttributeSection() override;
427 void emitLabel(MCSymbol *Symbol) override;
429 void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
430 void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
432 size_t calculateContentSize() const;
435 ARMTargetELFStreamer(MCStreamer &S)
436 : ARMTargetStreamer(S), CurrentVendor("aeabi"), FPU(ARM::INVALID_FPU),
437 Arch(ARM::INVALID_ARCH), EmittedArch(ARM::INVALID_ARCH),
438 AttributeSection(nullptr) {}
441 /// Extend the generic ELFStreamer class so that it can emit mapping symbols at
442 /// the appropriate points in the object files. These symbols are defined in the
443 /// ARM ELF ABI: infocenter.arm.com/help/topic/com.arm.../IHI0044D_aaelf.pdf.
445 /// In brief: $a, $t or $d should be emitted at the start of each contiguous
446 /// region of ARM code, Thumb code or data in a section. In practice, this
447 /// emission does not rely on explicit assembler directives but on inherent
448 /// properties of the directives doing the emission (e.g. ".byte" is data, "add
449 /// r0, r0, r0" an instruction).
451 /// As a result this system is orthogonal to the DataRegion infrastructure used
452 /// by MachO. Beware!
453 class ARMELFStreamer : public MCELFStreamer {
455 friend class ARMTargetELFStreamer;
457 ARMELFStreamer(MCContext &Context, MCAsmBackend &TAB, raw_ostream &OS,
458 MCCodeEmitter *Emitter, bool IsThumb)
459 : MCELFStreamer(Context, TAB, OS, Emitter), IsThumb(IsThumb),
460 MappingSymbolCounter(0), LastEMS(EMS_None) {
466 void FinishImpl() override;
468 // ARM exception handling directives
471 void emitCantUnwind();
472 void emitPersonality(const MCSymbol *Per);
473 void emitPersonalityIndex(unsigned index);
474 void emitHandlerData();
475 void emitSetFP(unsigned NewFpReg, unsigned NewSpReg, int64_t Offset = 0);
476 void emitMovSP(unsigned Reg, int64_t Offset = 0);
477 void emitPad(int64_t Offset);
478 void emitRegSave(const SmallVectorImpl<unsigned> &RegList, bool isVector);
479 void emitUnwindRaw(int64_t Offset, const SmallVectorImpl<uint8_t> &Opcodes);
481 void ChangeSection(const MCSection *Section,
482 const MCExpr *Subsection) override {
483 // We have to keep track of the mapping symbol state of any sections we
484 // use. Each one should start off as EMS_None, which is provided as the
485 // default constructor by DenseMap::lookup.
486 LastMappingSymbols[getPreviousSection().first] = LastEMS;
487 LastEMS = LastMappingSymbols.lookup(Section);
489 MCELFStreamer::ChangeSection(Section, Subsection);
492 /// This function is the one used to emit instruction data into the ELF
493 /// streamer. We override it to add the appropriate mapping symbol if
495 void EmitInstruction(const MCInst& Inst,
496 const MCSubtargetInfo &STI) override {
498 EmitThumbMappingSymbol();
500 EmitARMMappingSymbol();
502 MCELFStreamer::EmitInstruction(Inst, STI);
505 void emitInst(uint32_t Inst, char Suffix) {
508 const bool LittleEndian = getContext().getAsmInfo()->isLittleEndian();
515 EmitARMMappingSymbol();
516 for (unsigned II = 0, IE = Size; II != IE; II++) {
517 const unsigned I = LittleEndian ? (Size - II - 1) : II;
518 Buffer[Size - II - 1] = uint8_t(Inst >> I * CHAR_BIT);
524 Size = (Suffix == 'n' ? 2 : 4);
527 EmitThumbMappingSymbol();
528 for (unsigned II = 0, IE = Size; II != IE; II = II + 2) {
529 const unsigned I0 = LittleEndian ? II + 0 : (Size - II - 1);
530 const unsigned I1 = LittleEndian ? II + 1 : (Size - II - 2);
531 Buffer[Size - II - 2] = uint8_t(Inst >> I0 * CHAR_BIT);
532 Buffer[Size - II - 1] = uint8_t(Inst >> I1 * CHAR_BIT);
537 llvm_unreachable("Invalid Suffix");
540 MCELFStreamer::EmitBytes(StringRef(Buffer, Size));
543 /// This is one of the functions used to emit data into an ELF section, so the
544 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
546 void EmitBytes(StringRef Data) override {
547 EmitDataMappingSymbol();
548 MCELFStreamer::EmitBytes(Data);
551 /// This is one of the functions used to emit data into an ELF section, so the
552 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
554 void EmitValueImpl(const MCExpr *Value, unsigned Size,
555 const SMLoc &Loc) override {
556 if (const MCSymbolRefExpr *SRE = dyn_cast_or_null<MCSymbolRefExpr>(Value))
557 if (SRE->getKind() == MCSymbolRefExpr::VK_ARM_SBREL && !(Size == 4))
558 getContext().FatalError(Loc, "relocated expression must be 32-bit");
560 EmitDataMappingSymbol();
561 MCELFStreamer::EmitValueImpl(Value, Size);
564 void EmitAssemblerFlag(MCAssemblerFlag Flag) override {
565 MCELFStreamer::EmitAssemblerFlag(Flag);
568 case MCAF_SyntaxUnified:
569 return; // no-op here.
572 return; // Change to Thumb mode
575 return; // Change to ARM mode
578 case MCAF_SubsectionsViaSymbols:
584 enum ElfMappingSymbol {
591 void EmitDataMappingSymbol() {
592 if (LastEMS == EMS_Data) return;
593 EmitMappingSymbol("$d");
597 void EmitThumbMappingSymbol() {
598 if (LastEMS == EMS_Thumb) return;
599 EmitMappingSymbol("$t");
603 void EmitARMMappingSymbol() {
604 if (LastEMS == EMS_ARM) return;
605 EmitMappingSymbol("$a");
609 void EmitMappingSymbol(StringRef Name) {
610 MCSymbol *Start = getContext().CreateTempSymbol();
614 getContext().GetOrCreateSymbol(Name + "." +
615 Twine(MappingSymbolCounter++));
617 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
618 MCELF::SetType(SD, ELF::STT_NOTYPE);
619 MCELF::SetBinding(SD, ELF::STB_LOCAL);
620 SD.setExternal(false);
621 AssignSection(Symbol, getCurrentSection().first);
623 const MCExpr *Value = MCSymbolRefExpr::Create(Start, getContext());
624 Symbol->setVariableValue(Value);
627 void EmitThumbFunc(MCSymbol *Func) override {
628 getAssembler().setIsThumbFunc(Func);
629 EmitSymbolAttribute(Func, MCSA_ELF_TypeFunction);
632 // Helper functions for ARM exception handling directives
635 void EmitPersonalityFixup(StringRef Name);
636 void FlushPendingOffset();
637 void FlushUnwindOpcodes(bool NoHandlerData);
639 void SwitchToEHSection(const char *Prefix, unsigned Type, unsigned Flags,
640 SectionKind Kind, const MCSymbol &Fn);
641 void SwitchToExTabSection(const MCSymbol &FnStart);
642 void SwitchToExIdxSection(const MCSymbol &FnStart);
644 void EmitFixup(const MCExpr *Expr, MCFixupKind Kind);
647 int64_t MappingSymbolCounter;
649 DenseMap<const MCSection *, ElfMappingSymbol> LastMappingSymbols;
650 ElfMappingSymbol LastEMS;
652 // ARM Exception Handling Frame Information
655 const MCSymbol *Personality;
656 unsigned PersonalityIndex;
657 unsigned FPReg; // Frame pointer register
658 int64_t FPOffset; // Offset: (final frame pointer) - (initial $sp)
659 int64_t SPOffset; // Offset: (final $sp) - (initial $sp)
660 int64_t PendingOffset; // Offset: (final $sp) - (emitted $sp)
663 SmallVector<uint8_t, 64> Opcodes;
664 UnwindOpcodeAssembler UnwindOpAsm;
666 } // end anonymous namespace
668 ARMELFStreamer &ARMTargetELFStreamer::getStreamer() {
669 return static_cast<ARMELFStreamer &>(Streamer);
672 void ARMTargetELFStreamer::emitFnStart() { getStreamer().emitFnStart(); }
673 void ARMTargetELFStreamer::emitFnEnd() { getStreamer().emitFnEnd(); }
674 void ARMTargetELFStreamer::emitCantUnwind() { getStreamer().emitCantUnwind(); }
675 void ARMTargetELFStreamer::emitPersonality(const MCSymbol *Personality) {
676 getStreamer().emitPersonality(Personality);
678 void ARMTargetELFStreamer::emitPersonalityIndex(unsigned Index) {
679 getStreamer().emitPersonalityIndex(Index);
681 void ARMTargetELFStreamer::emitHandlerData() {
682 getStreamer().emitHandlerData();
684 void ARMTargetELFStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
686 getStreamer().emitSetFP(FpReg, SpReg, Offset);
688 void ARMTargetELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
689 getStreamer().emitMovSP(Reg, Offset);
691 void ARMTargetELFStreamer::emitPad(int64_t Offset) {
692 getStreamer().emitPad(Offset);
694 void ARMTargetELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
696 getStreamer().emitRegSave(RegList, isVector);
698 void ARMTargetELFStreamer::emitUnwindRaw(int64_t Offset,
699 const SmallVectorImpl<uint8_t> &Opcodes) {
700 getStreamer().emitUnwindRaw(Offset, Opcodes);
702 void ARMTargetELFStreamer::switchVendor(StringRef Vendor) {
703 assert(!Vendor.empty() && "Vendor cannot be empty.");
705 if (CurrentVendor == Vendor)
708 if (!CurrentVendor.empty())
709 finishAttributeSection();
711 assert(Contents.empty() &&
712 ".ARM.attributes should be flushed before changing vendor");
713 CurrentVendor = Vendor;
716 void ARMTargetELFStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
717 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
719 void ARMTargetELFStreamer::emitTextAttribute(unsigned Attribute,
721 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
723 void ARMTargetELFStreamer::emitIntTextAttribute(unsigned Attribute,
725 StringRef StringValue) {
726 setAttributeItems(Attribute, IntValue, StringValue,
727 /* OverwriteExisting= */ true);
729 void ARMTargetELFStreamer::emitArch(unsigned Value) {
732 void ARMTargetELFStreamer::emitObjectArch(unsigned Value) {
735 void ARMTargetELFStreamer::emitArchDefaultAttributes() {
736 using namespace ARMBuildAttrs;
738 setAttributeItem(CPU_name, GetArchDefaultCPUName(Arch), false);
739 if (EmittedArch == ARM::INVALID_ARCH)
740 setAttributeItem(CPU_arch, GetArchDefaultCPUArch(Arch), false);
742 setAttributeItem(CPU_arch, GetArchDefaultCPUArch(EmittedArch), false);
751 setAttributeItem(ARM_ISA_use, Allowed, false);
759 setAttributeItem(ARM_ISA_use, Allowed, false);
760 setAttributeItem(THUMB_ISA_use, Allowed, false);
764 setAttributeItem(ARM_ISA_use, Allowed, false);
765 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
770 setAttributeItem(ARM_ISA_use, Allowed, false);
771 setAttributeItem(THUMB_ISA_use, Allowed, false);
772 setAttributeItem(Virtualization_use, AllowTZ, false);
776 setAttributeItem(THUMB_ISA_use, Allowed, false);
780 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
784 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
785 setAttributeItem(ARM_ISA_use, Allowed, false);
786 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
790 setAttributeItem(CPU_arch_profile, RealTimeProfile, false);
791 setAttributeItem(ARM_ISA_use, Allowed, false);
792 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
796 setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
797 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
801 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
802 setAttributeItem(ARM_ISA_use, Allowed, false);
803 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
804 setAttributeItem(MPextension_use, Allowed, false);
805 setAttributeItem(Virtualization_use, AllowTZVirtualization, false);
809 setAttributeItem(ARM_ISA_use, Allowed, false);
810 setAttributeItem(THUMB_ISA_use, Allowed, false);
811 setAttributeItem(WMMX_arch, AllowWMMXv1, false);
815 setAttributeItem(ARM_ISA_use, Allowed, false);
816 setAttributeItem(THUMB_ISA_use, Allowed, false);
817 setAttributeItem(WMMX_arch, AllowWMMXv2, false);
821 report_fatal_error("Unknown Arch: " + Twine(Arch));
825 void ARMTargetELFStreamer::emitFPU(unsigned Value) {
828 void ARMTargetELFStreamer::emitFPUDefaultAttributes() {
832 setAttributeItem(ARMBuildAttrs::FP_arch,
833 ARMBuildAttrs::AllowFPv2,
834 /* OverwriteExisting= */ false);
838 setAttributeItem(ARMBuildAttrs::FP_arch,
839 ARMBuildAttrs::AllowFPv3A,
840 /* OverwriteExisting= */ false);
844 setAttributeItem(ARMBuildAttrs::FP_arch,
845 ARMBuildAttrs::AllowFPv3B,
846 /* OverwriteExisting= */ false);
850 setAttributeItem(ARMBuildAttrs::FP_arch,
851 ARMBuildAttrs::AllowFPv4A,
852 /* OverwriteExisting= */ false);
856 setAttributeItem(ARMBuildAttrs::FP_arch,
857 ARMBuildAttrs::AllowFPv4B,
858 /* OverwriteExisting= */ false);
862 setAttributeItem(ARMBuildAttrs::FP_arch,
863 ARMBuildAttrs::AllowFPARMv8A,
864 /* OverwriteExisting= */ false);
867 // FPV5_D16 is identical to FP_ARMV8 except for the number of D registers, so
868 // uses the FP_ARMV8_D16 build attribute.
870 setAttributeItem(ARMBuildAttrs::FP_arch,
871 ARMBuildAttrs::AllowFPARMv8B,
872 /* OverwriteExisting= */ false);
876 setAttributeItem(ARMBuildAttrs::FP_arch,
877 ARMBuildAttrs::AllowFPv3A,
878 /* OverwriteExisting= */ false);
879 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
880 ARMBuildAttrs::AllowNeon,
881 /* OverwriteExisting= */ false);
884 case ARM::NEON_VFPV4:
885 setAttributeItem(ARMBuildAttrs::FP_arch,
886 ARMBuildAttrs::AllowFPv4A,
887 /* OverwriteExisting= */ false);
888 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
889 ARMBuildAttrs::AllowNeon2,
890 /* OverwriteExisting= */ false);
893 case ARM::NEON_FP_ARMV8:
894 case ARM::CRYPTO_NEON_FP_ARMV8:
895 setAttributeItem(ARMBuildAttrs::FP_arch,
896 ARMBuildAttrs::AllowFPARMv8A,
897 /* OverwriteExisting= */ false);
898 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
899 ARMBuildAttrs::AllowNeonARMv8,
900 /* OverwriteExisting= */ false);
907 report_fatal_error("Unknown FPU: " + Twine(FPU));
911 size_t ARMTargetELFStreamer::calculateContentSize() const {
913 for (size_t i = 0; i < Contents.size(); ++i) {
914 AttributeItem item = Contents[i];
916 case AttributeItem::HiddenAttribute:
918 case AttributeItem::NumericAttribute:
919 Result += getULEB128Size(item.Tag);
920 Result += getULEB128Size(item.IntValue);
922 case AttributeItem::TextAttribute:
923 Result += getULEB128Size(item.Tag);
924 Result += item.StringValue.size() + 1; // string + '\0'
926 case AttributeItem::NumericAndTextAttributes:
927 Result += getULEB128Size(item.Tag);
928 Result += getULEB128Size(item.IntValue);
929 Result += item.StringValue.size() + 1; // string + '\0';
935 void ARMTargetELFStreamer::finishAttributeSection() {
937 // [ <section-length> "vendor-name"
938 // [ <file-tag> <size> <attribute>*
939 // | <section-tag> <size> <section-number>* 0 <attribute>*
940 // | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
944 if (FPU != ARM::INVALID_FPU)
945 emitFPUDefaultAttributes();
947 if (Arch != ARM::INVALID_ARCH)
948 emitArchDefaultAttributes();
950 if (Contents.empty())
953 std::sort(Contents.begin(), Contents.end(), AttributeItem::LessTag);
955 ARMELFStreamer &Streamer = getStreamer();
957 // Switch to .ARM.attributes section
958 if (AttributeSection) {
959 Streamer.SwitchSection(AttributeSection);
961 AttributeSection = Streamer.getContext().getELFSection(
962 ".ARM.attributes", ELF::SHT_ARM_ATTRIBUTES, 0);
963 Streamer.SwitchSection(AttributeSection);
966 Streamer.EmitIntValue(0x41, 1);
969 // Vendor size + Vendor name + '\0'
970 const size_t VendorHeaderSize = 4 + CurrentVendor.size() + 1;
973 const size_t TagHeaderSize = 1 + 4;
975 const size_t ContentsSize = calculateContentSize();
977 Streamer.EmitIntValue(VendorHeaderSize + TagHeaderSize + ContentsSize, 4);
978 Streamer.EmitBytes(CurrentVendor);
979 Streamer.EmitIntValue(0, 1); // '\0'
981 Streamer.EmitIntValue(ARMBuildAttrs::File, 1);
982 Streamer.EmitIntValue(TagHeaderSize + ContentsSize, 4);
984 // Size should have been accounted for already, now
985 // emit each field as its type (ULEB or String)
986 for (size_t i = 0; i < Contents.size(); ++i) {
987 AttributeItem item = Contents[i];
988 Streamer.EmitULEB128IntValue(item.Tag);
990 default: llvm_unreachable("Invalid attribute type");
991 case AttributeItem::NumericAttribute:
992 Streamer.EmitULEB128IntValue(item.IntValue);
994 case AttributeItem::TextAttribute:
995 Streamer.EmitBytes(item.StringValue);
996 Streamer.EmitIntValue(0, 1); // '\0'
998 case AttributeItem::NumericAndTextAttributes:
999 Streamer.EmitULEB128IntValue(item.IntValue);
1000 Streamer.EmitBytes(item.StringValue);
1001 Streamer.EmitIntValue(0, 1); // '\0'
1007 FPU = ARM::INVALID_FPU;
1010 void ARMTargetELFStreamer::emitLabel(MCSymbol *Symbol) {
1011 ARMELFStreamer &Streamer = getStreamer();
1012 if (!Streamer.IsThumb)
1015 const MCSymbolData &SD = Streamer.getOrCreateSymbolData(Symbol);
1016 unsigned Type = MCELF::GetType(SD);
1017 if (Type == ELF_STT_Func || Type == ELF_STT_GnuIFunc)
1018 Streamer.EmitThumbFunc(Symbol);
1022 ARMTargetELFStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
1023 getStreamer().EmitFixup(S, FK_Data_4);
1026 void ARMTargetELFStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
1027 if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(Value)) {
1028 const MCSymbol &Sym = SRE->getSymbol();
1029 if (!Sym.isDefined()) {
1030 getStreamer().EmitAssignment(Symbol, Value);
1035 getStreamer().EmitThumbFunc(Symbol);
1036 getStreamer().EmitAssignment(Symbol, Value);
1039 void ARMTargetELFStreamer::emitInst(uint32_t Inst, char Suffix) {
1040 getStreamer().emitInst(Inst, Suffix);
1043 void ARMELFStreamer::FinishImpl() {
1044 MCTargetStreamer &TS = *getTargetStreamer();
1045 ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1046 ATS.finishAttributeSection();
1048 MCELFStreamer::FinishImpl();
1051 inline void ARMELFStreamer::SwitchToEHSection(const char *Prefix,
1055 const MCSymbol &Fn) {
1056 const MCSectionELF &FnSection =
1057 static_cast<const MCSectionELF &>(Fn.getSection());
1059 // Create the name for new section
1060 StringRef FnSecName(FnSection.getSectionName());
1061 SmallString<128> EHSecName(Prefix);
1062 if (FnSecName != ".text") {
1063 EHSecName += FnSecName;
1066 // Get .ARM.extab or .ARM.exidx section
1067 const MCSectionELF *EHSection = nullptr;
1068 if (const MCSymbol *Group = FnSection.getGroup()) {
1070 getContext().getELFSection(EHSecName, Type, Flags | ELF::SHF_GROUP,
1071 FnSection.getEntrySize(), Group->getName());
1073 EHSection = getContext().getELFSection(EHSecName, Type, Flags);
1075 assert(EHSection && "Failed to get the required EH section");
1077 // Switch to .ARM.extab or .ARM.exidx section
1078 SwitchSection(EHSection);
1079 EmitCodeAlignment(4);
1082 inline void ARMELFStreamer::SwitchToExTabSection(const MCSymbol &FnStart) {
1083 SwitchToEHSection(".ARM.extab",
1086 SectionKind::getDataRel(),
1090 inline void ARMELFStreamer::SwitchToExIdxSection(const MCSymbol &FnStart) {
1091 SwitchToEHSection(".ARM.exidx",
1093 ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER,
1094 SectionKind::getDataRel(),
1097 void ARMELFStreamer::EmitFixup(const MCExpr *Expr, MCFixupKind Kind) {
1098 MCDataFragment *Frag = getOrCreateDataFragment();
1099 Frag->getFixups().push_back(MCFixup::Create(Frag->getContents().size(), Expr,
1103 void ARMELFStreamer::Reset() {
1106 Personality = nullptr;
1107 PersonalityIndex = ARM::EHABI::NUM_PERSONALITY_INDEX;
1116 UnwindOpAsm.Reset();
1119 void ARMELFStreamer::emitFnStart() {
1120 assert(FnStart == nullptr);
1121 FnStart = getContext().CreateTempSymbol();
1125 void ARMELFStreamer::emitFnEnd() {
1126 assert(FnStart && ".fnstart must precedes .fnend");
1128 // Emit unwind opcodes if there is no .handlerdata directive
1129 if (!ExTab && !CantUnwind)
1130 FlushUnwindOpcodes(true);
1132 // Emit the exception index table entry
1133 SwitchToExIdxSection(*FnStart);
1135 if (PersonalityIndex < ARM::EHABI::NUM_PERSONALITY_INDEX)
1136 EmitPersonalityFixup(GetAEABIUnwindPersonalityName(PersonalityIndex));
1138 const MCSymbolRefExpr *FnStartRef =
1139 MCSymbolRefExpr::Create(FnStart,
1140 MCSymbolRefExpr::VK_ARM_PREL31,
1143 EmitValue(FnStartRef, 4);
1146 EmitIntValue(ARM::EHABI::EXIDX_CANTUNWIND, 4);
1148 // Emit a reference to the unwind opcodes in the ".ARM.extab" section.
1149 const MCSymbolRefExpr *ExTabEntryRef =
1150 MCSymbolRefExpr::Create(ExTab,
1151 MCSymbolRefExpr::VK_ARM_PREL31,
1153 EmitValue(ExTabEntryRef, 4);
1155 // For the __aeabi_unwind_cpp_pr0, we have to emit the unwind opcodes in
1156 // the second word of exception index table entry. The size of the unwind
1157 // opcodes should always be 4 bytes.
1158 assert(PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0 &&
1159 "Compact model must use __aeabi_unwind_cpp_pr0 as personality");
1160 assert(Opcodes.size() == 4u &&
1161 "Unwind opcode size for __aeabi_unwind_cpp_pr0 must be equal to 4");
1162 uint64_t Intval = Opcodes[0] |
1166 EmitIntValue(Intval, Opcodes.size());
1169 // Switch to the section containing FnStart
1170 SwitchSection(&FnStart->getSection());
1172 // Clean exception handling frame information
1176 void ARMELFStreamer::emitCantUnwind() { CantUnwind = true; }
1178 // Add the R_ARM_NONE fixup at the same position
1179 void ARMELFStreamer::EmitPersonalityFixup(StringRef Name) {
1180 const MCSymbol *PersonalitySym = getContext().GetOrCreateSymbol(Name);
1182 const MCSymbolRefExpr *PersonalityRef = MCSymbolRefExpr::Create(
1183 PersonalitySym, MCSymbolRefExpr::VK_ARM_NONE, getContext());
1185 visitUsedExpr(*PersonalityRef);
1186 MCDataFragment *DF = getOrCreateDataFragment();
1187 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
1189 MCFixup::getKindForSize(4, false)));
1192 void ARMELFStreamer::FlushPendingOffset() {
1193 if (PendingOffset != 0) {
1194 UnwindOpAsm.EmitSPOffset(-PendingOffset);
1199 void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) {
1200 // Emit the unwind opcode to restore $sp.
1202 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1203 int64_t LastRegSaveSPOffset = SPOffset - PendingOffset;
1204 UnwindOpAsm.EmitSPOffset(LastRegSaveSPOffset - FPOffset);
1205 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1207 FlushPendingOffset();
1210 // Finalize the unwind opcode sequence
1211 UnwindOpAsm.Finalize(PersonalityIndex, Opcodes);
1213 // For compact model 0, we have to emit the unwind opcodes in the .ARM.exidx
1214 // section. Thus, we don't have to create an entry in the .ARM.extab
1216 if (NoHandlerData && PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0)
1219 // Switch to .ARM.extab section.
1220 SwitchToExTabSection(*FnStart);
1222 // Create .ARM.extab label for offset in .ARM.exidx
1224 ExTab = getContext().CreateTempSymbol();
1229 const MCSymbolRefExpr *PersonalityRef =
1230 MCSymbolRefExpr::Create(Personality,
1231 MCSymbolRefExpr::VK_ARM_PREL31,
1234 EmitValue(PersonalityRef, 4);
1237 // Emit unwind opcodes
1238 assert((Opcodes.size() % 4) == 0 &&
1239 "Unwind opcode size for __aeabi_cpp_unwind_pr0 must be multiple of 4");
1240 for (unsigned I = 0; I != Opcodes.size(); I += 4) {
1241 uint64_t Intval = Opcodes[I] |
1242 Opcodes[I + 1] << 8 |
1243 Opcodes[I + 2] << 16 |
1244 Opcodes[I + 3] << 24;
1245 EmitIntValue(Intval, 4);
1248 // According to ARM EHABI section 9.2, if the __aeabi_unwind_cpp_pr1() or
1249 // __aeabi_unwind_cpp_pr2() is used, then the handler data must be emitted
1250 // after the unwind opcodes. The handler data consists of several 32-bit
1251 // words, and should be terminated by zero.
1253 // In case that the .handlerdata directive is not specified by the
1254 // programmer, we should emit zero to terminate the handler data.
1255 if (NoHandlerData && !Personality)
1259 void ARMELFStreamer::emitHandlerData() { FlushUnwindOpcodes(false); }
1261 void ARMELFStreamer::emitPersonality(const MCSymbol *Per) {
1263 UnwindOpAsm.setPersonality(Per);
1266 void ARMELFStreamer::emitPersonalityIndex(unsigned Index) {
1267 assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX && "invalid index");
1268 PersonalityIndex = Index;
1271 void ARMELFStreamer::emitSetFP(unsigned NewFPReg, unsigned NewSPReg,
1273 assert((NewSPReg == ARM::SP || NewSPReg == FPReg) &&
1274 "the operand of .setfp directive should be either $sp or $fp");
1279 if (NewSPReg == ARM::SP)
1280 FPOffset = SPOffset + Offset;
1285 void ARMELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
1286 assert((Reg != ARM::SP && Reg != ARM::PC) &&
1287 "the operand of .movsp cannot be either sp or pc");
1288 assert(FPReg == ARM::SP && "current FP must be SP");
1290 FlushPendingOffset();
1293 FPOffset = SPOffset + Offset;
1295 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1296 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1299 void ARMELFStreamer::emitPad(int64_t Offset) {
1300 // Track the change of the $sp offset
1303 // To squash multiple .pad directives, we should delay the unwind opcode
1304 // until the .save, .vsave, .handlerdata, or .fnend directives.
1305 PendingOffset -= Offset;
1308 void ARMELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
1310 // Collect the registers in the register list
1313 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1314 for (size_t i = 0; i < RegList.size(); ++i) {
1315 unsigned Reg = MRI->getEncodingValue(RegList[i]);
1316 assert(Reg < (IsVector ? 32U : 16U) && "Register out of range");
1317 unsigned Bit = (1u << Reg);
1318 if ((Mask & Bit) == 0) {
1324 // Track the change the $sp offset: For the .save directive, the
1325 // corresponding push instruction will decrease the $sp by (4 * Count).
1326 // For the .vsave directive, the corresponding vpush instruction will
1327 // decrease $sp by (8 * Count).
1328 SPOffset -= Count * (IsVector ? 8 : 4);
1331 FlushPendingOffset();
1333 UnwindOpAsm.EmitVFPRegSave(Mask);
1335 UnwindOpAsm.EmitRegSave(Mask);
1338 void ARMELFStreamer::emitUnwindRaw(int64_t Offset,
1339 const SmallVectorImpl<uint8_t> &Opcodes) {
1340 FlushPendingOffset();
1341 SPOffset = SPOffset - Offset;
1342 UnwindOpAsm.EmitRaw(Opcodes);
1347 MCStreamer *createMCAsmStreamer(MCContext &Ctx, formatted_raw_ostream &OS,
1348 bool isVerboseAsm, bool useDwarfDirectory,
1349 MCInstPrinter *InstPrint, MCCodeEmitter *CE,
1350 MCAsmBackend *TAB, bool ShowInst) {
1351 MCStreamer *S = llvm::createAsmStreamer(
1352 Ctx, OS, isVerboseAsm, useDwarfDirectory, InstPrint, CE, TAB, ShowInst);
1353 new ARMTargetAsmStreamer(*S, OS, *InstPrint, isVerboseAsm);
1357 MCTargetStreamer *createARMNullTargetStreamer(MCStreamer &S) {
1358 return new ARMTargetStreamer(S);
1361 MCELFStreamer *createARMELFStreamer(MCContext &Context, MCAsmBackend &TAB,
1362 raw_ostream &OS, MCCodeEmitter *Emitter,
1363 bool RelaxAll, bool IsThumb) {
1364 ARMELFStreamer *S = new ARMELFStreamer(Context, TAB, OS, Emitter, IsThumb);
1365 new ARMTargetELFStreamer(*S);
1366 // FIXME: This should eventually end up somewhere else where more
1367 // intelligent flag decisions can be made. For now we are just maintaining
1368 // the status quo for ARM and setting EF_ARM_EABI_VER5 as the default.
1369 S->getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
1372 S->getAssembler().setRelaxAll(true);