1 //===- lib/MC/ARMELFStreamer.cpp - ELF Object Output for ARM --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file assembles .s files and emits ARM ELF .o object files. Different
11 // from generic ELF streamer in emitting mapping symbols ($a, $t and $d) to
12 // delimit regions of data and code.
14 //===----------------------------------------------------------------------===//
16 #include "ARMRegisterInfo.h"
17 #include "ARMUnwindOpAsm.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/MC/MCAsmBackend.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCCodeEmitter.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCELF.h"
26 #include "llvm/MC/MCELFStreamer.h"
27 #include "llvm/MC/MCELFSymbolFlags.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/MC/MCInst.h"
30 #include "llvm/MC/MCInstPrinter.h"
31 #include "llvm/MC/MCObjectFileInfo.h"
32 #include "llvm/MC/MCObjectStreamer.h"
33 #include "llvm/MC/MCRegisterInfo.h"
34 #include "llvm/MC/MCSection.h"
35 #include "llvm/MC/MCSectionELF.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/MC/MCValue.h"
39 #include "llvm/Support/ARMBuildAttributes.h"
40 #include "llvm/Support/ARMEHABI.h"
41 #include "llvm/Support/TargetParser.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ELF.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/LEB128.h"
46 #include "llvm/Support/raw_ostream.h"
51 static std::string GetAEABIUnwindPersonalityName(unsigned Index) {
52 assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX &&
53 "Invalid personality index");
54 return (Twine("__aeabi_unwind_cpp_pr") + Twine(Index)).str();
61 class ARMTargetAsmStreamer : public ARMTargetStreamer {
62 formatted_raw_ostream &OS;
63 MCInstPrinter &InstPrinter;
66 void emitFnStart() override;
67 void emitFnEnd() override;
68 void emitCantUnwind() override;
69 void emitPersonality(const MCSymbol *Personality) override;
70 void emitPersonalityIndex(unsigned Index) override;
71 void emitHandlerData() override;
72 void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
73 void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
74 void emitPad(int64_t Offset) override;
75 void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
76 bool isVector) override;
77 void emitUnwindRaw(int64_t Offset,
78 const SmallVectorImpl<uint8_t> &Opcodes) override;
80 void switchVendor(StringRef Vendor) override;
81 void emitAttribute(unsigned Attribute, unsigned Value) override;
82 void emitTextAttribute(unsigned Attribute, StringRef String) override;
83 void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
84 StringRef StrinValue) override;
85 void emitArch(unsigned Arch) override;
86 void emitArchExtension(unsigned ArchExt) override;
87 void emitObjectArch(unsigned Arch) override;
88 void emitFPU(unsigned FPU) override;
89 void emitInst(uint32_t Inst, char Suffix = '\0') override;
90 void finishAttributeSection() override;
92 void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
93 void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
96 ARMTargetAsmStreamer(MCStreamer &S, formatted_raw_ostream &OS,
97 MCInstPrinter &InstPrinter, bool VerboseAsm);
100 ARMTargetAsmStreamer::ARMTargetAsmStreamer(MCStreamer &S,
101 formatted_raw_ostream &OS,
102 MCInstPrinter &InstPrinter,
104 : ARMTargetStreamer(S), OS(OS), InstPrinter(InstPrinter),
105 IsVerboseAsm(VerboseAsm) {}
106 void ARMTargetAsmStreamer::emitFnStart() { OS << "\t.fnstart\n"; }
107 void ARMTargetAsmStreamer::emitFnEnd() { OS << "\t.fnend\n"; }
108 void ARMTargetAsmStreamer::emitCantUnwind() { OS << "\t.cantunwind\n"; }
109 void ARMTargetAsmStreamer::emitPersonality(const MCSymbol *Personality) {
110 OS << "\t.personality " << Personality->getName() << '\n';
112 void ARMTargetAsmStreamer::emitPersonalityIndex(unsigned Index) {
113 OS << "\t.personalityindex " << Index << '\n';
115 void ARMTargetAsmStreamer::emitHandlerData() { OS << "\t.handlerdata\n"; }
116 void ARMTargetAsmStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
119 InstPrinter.printRegName(OS, FpReg);
121 InstPrinter.printRegName(OS, SpReg);
123 OS << ", #" << Offset;
126 void ARMTargetAsmStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
127 assert((Reg != ARM::SP && Reg != ARM::PC) &&
128 "the operand of .movsp cannot be either sp or pc");
131 InstPrinter.printRegName(OS, Reg);
133 OS << ", #" << Offset;
136 void ARMTargetAsmStreamer::emitPad(int64_t Offset) {
137 OS << "\t.pad\t#" << Offset << '\n';
139 void ARMTargetAsmStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
141 assert(RegList.size() && "RegList should not be empty");
147 InstPrinter.printRegName(OS, RegList[0]);
149 for (unsigned i = 1, e = RegList.size(); i != e; ++i) {
151 InstPrinter.printRegName(OS, RegList[i]);
156 void ARMTargetAsmStreamer::switchVendor(StringRef Vendor) {
158 void ARMTargetAsmStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
159 OS << "\t.eabi_attribute\t" << Attribute << ", " << Twine(Value);
161 StringRef Name = ARMBuildAttrs::AttrTypeAsString(Attribute);
163 OS << "\t@ " << Name;
167 void ARMTargetAsmStreamer::emitTextAttribute(unsigned Attribute,
170 case ARMBuildAttrs::CPU_name:
171 OS << "\t.cpu\t" << String.lower();
174 OS << "\t.eabi_attribute\t" << Attribute << ", \"" << String << "\"";
176 StringRef Name = ARMBuildAttrs::AttrTypeAsString(Attribute);
178 OS << "\t@ " << Name;
184 void ARMTargetAsmStreamer::emitIntTextAttribute(unsigned Attribute,
186 StringRef StringValue) {
188 default: llvm_unreachable("unsupported multi-value attribute in asm mode");
189 case ARMBuildAttrs::compatibility:
190 OS << "\t.eabi_attribute\t" << Attribute << ", " << IntValue;
191 if (!StringValue.empty())
192 OS << ", \"" << StringValue << "\"";
194 OS << "\t@ " << ARMBuildAttrs::AttrTypeAsString(Attribute);
199 void ARMTargetAsmStreamer::emitArch(unsigned Arch) {
200 OS << "\t.arch\t" << ARMTargetParser::getArchName(Arch) << "\n";
202 void ARMTargetAsmStreamer::emitArchExtension(unsigned ArchExt) {
203 OS << "\t.arch_extension\t" << ARMTargetParser::getArchExtName(ArchExt) << "\n";
205 void ARMTargetAsmStreamer::emitObjectArch(unsigned Arch) {
206 OS << "\t.object_arch\t" << ARMTargetParser::getArchName(Arch) << '\n';
208 void ARMTargetAsmStreamer::emitFPU(unsigned FPU) {
209 OS << "\t.fpu\t" << ARMTargetParser::getFPUName(FPU) << "\n";
211 void ARMTargetAsmStreamer::finishAttributeSection() {
214 ARMTargetAsmStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
215 OS << "\t.tlsdescseq\t" << S->getSymbol().getName();
218 void ARMTargetAsmStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
219 OS << "\t.thumb_set\t" << *Symbol << ", " << *Value << '\n';
222 void ARMTargetAsmStreamer::emitInst(uint32_t Inst, char Suffix) {
226 OS << "\t0x" << Twine::utohexstr(Inst) << "\n";
229 void ARMTargetAsmStreamer::emitUnwindRaw(int64_t Offset,
230 const SmallVectorImpl<uint8_t> &Opcodes) {
231 OS << "\t.unwind_raw " << Offset;
232 for (SmallVectorImpl<uint8_t>::const_iterator OCI = Opcodes.begin(),
235 OS << ", 0x" << Twine::utohexstr(*OCI);
239 class ARMTargetELFStreamer : public ARMTargetStreamer {
241 // This structure holds all attributes, accounting for
242 // their string/numeric value, so we can later emmit them
243 // in declaration order, keeping all in the same vector
244 struct AttributeItem {
249 NumericAndTextAttributes
253 StringRef StringValue;
255 static bool LessTag(const AttributeItem &LHS, const AttributeItem &RHS) {
256 // The conformance tag must be emitted first when serialised
257 // into an object file. Specifically, the addenda to the ARM ABI
258 // states that (2.3.7.4):
260 // "To simplify recognition by consumers in the common case of
261 // claiming conformity for the whole file, this tag should be
262 // emitted first in a file-scope sub-subsection of the first
263 // public subsection of the attributes section."
265 // So it is special-cased in this comparison predicate when the
266 // attributes are sorted in finishAttributeSection().
267 return (RHS.Tag != ARMBuildAttrs::conformance) &&
268 ((LHS.Tag == ARMBuildAttrs::conformance) || (LHS.Tag < RHS.Tag));
272 StringRef CurrentVendor;
275 unsigned EmittedArch;
276 SmallVector<AttributeItem, 64> Contents;
278 MCSection *AttributeSection;
280 AttributeItem *getAttributeItem(unsigned Attribute) {
281 for (size_t i = 0; i < Contents.size(); ++i)
282 if (Contents[i].Tag == Attribute)
287 void setAttributeItem(unsigned Attribute, unsigned Value,
288 bool OverwriteExisting) {
289 // Look for existing attribute item
290 if (AttributeItem *Item = getAttributeItem(Attribute)) {
291 if (!OverwriteExisting)
293 Item->Type = AttributeItem::NumericAttribute;
294 Item->IntValue = Value;
298 // Create new attribute item
299 AttributeItem Item = {
300 AttributeItem::NumericAttribute,
305 Contents.push_back(Item);
308 void setAttributeItem(unsigned Attribute, StringRef Value,
309 bool OverwriteExisting) {
310 // Look for existing attribute item
311 if (AttributeItem *Item = getAttributeItem(Attribute)) {
312 if (!OverwriteExisting)
314 Item->Type = AttributeItem::TextAttribute;
315 Item->StringValue = Value;
319 // Create new attribute item
320 AttributeItem Item = {
321 AttributeItem::TextAttribute,
326 Contents.push_back(Item);
329 void setAttributeItems(unsigned Attribute, unsigned IntValue,
330 StringRef StringValue, bool OverwriteExisting) {
331 // Look for existing attribute item
332 if (AttributeItem *Item = getAttributeItem(Attribute)) {
333 if (!OverwriteExisting)
335 Item->Type = AttributeItem::NumericAndTextAttributes;
336 Item->IntValue = IntValue;
337 Item->StringValue = StringValue;
341 // Create new attribute item
342 AttributeItem Item = {
343 AttributeItem::NumericAndTextAttributes,
348 Contents.push_back(Item);
351 void emitArchDefaultAttributes();
352 void emitFPUDefaultAttributes();
354 ARMELFStreamer &getStreamer();
356 void emitFnStart() override;
357 void emitFnEnd() override;
358 void emitCantUnwind() override;
359 void emitPersonality(const MCSymbol *Personality) override;
360 void emitPersonalityIndex(unsigned Index) override;
361 void emitHandlerData() override;
362 void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
363 void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
364 void emitPad(int64_t Offset) override;
365 void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
366 bool isVector) override;
367 void emitUnwindRaw(int64_t Offset,
368 const SmallVectorImpl<uint8_t> &Opcodes) override;
370 void switchVendor(StringRef Vendor) override;
371 void emitAttribute(unsigned Attribute, unsigned Value) override;
372 void emitTextAttribute(unsigned Attribute, StringRef String) override;
373 void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
374 StringRef StringValue) override;
375 void emitArch(unsigned Arch) override;
376 void emitObjectArch(unsigned Arch) override;
377 void emitFPU(unsigned FPU) override;
378 void emitInst(uint32_t Inst, char Suffix = '\0') override;
379 void finishAttributeSection() override;
380 void emitLabel(MCSymbol *Symbol) override;
382 void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
383 void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
385 size_t calculateContentSize() const;
388 ARMTargetELFStreamer(MCStreamer &S)
389 : ARMTargetStreamer(S), CurrentVendor("aeabi"), FPU(ARM::FK_INVALID),
390 Arch(ARM::AK_INVALID), EmittedArch(ARM::AK_INVALID),
391 AttributeSection(nullptr) {}
394 /// Extend the generic ELFStreamer class so that it can emit mapping symbols at
395 /// the appropriate points in the object files. These symbols are defined in the
396 /// ARM ELF ABI: infocenter.arm.com/help/topic/com.arm.../IHI0044D_aaelf.pdf.
398 /// In brief: $a, $t or $d should be emitted at the start of each contiguous
399 /// region of ARM code, Thumb code or data in a section. In practice, this
400 /// emission does not rely on explicit assembler directives but on inherent
401 /// properties of the directives doing the emission (e.g. ".byte" is data, "add
402 /// r0, r0, r0" an instruction).
404 /// As a result this system is orthogonal to the DataRegion infrastructure used
405 /// by MachO. Beware!
406 class ARMELFStreamer : public MCELFStreamer {
408 friend class ARMTargetELFStreamer;
410 ARMELFStreamer(MCContext &Context, MCAsmBackend &TAB, raw_pwrite_stream &OS,
411 MCCodeEmitter *Emitter, bool IsThumb)
412 : MCELFStreamer(Context, TAB, OS, Emitter), IsThumb(IsThumb),
413 MappingSymbolCounter(0), LastEMS(EMS_None) {
419 void FinishImpl() override;
421 // ARM exception handling directives
424 void emitCantUnwind();
425 void emitPersonality(const MCSymbol *Per);
426 void emitPersonalityIndex(unsigned index);
427 void emitHandlerData();
428 void emitSetFP(unsigned NewFpReg, unsigned NewSpReg, int64_t Offset = 0);
429 void emitMovSP(unsigned Reg, int64_t Offset = 0);
430 void emitPad(int64_t Offset);
431 void emitRegSave(const SmallVectorImpl<unsigned> &RegList, bool isVector);
432 void emitUnwindRaw(int64_t Offset, const SmallVectorImpl<uint8_t> &Opcodes);
434 void ChangeSection(MCSection *Section, const MCExpr *Subsection) override {
435 // We have to keep track of the mapping symbol state of any sections we
436 // use. Each one should start off as EMS_None, which is provided as the
437 // default constructor by DenseMap::lookup.
438 LastMappingSymbols[getPreviousSection().first] = LastEMS;
439 LastEMS = LastMappingSymbols.lookup(Section);
441 MCELFStreamer::ChangeSection(Section, Subsection);
444 /// This function is the one used to emit instruction data into the ELF
445 /// streamer. We override it to add the appropriate mapping symbol if
447 void EmitInstruction(const MCInst& Inst,
448 const MCSubtargetInfo &STI) override {
450 EmitThumbMappingSymbol();
452 EmitARMMappingSymbol();
454 MCELFStreamer::EmitInstruction(Inst, STI);
457 void emitInst(uint32_t Inst, char Suffix) {
460 const bool LittleEndian = getContext().getAsmInfo()->isLittleEndian();
467 EmitARMMappingSymbol();
468 for (unsigned II = 0, IE = Size; II != IE; II++) {
469 const unsigned I = LittleEndian ? (Size - II - 1) : II;
470 Buffer[Size - II - 1] = uint8_t(Inst >> I * CHAR_BIT);
476 Size = (Suffix == 'n' ? 2 : 4);
479 EmitThumbMappingSymbol();
480 for (unsigned II = 0, IE = Size; II != IE; II = II + 2) {
481 const unsigned I0 = LittleEndian ? II + 0 : (Size - II - 1);
482 const unsigned I1 = LittleEndian ? II + 1 : (Size - II - 2);
483 Buffer[Size - II - 2] = uint8_t(Inst >> I0 * CHAR_BIT);
484 Buffer[Size - II - 1] = uint8_t(Inst >> I1 * CHAR_BIT);
489 llvm_unreachable("Invalid Suffix");
492 MCELFStreamer::EmitBytes(StringRef(Buffer, Size));
495 /// This is one of the functions used to emit data into an ELF section, so the
496 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
498 void EmitBytes(StringRef Data) override {
499 EmitDataMappingSymbol();
500 MCELFStreamer::EmitBytes(Data);
503 /// This is one of the functions used to emit data into an ELF section, so the
504 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
506 void EmitValueImpl(const MCExpr *Value, unsigned Size,
507 const SMLoc &Loc) override {
508 if (const MCSymbolRefExpr *SRE = dyn_cast_or_null<MCSymbolRefExpr>(Value))
509 if (SRE->getKind() == MCSymbolRefExpr::VK_ARM_SBREL && !(Size == 4))
510 getContext().reportFatalError(Loc, "relocated expression must be 32-bit");
512 EmitDataMappingSymbol();
513 MCELFStreamer::EmitValueImpl(Value, Size);
516 void EmitAssemblerFlag(MCAssemblerFlag Flag) override {
517 MCELFStreamer::EmitAssemblerFlag(Flag);
520 case MCAF_SyntaxUnified:
521 return; // no-op here.
524 return; // Change to Thumb mode
527 return; // Change to ARM mode
530 case MCAF_SubsectionsViaSymbols:
536 enum ElfMappingSymbol {
543 void EmitDataMappingSymbol() {
544 if (LastEMS == EMS_Data) return;
545 EmitMappingSymbol("$d");
549 void EmitThumbMappingSymbol() {
550 if (LastEMS == EMS_Thumb) return;
551 EmitMappingSymbol("$t");
555 void EmitARMMappingSymbol() {
556 if (LastEMS == EMS_ARM) return;
557 EmitMappingSymbol("$a");
561 void EmitMappingSymbol(StringRef Name) {
562 MCSymbol *Start = getContext().createTempSymbol();
566 getContext().getOrCreateSymbol(Name + "." +
567 Twine(MappingSymbolCounter++));
569 getAssembler().registerSymbol(*Symbol);
570 MCELF::SetType(*Symbol, ELF::STT_NOTYPE);
571 MCELF::SetBinding(*Symbol, ELF::STB_LOCAL);
572 Symbol->setExternal(false);
573 AssignSection(Symbol, getCurrentSection().first);
575 const MCExpr *Value = MCSymbolRefExpr::create(Start, getContext());
576 Symbol->setVariableValue(Value);
579 void EmitThumbFunc(MCSymbol *Func) override {
580 getAssembler().setIsThumbFunc(Func);
581 EmitSymbolAttribute(Func, MCSA_ELF_TypeFunction);
584 // Helper functions for ARM exception handling directives
587 void EmitPersonalityFixup(StringRef Name);
588 void FlushPendingOffset();
589 void FlushUnwindOpcodes(bool NoHandlerData);
591 void SwitchToEHSection(const char *Prefix, unsigned Type, unsigned Flags,
592 SectionKind Kind, const MCSymbol &Fn);
593 void SwitchToExTabSection(const MCSymbol &FnStart);
594 void SwitchToExIdxSection(const MCSymbol &FnStart);
596 void EmitFixup(const MCExpr *Expr, MCFixupKind Kind);
599 int64_t MappingSymbolCounter;
601 DenseMap<const MCSection *, ElfMappingSymbol> LastMappingSymbols;
602 ElfMappingSymbol LastEMS;
604 // ARM Exception Handling Frame Information
607 const MCSymbol *Personality;
608 unsigned PersonalityIndex;
609 unsigned FPReg; // Frame pointer register
610 int64_t FPOffset; // Offset: (final frame pointer) - (initial $sp)
611 int64_t SPOffset; // Offset: (final $sp) - (initial $sp)
612 int64_t PendingOffset; // Offset: (final $sp) - (emitted $sp)
615 SmallVector<uint8_t, 64> Opcodes;
616 UnwindOpcodeAssembler UnwindOpAsm;
618 } // end anonymous namespace
620 ARMELFStreamer &ARMTargetELFStreamer::getStreamer() {
621 return static_cast<ARMELFStreamer &>(Streamer);
624 void ARMTargetELFStreamer::emitFnStart() { getStreamer().emitFnStart(); }
625 void ARMTargetELFStreamer::emitFnEnd() { getStreamer().emitFnEnd(); }
626 void ARMTargetELFStreamer::emitCantUnwind() { getStreamer().emitCantUnwind(); }
627 void ARMTargetELFStreamer::emitPersonality(const MCSymbol *Personality) {
628 getStreamer().emitPersonality(Personality);
630 void ARMTargetELFStreamer::emitPersonalityIndex(unsigned Index) {
631 getStreamer().emitPersonalityIndex(Index);
633 void ARMTargetELFStreamer::emitHandlerData() {
634 getStreamer().emitHandlerData();
636 void ARMTargetELFStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
638 getStreamer().emitSetFP(FpReg, SpReg, Offset);
640 void ARMTargetELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
641 getStreamer().emitMovSP(Reg, Offset);
643 void ARMTargetELFStreamer::emitPad(int64_t Offset) {
644 getStreamer().emitPad(Offset);
646 void ARMTargetELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
648 getStreamer().emitRegSave(RegList, isVector);
650 void ARMTargetELFStreamer::emitUnwindRaw(int64_t Offset,
651 const SmallVectorImpl<uint8_t> &Opcodes) {
652 getStreamer().emitUnwindRaw(Offset, Opcodes);
654 void ARMTargetELFStreamer::switchVendor(StringRef Vendor) {
655 assert(!Vendor.empty() && "Vendor cannot be empty.");
657 if (CurrentVendor == Vendor)
660 if (!CurrentVendor.empty())
661 finishAttributeSection();
663 assert(Contents.empty() &&
664 ".ARM.attributes should be flushed before changing vendor");
665 CurrentVendor = Vendor;
668 void ARMTargetELFStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
669 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
671 void ARMTargetELFStreamer::emitTextAttribute(unsigned Attribute,
673 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
675 void ARMTargetELFStreamer::emitIntTextAttribute(unsigned Attribute,
677 StringRef StringValue) {
678 setAttributeItems(Attribute, IntValue, StringValue,
679 /* OverwriteExisting= */ true);
681 void ARMTargetELFStreamer::emitArch(unsigned Value) {
684 void ARMTargetELFStreamer::emitObjectArch(unsigned Value) {
687 void ARMTargetELFStreamer::emitArchDefaultAttributes() {
688 using namespace ARMBuildAttrs;
690 setAttributeItem(CPU_name,
691 ARMTargetParser::getCPUAttr(Arch),
694 if (EmittedArch == ARM::AK_INVALID)
695 setAttributeItem(CPU_arch,
696 ARMTargetParser::getArchAttr(Arch),
699 setAttributeItem(CPU_arch,
700 ARMTargetParser::getArchAttr(EmittedArch),
710 setAttributeItem(ARM_ISA_use, Allowed, false);
715 case ARM::AK_ARMV5TE:
718 setAttributeItem(ARM_ISA_use, Allowed, false);
719 setAttributeItem(THUMB_ISA_use, Allowed, false);
722 case ARM::AK_ARMV6T2:
723 setAttributeItem(ARM_ISA_use, Allowed, false);
724 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
729 case ARM::AK_ARMV6ZK:
730 setAttributeItem(ARM_ISA_use, Allowed, false);
731 setAttributeItem(THUMB_ISA_use, Allowed, false);
732 setAttributeItem(Virtualization_use, AllowTZ, false);
736 setAttributeItem(THUMB_ISA_use, Allowed, false);
740 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
744 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
745 setAttributeItem(ARM_ISA_use, Allowed, false);
746 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
750 setAttributeItem(CPU_arch_profile, RealTimeProfile, false);
751 setAttributeItem(ARM_ISA_use, Allowed, false);
752 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
756 setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
757 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
761 case ARM::AK_ARMV8_1A:
762 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
763 setAttributeItem(ARM_ISA_use, Allowed, false);
764 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
765 setAttributeItem(MPextension_use, Allowed, false);
766 setAttributeItem(Virtualization_use, AllowTZVirtualization, false);
770 setAttributeItem(ARM_ISA_use, Allowed, false);
771 setAttributeItem(THUMB_ISA_use, Allowed, false);
772 setAttributeItem(WMMX_arch, AllowWMMXv1, false);
775 case ARM::AK_IWMMXT2:
776 setAttributeItem(ARM_ISA_use, Allowed, false);
777 setAttributeItem(THUMB_ISA_use, Allowed, false);
778 setAttributeItem(WMMX_arch, AllowWMMXv2, false);
782 report_fatal_error("Unknown Arch: " + Twine(Arch));
786 void ARMTargetELFStreamer::emitFPU(unsigned Value) {
789 void ARMTargetELFStreamer::emitFPUDefaultAttributes() {
793 setAttributeItem(ARMBuildAttrs::FP_arch,
794 ARMBuildAttrs::AllowFPv2,
795 /* OverwriteExisting= */ false);
799 setAttributeItem(ARMBuildAttrs::FP_arch,
800 ARMBuildAttrs::AllowFPv3A,
801 /* OverwriteExisting= */ false);
804 case ARM::FK_VFPV3_D16:
805 setAttributeItem(ARMBuildAttrs::FP_arch,
806 ARMBuildAttrs::AllowFPv3B,
807 /* OverwriteExisting= */ false);
811 setAttributeItem(ARMBuildAttrs::FP_arch,
812 ARMBuildAttrs::AllowFPv4A,
813 /* OverwriteExisting= */ false);
816 case ARM::FK_VFPV4_D16:
817 setAttributeItem(ARMBuildAttrs::FP_arch,
818 ARMBuildAttrs::AllowFPv4B,
819 /* OverwriteExisting= */ false);
822 case ARM::FK_FP_ARMV8:
823 setAttributeItem(ARMBuildAttrs::FP_arch,
824 ARMBuildAttrs::AllowFPARMv8A,
825 /* OverwriteExisting= */ false);
828 // FPV5_D16 is identical to FP_ARMV8 except for the number of D registers, so
829 // uses the FP_ARMV8_D16 build attribute.
830 case ARM::FK_FPV5_D16:
831 setAttributeItem(ARMBuildAttrs::FP_arch,
832 ARMBuildAttrs::AllowFPARMv8B,
833 /* OverwriteExisting= */ false);
837 setAttributeItem(ARMBuildAttrs::FP_arch,
838 ARMBuildAttrs::AllowFPv3A,
839 /* OverwriteExisting= */ false);
840 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
841 ARMBuildAttrs::AllowNeon,
842 /* OverwriteExisting= */ false);
845 case ARM::FK_NEON_VFPV4:
846 setAttributeItem(ARMBuildAttrs::FP_arch,
847 ARMBuildAttrs::AllowFPv4A,
848 /* OverwriteExisting= */ false);
849 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
850 ARMBuildAttrs::AllowNeon2,
851 /* OverwriteExisting= */ false);
854 case ARM::FK_NEON_FP_ARMV8:
855 case ARM::FK_CRYPTO_NEON_FP_ARMV8:
856 setAttributeItem(ARMBuildAttrs::FP_arch,
857 ARMBuildAttrs::AllowFPARMv8A,
858 /* OverwriteExisting= */ false);
859 // 'Advanced_SIMD_arch' must be emitted not here, but within
860 // ARMAsmPrinter::emitAttributes(), depending on hasV8Ops() and hasV8_1a()
863 case ARM::FK_SOFTVFP:
867 report_fatal_error("Unknown FPU: " + Twine(FPU));
871 size_t ARMTargetELFStreamer::calculateContentSize() const {
873 for (size_t i = 0; i < Contents.size(); ++i) {
874 AttributeItem item = Contents[i];
876 case AttributeItem::HiddenAttribute:
878 case AttributeItem::NumericAttribute:
879 Result += getULEB128Size(item.Tag);
880 Result += getULEB128Size(item.IntValue);
882 case AttributeItem::TextAttribute:
883 Result += getULEB128Size(item.Tag);
884 Result += item.StringValue.size() + 1; // string + '\0'
886 case AttributeItem::NumericAndTextAttributes:
887 Result += getULEB128Size(item.Tag);
888 Result += getULEB128Size(item.IntValue);
889 Result += item.StringValue.size() + 1; // string + '\0';
895 void ARMTargetELFStreamer::finishAttributeSection() {
897 // [ <section-length> "vendor-name"
898 // [ <file-tag> <size> <attribute>*
899 // | <section-tag> <size> <section-number>* 0 <attribute>*
900 // | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
904 if (FPU != ARM::FK_INVALID)
905 emitFPUDefaultAttributes();
907 if (Arch != ARM::AK_INVALID)
908 emitArchDefaultAttributes();
910 if (Contents.empty())
913 std::sort(Contents.begin(), Contents.end(), AttributeItem::LessTag);
915 ARMELFStreamer &Streamer = getStreamer();
917 // Switch to .ARM.attributes section
918 if (AttributeSection) {
919 Streamer.SwitchSection(AttributeSection);
921 AttributeSection = Streamer.getContext().getELFSection(
922 ".ARM.attributes", ELF::SHT_ARM_ATTRIBUTES, 0);
923 Streamer.SwitchSection(AttributeSection);
926 Streamer.EmitIntValue(0x41, 1);
929 // Vendor size + Vendor name + '\0'
930 const size_t VendorHeaderSize = 4 + CurrentVendor.size() + 1;
933 const size_t TagHeaderSize = 1 + 4;
935 const size_t ContentsSize = calculateContentSize();
937 Streamer.EmitIntValue(VendorHeaderSize + TagHeaderSize + ContentsSize, 4);
938 Streamer.EmitBytes(CurrentVendor);
939 Streamer.EmitIntValue(0, 1); // '\0'
941 Streamer.EmitIntValue(ARMBuildAttrs::File, 1);
942 Streamer.EmitIntValue(TagHeaderSize + ContentsSize, 4);
944 // Size should have been accounted for already, now
945 // emit each field as its type (ULEB or String)
946 for (size_t i = 0; i < Contents.size(); ++i) {
947 AttributeItem item = Contents[i];
948 Streamer.EmitULEB128IntValue(item.Tag);
950 default: llvm_unreachable("Invalid attribute type");
951 case AttributeItem::NumericAttribute:
952 Streamer.EmitULEB128IntValue(item.IntValue);
954 case AttributeItem::TextAttribute:
955 Streamer.EmitBytes(item.StringValue);
956 Streamer.EmitIntValue(0, 1); // '\0'
958 case AttributeItem::NumericAndTextAttributes:
959 Streamer.EmitULEB128IntValue(item.IntValue);
960 Streamer.EmitBytes(item.StringValue);
961 Streamer.EmitIntValue(0, 1); // '\0'
967 FPU = ARM::FK_INVALID;
970 void ARMTargetELFStreamer::emitLabel(MCSymbol *Symbol) {
971 ARMELFStreamer &Streamer = getStreamer();
972 if (!Streamer.IsThumb)
975 Streamer.getOrCreateSymbolData(Symbol);
976 unsigned Type = MCELF::GetType(*Symbol);
977 if (Type == ELF_STT_Func || Type == ELF_STT_GnuIFunc)
978 Streamer.EmitThumbFunc(Symbol);
982 ARMTargetELFStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
983 getStreamer().EmitFixup(S, FK_Data_4);
986 void ARMTargetELFStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
987 if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(Value)) {
988 const MCSymbol &Sym = SRE->getSymbol();
989 if (!Sym.isDefined()) {
990 getStreamer().EmitAssignment(Symbol, Value);
995 getStreamer().EmitThumbFunc(Symbol);
996 getStreamer().EmitAssignment(Symbol, Value);
999 void ARMTargetELFStreamer::emitInst(uint32_t Inst, char Suffix) {
1000 getStreamer().emitInst(Inst, Suffix);
1003 void ARMELFStreamer::FinishImpl() {
1004 MCTargetStreamer &TS = *getTargetStreamer();
1005 ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1006 ATS.finishAttributeSection();
1008 MCELFStreamer::FinishImpl();
1011 inline void ARMELFStreamer::SwitchToEHSection(const char *Prefix,
1015 const MCSymbol &Fn) {
1016 const MCSectionELF &FnSection =
1017 static_cast<const MCSectionELF &>(Fn.getSection());
1019 // Create the name for new section
1020 StringRef FnSecName(FnSection.getSectionName());
1021 SmallString<128> EHSecName(Prefix);
1022 if (FnSecName != ".text") {
1023 EHSecName += FnSecName;
1026 // Get .ARM.extab or .ARM.exidx section
1027 const MCSymbol *Group = FnSection.getGroup();
1029 Flags |= ELF::SHF_GROUP;
1030 MCSectionELF *EHSection =
1031 getContext().getELFSection(EHSecName, Type, Flags, 0, Group,
1032 FnSection.getUniqueID(), nullptr, &FnSection);
1034 assert(EHSection && "Failed to get the required EH section");
1036 // Switch to .ARM.extab or .ARM.exidx section
1037 SwitchSection(EHSection);
1038 EmitCodeAlignment(4);
1041 inline void ARMELFStreamer::SwitchToExTabSection(const MCSymbol &FnStart) {
1042 SwitchToEHSection(".ARM.extab",
1045 SectionKind::getDataRel(),
1049 inline void ARMELFStreamer::SwitchToExIdxSection(const MCSymbol &FnStart) {
1050 SwitchToEHSection(".ARM.exidx",
1052 ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER,
1053 SectionKind::getDataRel(),
1056 void ARMELFStreamer::EmitFixup(const MCExpr *Expr, MCFixupKind Kind) {
1057 MCDataFragment *Frag = getOrCreateDataFragment();
1058 Frag->getFixups().push_back(MCFixup::create(Frag->getContents().size(), Expr,
1062 void ARMELFStreamer::Reset() {
1065 Personality = nullptr;
1066 PersonalityIndex = ARM::EHABI::NUM_PERSONALITY_INDEX;
1075 UnwindOpAsm.Reset();
1078 void ARMELFStreamer::emitFnStart() {
1079 assert(FnStart == nullptr);
1080 FnStart = getContext().createTempSymbol();
1084 void ARMELFStreamer::emitFnEnd() {
1085 assert(FnStart && ".fnstart must precedes .fnend");
1087 // Emit unwind opcodes if there is no .handlerdata directive
1088 if (!ExTab && !CantUnwind)
1089 FlushUnwindOpcodes(true);
1091 // Emit the exception index table entry
1092 SwitchToExIdxSection(*FnStart);
1094 if (PersonalityIndex < ARM::EHABI::NUM_PERSONALITY_INDEX)
1095 EmitPersonalityFixup(GetAEABIUnwindPersonalityName(PersonalityIndex));
1097 const MCSymbolRefExpr *FnStartRef =
1098 MCSymbolRefExpr::create(FnStart,
1099 MCSymbolRefExpr::VK_ARM_PREL31,
1102 EmitValue(FnStartRef, 4);
1105 EmitIntValue(ARM::EHABI::EXIDX_CANTUNWIND, 4);
1107 // Emit a reference to the unwind opcodes in the ".ARM.extab" section.
1108 const MCSymbolRefExpr *ExTabEntryRef =
1109 MCSymbolRefExpr::create(ExTab,
1110 MCSymbolRefExpr::VK_ARM_PREL31,
1112 EmitValue(ExTabEntryRef, 4);
1114 // For the __aeabi_unwind_cpp_pr0, we have to emit the unwind opcodes in
1115 // the second word of exception index table entry. The size of the unwind
1116 // opcodes should always be 4 bytes.
1117 assert(PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0 &&
1118 "Compact model must use __aeabi_unwind_cpp_pr0 as personality");
1119 assert(Opcodes.size() == 4u &&
1120 "Unwind opcode size for __aeabi_unwind_cpp_pr0 must be equal to 4");
1121 uint64_t Intval = Opcodes[0] |
1125 EmitIntValue(Intval, Opcodes.size());
1128 // Switch to the section containing FnStart
1129 SwitchSection(&FnStart->getSection());
1131 // Clean exception handling frame information
1135 void ARMELFStreamer::emitCantUnwind() { CantUnwind = true; }
1137 // Add the R_ARM_NONE fixup at the same position
1138 void ARMELFStreamer::EmitPersonalityFixup(StringRef Name) {
1139 const MCSymbol *PersonalitySym = getContext().getOrCreateSymbol(Name);
1141 const MCSymbolRefExpr *PersonalityRef = MCSymbolRefExpr::create(
1142 PersonalitySym, MCSymbolRefExpr::VK_ARM_NONE, getContext());
1144 visitUsedExpr(*PersonalityRef);
1145 MCDataFragment *DF = getOrCreateDataFragment();
1146 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
1148 MCFixup::getKindForSize(4, false)));
1151 void ARMELFStreamer::FlushPendingOffset() {
1152 if (PendingOffset != 0) {
1153 UnwindOpAsm.EmitSPOffset(-PendingOffset);
1158 void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) {
1159 // Emit the unwind opcode to restore $sp.
1161 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1162 int64_t LastRegSaveSPOffset = SPOffset - PendingOffset;
1163 UnwindOpAsm.EmitSPOffset(LastRegSaveSPOffset - FPOffset);
1164 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1166 FlushPendingOffset();
1169 // Finalize the unwind opcode sequence
1170 UnwindOpAsm.Finalize(PersonalityIndex, Opcodes);
1172 // For compact model 0, we have to emit the unwind opcodes in the .ARM.exidx
1173 // section. Thus, we don't have to create an entry in the .ARM.extab
1175 if (NoHandlerData && PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0)
1178 // Switch to .ARM.extab section.
1179 SwitchToExTabSection(*FnStart);
1181 // Create .ARM.extab label for offset in .ARM.exidx
1183 ExTab = getContext().createTempSymbol();
1188 const MCSymbolRefExpr *PersonalityRef =
1189 MCSymbolRefExpr::create(Personality,
1190 MCSymbolRefExpr::VK_ARM_PREL31,
1193 EmitValue(PersonalityRef, 4);
1196 // Emit unwind opcodes
1197 assert((Opcodes.size() % 4) == 0 &&
1198 "Unwind opcode size for __aeabi_cpp_unwind_pr0 must be multiple of 4");
1199 for (unsigned I = 0; I != Opcodes.size(); I += 4) {
1200 uint64_t Intval = Opcodes[I] |
1201 Opcodes[I + 1] << 8 |
1202 Opcodes[I + 2] << 16 |
1203 Opcodes[I + 3] << 24;
1204 EmitIntValue(Intval, 4);
1207 // According to ARM EHABI section 9.2, if the __aeabi_unwind_cpp_pr1() or
1208 // __aeabi_unwind_cpp_pr2() is used, then the handler data must be emitted
1209 // after the unwind opcodes. The handler data consists of several 32-bit
1210 // words, and should be terminated by zero.
1212 // In case that the .handlerdata directive is not specified by the
1213 // programmer, we should emit zero to terminate the handler data.
1214 if (NoHandlerData && !Personality)
1218 void ARMELFStreamer::emitHandlerData() { FlushUnwindOpcodes(false); }
1220 void ARMELFStreamer::emitPersonality(const MCSymbol *Per) {
1222 UnwindOpAsm.setPersonality(Per);
1225 void ARMELFStreamer::emitPersonalityIndex(unsigned Index) {
1226 assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX && "invalid index");
1227 PersonalityIndex = Index;
1230 void ARMELFStreamer::emitSetFP(unsigned NewFPReg, unsigned NewSPReg,
1232 assert((NewSPReg == ARM::SP || NewSPReg == FPReg) &&
1233 "the operand of .setfp directive should be either $sp or $fp");
1238 if (NewSPReg == ARM::SP)
1239 FPOffset = SPOffset + Offset;
1244 void ARMELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
1245 assert((Reg != ARM::SP && Reg != ARM::PC) &&
1246 "the operand of .movsp cannot be either sp or pc");
1247 assert(FPReg == ARM::SP && "current FP must be SP");
1249 FlushPendingOffset();
1252 FPOffset = SPOffset + Offset;
1254 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1255 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1258 void ARMELFStreamer::emitPad(int64_t Offset) {
1259 // Track the change of the $sp offset
1262 // To squash multiple .pad directives, we should delay the unwind opcode
1263 // until the .save, .vsave, .handlerdata, or .fnend directives.
1264 PendingOffset -= Offset;
1267 void ARMELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
1269 // Collect the registers in the register list
1272 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1273 for (size_t i = 0; i < RegList.size(); ++i) {
1274 unsigned Reg = MRI->getEncodingValue(RegList[i]);
1275 assert(Reg < (IsVector ? 32U : 16U) && "Register out of range");
1276 unsigned Bit = (1u << Reg);
1277 if ((Mask & Bit) == 0) {
1283 // Track the change the $sp offset: For the .save directive, the
1284 // corresponding push instruction will decrease the $sp by (4 * Count).
1285 // For the .vsave directive, the corresponding vpush instruction will
1286 // decrease $sp by (8 * Count).
1287 SPOffset -= Count * (IsVector ? 8 : 4);
1290 FlushPendingOffset();
1292 UnwindOpAsm.EmitVFPRegSave(Mask);
1294 UnwindOpAsm.EmitRegSave(Mask);
1297 void ARMELFStreamer::emitUnwindRaw(int64_t Offset,
1298 const SmallVectorImpl<uint8_t> &Opcodes) {
1299 FlushPendingOffset();
1300 SPOffset = SPOffset - Offset;
1301 UnwindOpAsm.EmitRaw(Opcodes);
1306 MCTargetStreamer *createARMTargetAsmStreamer(MCStreamer &S,
1307 formatted_raw_ostream &OS,
1308 MCInstPrinter *InstPrint,
1309 bool isVerboseAsm) {
1310 return new ARMTargetAsmStreamer(S, OS, *InstPrint, isVerboseAsm);
1313 MCTargetStreamer *createARMNullTargetStreamer(MCStreamer &S) {
1314 return new ARMTargetStreamer(S);
1317 MCTargetStreamer *createARMObjectTargetStreamer(MCStreamer &S,
1318 const MCSubtargetInfo &STI) {
1319 Triple TT(STI.getTargetTriple());
1320 if (TT.getObjectFormat() == Triple::ELF)
1321 return new ARMTargetELFStreamer(S);
1322 return new ARMTargetStreamer(S);
1325 MCELFStreamer *createARMELFStreamer(MCContext &Context, MCAsmBackend &TAB,
1326 raw_pwrite_stream &OS,
1327 MCCodeEmitter *Emitter, bool RelaxAll,
1329 ARMELFStreamer *S = new ARMELFStreamer(Context, TAB, OS, Emitter, IsThumb);
1330 // FIXME: This should eventually end up somewhere else where more
1331 // intelligent flag decisions can be made. For now we are just maintaining
1332 // the status quo for ARM and setting EF_ARM_EABI_VER5 as the default.
1333 S->getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
1336 S->getAssembler().setRelaxAll(true);