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/SmallPtrSet.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/MC/MCAsmBackend.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCAssembler.h"
26 #include "llvm/MC/MCCodeEmitter.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCELF.h"
29 #include "llvm/MC/MCELFStreamer.h"
30 #include "llvm/MC/MCELFSymbolFlags.h"
31 #include "llvm/MC/MCExpr.h"
32 #include "llvm/MC/MCInst.h"
33 #include "llvm/MC/MCInstPrinter.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/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();
57 static const char *GetFPUName(unsigned ID) {
60 llvm_unreachable("Unknown FPU kind");
62 #define ARM_FPU_NAME(NAME, ID) case ARM::ID: return NAME;
63 #include "ARMFPUName.def"
68 static const char *GetArchName(unsigned ID) {
71 llvm_unreachable("Unknown ARCH kind");
73 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
74 case ARM::ID: return NAME;
75 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
76 #include "ARMArchName.def"
81 static const char *GetArchDefaultCPUName(unsigned ID) {
84 llvm_unreachable("Unknown ARCH kind");
86 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
87 case ARM::ID: return DEFAULT_CPU_NAME;
88 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
89 #include "ARMArchName.def"
94 static unsigned GetArchDefaultCPUArch(unsigned ID) {
97 llvm_unreachable("Unknown ARCH kind");
99 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
100 case ARM::ID: return ARMBuildAttrs::DEFAULT_CPU_ARCH;
101 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
102 #include "ARMArchName.def"
107 void ARMTargetStreamer::anchor() {}
108 ARMTargetStreamer::ARMTargetStreamer(MCStreamer &S) : MCTargetStreamer(S) {}
112 class ARMELFStreamer;
114 class ARMTargetAsmStreamer : public ARMTargetStreamer {
115 formatted_raw_ostream &OS;
116 MCInstPrinter &InstPrinter;
119 virtual void emitFnStart();
120 virtual void emitFnEnd();
121 virtual void emitCantUnwind();
122 virtual void emitPersonality(const MCSymbol *Personality);
123 virtual void emitPersonalityIndex(unsigned Index);
124 virtual void emitHandlerData();
125 virtual void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
126 virtual void emitMovSP(unsigned Reg, int64_t Offset = 0);
127 virtual void emitPad(int64_t Offset);
128 virtual void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
130 virtual void emitUnwindRaw(int64_t Offset,
131 const SmallVectorImpl<uint8_t> &Opcodes);
133 virtual void switchVendor(StringRef Vendor);
134 virtual void emitAttribute(unsigned Attribute, unsigned Value);
135 virtual void emitTextAttribute(unsigned Attribute, StringRef String);
136 virtual void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
137 StringRef StrinValue);
138 virtual void emitArch(unsigned Arch);
139 virtual void emitFPU(unsigned FPU);
140 virtual void emitInst(uint32_t Inst, char Suffix = '\0');
141 virtual void finishAttributeSection();
143 virtual void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE);
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::emitFPU(unsigned FPU) {
253 OS << "\t.fpu\t" << GetFPUName(FPU) << "\n";
255 void ARMTargetAsmStreamer::finishAttributeSection() {
258 ARMTargetAsmStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
259 OS << "\t.tlsdescseq\t" << S->getSymbol().getName();
262 void ARMTargetAsmStreamer::emitInst(uint32_t Inst, char Suffix) {
266 OS << "\t0x" << utohexstr(Inst) << "\n";
269 void ARMTargetAsmStreamer::emitUnwindRaw(int64_t Offset,
270 const SmallVectorImpl<uint8_t> &Opcodes) {
271 OS << "\t.unwind_raw " << Offset;
272 for (SmallVectorImpl<uint8_t>::const_iterator OCI = Opcodes.begin(),
275 OS << ", 0x" << utohexstr(*OCI);
279 class ARMTargetELFStreamer : public ARMTargetStreamer {
281 // This structure holds all attributes, accounting for
282 // their string/numeric value, so we can later emmit them
283 // in declaration order, keeping all in the same vector
284 struct AttributeItem {
289 NumericAndTextAttributes
293 StringRef StringValue;
295 static bool LessTag(const AttributeItem &LHS, const AttributeItem &RHS) {
296 return (LHS.Tag < RHS.Tag);
300 StringRef CurrentVendor;
303 SmallVector<AttributeItem, 64> Contents;
305 const MCSection *AttributeSection;
307 // FIXME: this should be in a more generic place, but
308 // getULEBSize() is in MCAsmInfo and will be moved to MCDwarf
309 static size_t getULEBSize(int Value) {
313 Size += sizeof(int8_t); // Is this really necessary?
318 AttributeItem *getAttributeItem(unsigned Attribute) {
319 for (size_t i = 0; i < Contents.size(); ++i)
320 if (Contents[i].Tag == Attribute)
325 void setAttributeItem(unsigned Attribute, unsigned Value,
326 bool OverwriteExisting) {
327 // Look for existing attribute item
328 if (AttributeItem *Item = getAttributeItem(Attribute)) {
329 if (!OverwriteExisting)
331 Item->Type = AttributeItem::NumericAttribute;
332 Item->IntValue = Value;
336 // Create new attribute item
337 AttributeItem Item = {
338 AttributeItem::NumericAttribute,
343 Contents.push_back(Item);
346 void setAttributeItem(unsigned Attribute, StringRef Value,
347 bool OverwriteExisting) {
348 // Look for existing attribute item
349 if (AttributeItem *Item = getAttributeItem(Attribute)) {
350 if (!OverwriteExisting)
352 Item->Type = AttributeItem::TextAttribute;
353 Item->StringValue = Value;
357 // Create new attribute item
358 AttributeItem Item = {
359 AttributeItem::TextAttribute,
364 Contents.push_back(Item);
367 void setAttributeItems(unsigned Attribute, unsigned IntValue,
368 StringRef StringValue, bool OverwriteExisting) {
369 // Look for existing attribute item
370 if (AttributeItem *Item = getAttributeItem(Attribute)) {
371 if (!OverwriteExisting)
373 Item->Type = AttributeItem::NumericAndTextAttributes;
374 Item->IntValue = IntValue;
375 Item->StringValue = StringValue;
379 // Create new attribute item
380 AttributeItem Item = {
381 AttributeItem::NumericAndTextAttributes,
386 Contents.push_back(Item);
389 void emitArchDefaultAttributes();
390 void emitFPUDefaultAttributes();
392 ARMELFStreamer &getStreamer();
394 virtual void emitFnStart();
395 virtual void emitFnEnd();
396 virtual void emitCantUnwind();
397 virtual void emitPersonality(const MCSymbol *Personality);
398 virtual void emitPersonalityIndex(unsigned Index);
399 virtual void emitHandlerData();
400 virtual void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
401 virtual void emitMovSP(unsigned Reg, int64_t Offset = 0);
402 virtual void emitPad(int64_t Offset);
403 virtual void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
405 virtual void emitUnwindRaw(int64_t Offset,
406 const SmallVectorImpl<uint8_t> &Opcodes);
408 virtual void switchVendor(StringRef Vendor);
409 virtual void emitAttribute(unsigned Attribute, unsigned Value);
410 virtual void emitTextAttribute(unsigned Attribute, StringRef String);
411 virtual void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
412 StringRef StringValue);
413 virtual void emitArch(unsigned Arch);
414 virtual void emitFPU(unsigned FPU);
415 virtual void emitInst(uint32_t Inst, char Suffix = '\0');
416 virtual void finishAttributeSection();
418 virtual void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE);
420 size_t calculateContentSize() const;
423 ARMTargetELFStreamer(MCStreamer &S)
424 : ARMTargetStreamer(S), CurrentVendor("aeabi"), FPU(ARM::INVALID_FPU),
425 Arch(ARM::INVALID_ARCH), AttributeSection(0) {}
428 /// Extend the generic ELFStreamer class so that it can emit mapping symbols at
429 /// the appropriate points in the object files. These symbols are defined in the
430 /// ARM ELF ABI: infocenter.arm.com/help/topic/com.arm.../IHI0044D_aaelf.pdf.
432 /// In brief: $a, $t or $d should be emitted at the start of each contiguous
433 /// region of ARM code, Thumb code or data in a section. In practice, this
434 /// emission does not rely on explicit assembler directives but on inherent
435 /// properties of the directives doing the emission (e.g. ".byte" is data, "add
436 /// r0, r0, r0" an instruction).
438 /// As a result this system is orthogonal to the DataRegion infrastructure used
439 /// by MachO. Beware!
440 class ARMELFStreamer : public MCELFStreamer {
442 friend class ARMTargetELFStreamer;
444 ARMELFStreamer(MCContext &Context, MCAsmBackend &TAB, raw_ostream &OS,
445 MCCodeEmitter *Emitter, bool IsThumb)
446 : MCELFStreamer(Context, TAB, OS, Emitter), IsThumb(IsThumb),
447 MappingSymbolCounter(0), LastEMS(EMS_None) {
453 virtual void FinishImpl();
455 // ARM exception handling directives
458 void emitCantUnwind();
459 void emitPersonality(const MCSymbol *Per);
460 void emitPersonalityIndex(unsigned index);
461 void emitHandlerData();
462 void emitSetFP(unsigned NewFpReg, unsigned NewSpReg, int64_t Offset = 0);
463 void emitMovSP(unsigned Reg, int64_t Offset = 0);
464 void emitPad(int64_t Offset);
465 void emitRegSave(const SmallVectorImpl<unsigned> &RegList, bool isVector);
466 void emitUnwindRaw(int64_t Offset, const SmallVectorImpl<uint8_t> &Opcodes);
468 virtual void ChangeSection(const MCSection *Section,
469 const MCExpr *Subsection) {
470 // We have to keep track of the mapping symbol state of any sections we
471 // use. Each one should start off as EMS_None, which is provided as the
472 // default constructor by DenseMap::lookup.
473 LastMappingSymbols[getPreviousSection().first] = LastEMS;
474 LastEMS = LastMappingSymbols.lookup(Section);
476 MCELFStreamer::ChangeSection(Section, Subsection);
479 /// This function is the one used to emit instruction data into the ELF
480 /// streamer. We override it to add the appropriate mapping symbol if
482 virtual void EmitInstruction(const MCInst& Inst, const MCSubtargetInfo &STI) {
484 EmitThumbMappingSymbol();
486 EmitARMMappingSymbol();
488 MCELFStreamer::EmitInstruction(Inst, STI);
491 virtual void emitInst(uint32_t Inst, char Suffix) {
494 const bool LittleEndian = getContext().getAsmInfo()->isLittleEndian();
501 EmitARMMappingSymbol();
502 for (unsigned II = 0, IE = Size; II != IE; II++) {
503 const unsigned I = LittleEndian ? (Size - II - 1) : II;
504 Buffer[Size - II - 1] = uint8_t(Inst >> I * CHAR_BIT);
510 Size = (Suffix == 'n' ? 2 : 4);
513 EmitThumbMappingSymbol();
514 for (unsigned II = 0, IE = Size; II != IE; II = II + 2) {
515 const unsigned I0 = LittleEndian ? II + 0 : (Size - II - 1);
516 const unsigned I1 = LittleEndian ? II + 1 : (Size - II - 2);
517 Buffer[Size - II - 2] = uint8_t(Inst >> I0 * CHAR_BIT);
518 Buffer[Size - II - 1] = uint8_t(Inst >> I1 * CHAR_BIT);
523 llvm_unreachable("Invalid Suffix");
526 MCELFStreamer::EmitBytes(StringRef(Buffer, Size));
529 /// This is one of the functions used to emit data into an ELF section, so the
530 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
532 virtual void EmitBytes(StringRef Data) {
533 EmitDataMappingSymbol();
534 MCELFStreamer::EmitBytes(Data);
537 /// This is one of the functions used to emit data into an ELF section, so the
538 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
540 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {
541 EmitDataMappingSymbol();
542 MCELFStreamer::EmitValueImpl(Value, Size);
545 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {
546 MCELFStreamer::EmitAssemblerFlag(Flag);
549 case MCAF_SyntaxUnified:
550 return; // no-op here.
553 return; // Change to Thumb mode
556 return; // Change to ARM mode
559 case MCAF_SubsectionsViaSymbols:
565 enum ElfMappingSymbol {
572 void EmitDataMappingSymbol() {
573 if (LastEMS == EMS_Data) return;
574 EmitMappingSymbol("$d");
578 void EmitThumbMappingSymbol() {
579 if (LastEMS == EMS_Thumb) return;
580 EmitMappingSymbol("$t");
584 void EmitARMMappingSymbol() {
585 if (LastEMS == EMS_ARM) return;
586 EmitMappingSymbol("$a");
590 void EmitMappingSymbol(StringRef Name) {
591 MCSymbol *Start = getContext().CreateTempSymbol();
595 getContext().GetOrCreateSymbol(Name + "." +
596 Twine(MappingSymbolCounter++));
598 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
599 MCELF::SetType(SD, ELF::STT_NOTYPE);
600 MCELF::SetBinding(SD, ELF::STB_LOCAL);
601 SD.setExternal(false);
602 AssignSection(Symbol, getCurrentSection().first);
604 const MCExpr *Value = MCSymbolRefExpr::Create(Start, getContext());
605 Symbol->setVariableValue(Value);
608 void EmitThumbFunc(MCSymbol *Func) {
609 // FIXME: Anything needed here to flag the function as thumb?
611 getAssembler().setIsThumbFunc(Func);
613 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Func);
614 SD.setFlags(SD.getFlags() | ELF_Other_ThumbFunc);
617 // Helper functions for ARM exception handling directives
620 void EmitPersonalityFixup(StringRef Name);
621 void FlushPendingOffset();
622 void FlushUnwindOpcodes(bool NoHandlerData);
624 void SwitchToEHSection(const char *Prefix, unsigned Type, unsigned Flags,
625 SectionKind Kind, const MCSymbol &Fn);
626 void SwitchToExTabSection(const MCSymbol &FnStart);
627 void SwitchToExIdxSection(const MCSymbol &FnStart);
629 void EmitFixup(const MCExpr *Expr, MCFixupKind Kind);
632 int64_t MappingSymbolCounter;
634 DenseMap<const MCSection *, ElfMappingSymbol> LastMappingSymbols;
635 ElfMappingSymbol LastEMS;
637 // ARM Exception Handling Frame Information
640 const MCSymbol *Personality;
641 unsigned PersonalityIndex;
642 unsigned FPReg; // Frame pointer register
643 int64_t FPOffset; // Offset: (final frame pointer) - (initial $sp)
644 int64_t SPOffset; // Offset: (final $sp) - (initial $sp)
645 int64_t PendingOffset; // Offset: (final $sp) - (emitted $sp)
648 SmallVector<uint8_t, 64> Opcodes;
649 UnwindOpcodeAssembler UnwindOpAsm;
651 } // end anonymous namespace
653 ARMELFStreamer &ARMTargetELFStreamer::getStreamer() {
654 return static_cast<ARMELFStreamer &>(Streamer);
657 void ARMTargetELFStreamer::emitFnStart() { getStreamer().emitFnStart(); }
658 void ARMTargetELFStreamer::emitFnEnd() { getStreamer().emitFnEnd(); }
659 void ARMTargetELFStreamer::emitCantUnwind() { getStreamer().emitCantUnwind(); }
660 void ARMTargetELFStreamer::emitPersonality(const MCSymbol *Personality) {
661 getStreamer().emitPersonality(Personality);
663 void ARMTargetELFStreamer::emitPersonalityIndex(unsigned Index) {
664 getStreamer().emitPersonalityIndex(Index);
666 void ARMTargetELFStreamer::emitHandlerData() {
667 getStreamer().emitHandlerData();
669 void ARMTargetELFStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
671 getStreamer().emitSetFP(FpReg, SpReg, Offset);
673 void ARMTargetELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
674 getStreamer().emitMovSP(Reg, Offset);
676 void ARMTargetELFStreamer::emitPad(int64_t Offset) {
677 getStreamer().emitPad(Offset);
679 void ARMTargetELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
681 getStreamer().emitRegSave(RegList, isVector);
683 void ARMTargetELFStreamer::emitUnwindRaw(int64_t Offset,
684 const SmallVectorImpl<uint8_t> &Opcodes) {
685 getStreamer().emitUnwindRaw(Offset, Opcodes);
687 void ARMTargetELFStreamer::switchVendor(StringRef Vendor) {
688 assert(!Vendor.empty() && "Vendor cannot be empty.");
690 if (CurrentVendor == Vendor)
693 if (!CurrentVendor.empty())
694 finishAttributeSection();
696 assert(Contents.empty() &&
697 ".ARM.attributes should be flushed before changing vendor");
698 CurrentVendor = Vendor;
701 void ARMTargetELFStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
702 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
704 void ARMTargetELFStreamer::emitTextAttribute(unsigned Attribute,
706 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
708 void ARMTargetELFStreamer::emitIntTextAttribute(unsigned Attribute,
710 StringRef StringValue) {
711 setAttributeItems(Attribute, IntValue, StringValue,
712 /* OverwriteExisting= */ true);
714 void ARMTargetELFStreamer::emitArch(unsigned Value) {
717 void ARMTargetELFStreamer::emitArchDefaultAttributes() {
718 using namespace ARMBuildAttrs;
719 setAttributeItem(CPU_name, GetArchDefaultCPUName(Arch), false);
720 setAttributeItem(CPU_arch, GetArchDefaultCPUArch(Arch), false);
729 setAttributeItem(ARM_ISA_use, Allowed, false);
737 setAttributeItem(ARM_ISA_use, Allowed, false);
738 setAttributeItem(THUMB_ISA_use, Allowed, false);
742 setAttributeItem(ARM_ISA_use, Allowed, false);
743 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
748 setAttributeItem(ARM_ISA_use, Allowed, false);
749 setAttributeItem(THUMB_ISA_use, Allowed, false);
750 setAttributeItem(Virtualization_use, AllowTZ, false);
754 setAttributeItem(THUMB_ISA_use, Allowed, false);
758 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
762 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
763 setAttributeItem(ARM_ISA_use, Allowed, false);
764 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
768 setAttributeItem(CPU_arch_profile, RealTimeProfile, false);
769 setAttributeItem(ARM_ISA_use, Allowed, false);
770 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
774 setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
775 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
779 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
780 setAttributeItem(ARM_ISA_use, Allowed, false);
781 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
782 setAttributeItem(MPextension_use, Allowed, false);
783 setAttributeItem(Virtualization_use, AllowTZVirtualization, false);
787 setAttributeItem(ARM_ISA_use, Allowed, false);
788 setAttributeItem(THUMB_ISA_use, Allowed, false);
789 setAttributeItem(WMMX_arch, AllowWMMXv1, false);
793 setAttributeItem(ARM_ISA_use, Allowed, false);
794 setAttributeItem(THUMB_ISA_use, Allowed, false);
795 setAttributeItem(WMMX_arch, AllowWMMXv2, false);
799 report_fatal_error("Unknown Arch: " + Twine(Arch));
803 void ARMTargetELFStreamer::emitFPU(unsigned Value) {
806 void ARMTargetELFStreamer::emitFPUDefaultAttributes() {
810 setAttributeItem(ARMBuildAttrs::FP_arch,
811 ARMBuildAttrs::AllowFPv2,
812 /* OverwriteExisting= */ false);
816 setAttributeItem(ARMBuildAttrs::FP_arch,
817 ARMBuildAttrs::AllowFPv3A,
818 /* OverwriteExisting= */ false);
822 setAttributeItem(ARMBuildAttrs::FP_arch,
823 ARMBuildAttrs::AllowFPv3B,
824 /* OverwriteExisting= */ false);
828 setAttributeItem(ARMBuildAttrs::FP_arch,
829 ARMBuildAttrs::AllowFPv4A,
830 /* OverwriteExisting= */ false);
834 setAttributeItem(ARMBuildAttrs::FP_arch,
835 ARMBuildAttrs::AllowFPv4B,
836 /* OverwriteExisting= */ false);
840 setAttributeItem(ARMBuildAttrs::FP_arch,
841 ARMBuildAttrs::AllowFPARMv8A,
842 /* OverwriteExisting= */ false);
846 setAttributeItem(ARMBuildAttrs::FP_arch,
847 ARMBuildAttrs::AllowFPv3A,
848 /* OverwriteExisting= */ false);
849 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
850 ARMBuildAttrs::AllowNeon,
851 /* OverwriteExisting= */ false);
854 case ARM::NEON_VFPV4:
855 setAttributeItem(ARMBuildAttrs::FP_arch,
856 ARMBuildAttrs::AllowFPv4A,
857 /* OverwriteExisting= */ false);
858 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
859 ARMBuildAttrs::AllowNeon2,
860 /* OverwriteExisting= */ false);
863 case ARM::NEON_FP_ARMV8:
864 case ARM::CRYPTO_NEON_FP_ARMV8:
865 setAttributeItem(ARMBuildAttrs::FP_arch,
866 ARMBuildAttrs::AllowFPARMv8A,
867 /* OverwriteExisting= */ false);
868 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
869 ARMBuildAttrs::AllowNeonARMv8,
870 /* OverwriteExisting= */ false);
877 report_fatal_error("Unknown FPU: " + Twine(FPU));
881 size_t ARMTargetELFStreamer::calculateContentSize() const {
883 for (size_t i = 0; i < Contents.size(); ++i) {
884 AttributeItem item = Contents[i];
886 case AttributeItem::HiddenAttribute:
888 case AttributeItem::NumericAttribute:
889 Result += getULEBSize(item.Tag);
890 Result += getULEBSize(item.IntValue);
892 case AttributeItem::TextAttribute:
893 Result += getULEBSize(item.Tag);
894 Result += item.StringValue.size() + 1; // string + '\0'
896 case AttributeItem::NumericAndTextAttributes:
897 Result += getULEBSize(item.Tag);
898 Result += getULEBSize(item.IntValue);
899 Result += item.StringValue.size() + 1; // string + '\0';
905 void ARMTargetELFStreamer::finishAttributeSection() {
907 // [ <section-length> "vendor-name"
908 // [ <file-tag> <size> <attribute>*
909 // | <section-tag> <size> <section-number>* 0 <attribute>*
910 // | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
914 if (FPU != ARM::INVALID_FPU)
915 emitFPUDefaultAttributes();
917 if (Arch != ARM::INVALID_ARCH)
918 emitArchDefaultAttributes();
920 if (Contents.empty())
923 std::sort(Contents.begin(), Contents.end(), AttributeItem::LessTag);
925 ARMELFStreamer &Streamer = getStreamer();
927 // Switch to .ARM.attributes section
928 if (AttributeSection) {
929 Streamer.SwitchSection(AttributeSection);
932 Streamer.getContext().getELFSection(".ARM.attributes",
933 ELF::SHT_ARM_ATTRIBUTES,
935 SectionKind::getMetadata());
936 Streamer.SwitchSection(AttributeSection);
939 Streamer.EmitIntValue(0x41, 1);
942 // Vendor size + Vendor name + '\0'
943 const size_t VendorHeaderSize = 4 + CurrentVendor.size() + 1;
946 const size_t TagHeaderSize = 1 + 4;
948 const size_t ContentsSize = calculateContentSize();
950 Streamer.EmitIntValue(VendorHeaderSize + TagHeaderSize + ContentsSize, 4);
951 Streamer.EmitBytes(CurrentVendor);
952 Streamer.EmitIntValue(0, 1); // '\0'
954 Streamer.EmitIntValue(ARMBuildAttrs::File, 1);
955 Streamer.EmitIntValue(TagHeaderSize + ContentsSize, 4);
957 // Size should have been accounted for already, now
958 // emit each field as its type (ULEB or String)
959 for (size_t i = 0; i < Contents.size(); ++i) {
960 AttributeItem item = Contents[i];
961 Streamer.EmitULEB128IntValue(item.Tag);
963 default: llvm_unreachable("Invalid attribute type");
964 case AttributeItem::NumericAttribute:
965 Streamer.EmitULEB128IntValue(item.IntValue);
967 case AttributeItem::TextAttribute:
968 Streamer.EmitBytes(item.StringValue.upper());
969 Streamer.EmitIntValue(0, 1); // '\0'
971 case AttributeItem::NumericAndTextAttributes:
972 Streamer.EmitULEB128IntValue(item.IntValue);
973 Streamer.EmitBytes(item.StringValue.upper());
974 Streamer.EmitIntValue(0, 1); // '\0'
980 FPU = ARM::INVALID_FPU;
983 ARMTargetELFStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
984 getStreamer().EmitFixup(S, FK_Data_4);
986 void ARMTargetELFStreamer::emitInst(uint32_t Inst, char Suffix) {
987 getStreamer().emitInst(Inst, Suffix);
990 void ARMELFStreamer::FinishImpl() {
991 MCTargetStreamer &TS = *getTargetStreamer();
992 ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
993 ATS.finishAttributeSection();
995 MCELFStreamer::FinishImpl();
998 inline void ARMELFStreamer::SwitchToEHSection(const char *Prefix,
1002 const MCSymbol &Fn) {
1003 const MCSectionELF &FnSection =
1004 static_cast<const MCSectionELF &>(Fn.getSection());
1006 // Create the name for new section
1007 StringRef FnSecName(FnSection.getSectionName());
1008 SmallString<128> EHSecName(Prefix);
1009 if (FnSecName != ".text") {
1010 EHSecName += FnSecName;
1013 // Get .ARM.extab or .ARM.exidx section
1014 const MCSectionELF *EHSection = NULL;
1015 if (const MCSymbol *Group = FnSection.getGroup()) {
1016 EHSection = getContext().getELFSection(
1017 EHSecName, Type, Flags | ELF::SHF_GROUP, Kind,
1018 FnSection.getEntrySize(), Group->getName());
1020 EHSection = getContext().getELFSection(EHSecName, Type, Flags, Kind);
1022 assert(EHSection && "Failed to get the required EH section");
1024 // Switch to .ARM.extab or .ARM.exidx section
1025 SwitchSection(EHSection);
1026 EmitCodeAlignment(4, 0);
1029 inline void ARMELFStreamer::SwitchToExTabSection(const MCSymbol &FnStart) {
1030 SwitchToEHSection(".ARM.extab",
1033 SectionKind::getDataRel(),
1037 inline void ARMELFStreamer::SwitchToExIdxSection(const MCSymbol &FnStart) {
1038 SwitchToEHSection(".ARM.exidx",
1040 ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER,
1041 SectionKind::getDataRel(),
1044 void ARMELFStreamer::EmitFixup(const MCExpr *Expr, MCFixupKind Kind) {
1045 MCDataFragment *Frag = getOrCreateDataFragment();
1046 Frag->getFixups().push_back(MCFixup::Create(Frag->getContents().size(), Expr,
1050 void ARMELFStreamer::Reset() {
1054 PersonalityIndex = ARM::EHABI::NUM_PERSONALITY_INDEX;
1063 UnwindOpAsm.Reset();
1066 void ARMELFStreamer::emitFnStart() {
1067 assert(FnStart == 0);
1068 FnStart = getContext().CreateTempSymbol();
1072 void ARMELFStreamer::emitFnEnd() {
1073 assert(FnStart && ".fnstart must precedes .fnend");
1075 // Emit unwind opcodes if there is no .handlerdata directive
1076 if (!ExTab && !CantUnwind)
1077 FlushUnwindOpcodes(true);
1079 // Emit the exception index table entry
1080 SwitchToExIdxSection(*FnStart);
1082 if (PersonalityIndex < ARM::EHABI::NUM_PERSONALITY_INDEX)
1083 EmitPersonalityFixup(GetAEABIUnwindPersonalityName(PersonalityIndex));
1085 const MCSymbolRefExpr *FnStartRef =
1086 MCSymbolRefExpr::Create(FnStart,
1087 MCSymbolRefExpr::VK_ARM_PREL31,
1090 EmitValue(FnStartRef, 4);
1093 EmitIntValue(ARM::EHABI::EXIDX_CANTUNWIND, 4);
1095 // Emit a reference to the unwind opcodes in the ".ARM.extab" section.
1096 const MCSymbolRefExpr *ExTabEntryRef =
1097 MCSymbolRefExpr::Create(ExTab,
1098 MCSymbolRefExpr::VK_ARM_PREL31,
1100 EmitValue(ExTabEntryRef, 4);
1102 // For the __aeabi_unwind_cpp_pr0, we have to emit the unwind opcodes in
1103 // the second word of exception index table entry. The size of the unwind
1104 // opcodes should always be 4 bytes.
1105 assert(PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0 &&
1106 "Compact model must use __aeabi_cpp_unwind_pr0 as personality");
1107 assert(Opcodes.size() == 4u &&
1108 "Unwind opcode size for __aeabi_cpp_unwind_pr0 must be equal to 4");
1109 EmitBytes(StringRef(reinterpret_cast<const char*>(Opcodes.data()),
1113 // Switch to the section containing FnStart
1114 SwitchSection(&FnStart->getSection());
1116 // Clean exception handling frame information
1120 void ARMELFStreamer::emitCantUnwind() { CantUnwind = true; }
1122 // Add the R_ARM_NONE fixup at the same position
1123 void ARMELFStreamer::EmitPersonalityFixup(StringRef Name) {
1124 const MCSymbol *PersonalitySym = getContext().GetOrCreateSymbol(Name);
1126 const MCSymbolRefExpr *PersonalityRef = MCSymbolRefExpr::Create(
1127 PersonalitySym, MCSymbolRefExpr::VK_ARM_NONE, getContext());
1129 AddValueSymbols(PersonalityRef);
1130 MCDataFragment *DF = getOrCreateDataFragment();
1131 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
1133 MCFixup::getKindForSize(4, false)));
1136 void ARMELFStreamer::FlushPendingOffset() {
1137 if (PendingOffset != 0) {
1138 UnwindOpAsm.EmitSPOffset(-PendingOffset);
1143 void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) {
1144 // Emit the unwind opcode to restore $sp.
1146 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1147 int64_t LastRegSaveSPOffset = SPOffset - PendingOffset;
1148 UnwindOpAsm.EmitSPOffset(LastRegSaveSPOffset - FPOffset);
1149 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1151 FlushPendingOffset();
1154 // Finalize the unwind opcode sequence
1155 UnwindOpAsm.Finalize(PersonalityIndex, Opcodes);
1157 // For compact model 0, we have to emit the unwind opcodes in the .ARM.exidx
1158 // section. Thus, we don't have to create an entry in the .ARM.extab
1160 if (NoHandlerData && PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0)
1163 // Switch to .ARM.extab section.
1164 SwitchToExTabSection(*FnStart);
1166 // Create .ARM.extab label for offset in .ARM.exidx
1168 ExTab = getContext().CreateTempSymbol();
1173 const MCSymbolRefExpr *PersonalityRef =
1174 MCSymbolRefExpr::Create(Personality,
1175 MCSymbolRefExpr::VK_ARM_PREL31,
1178 EmitValue(PersonalityRef, 4);
1181 // Emit unwind opcodes
1182 EmitBytes(StringRef(reinterpret_cast<const char *>(Opcodes.data()),
1185 // According to ARM EHABI section 9.2, if the __aeabi_unwind_cpp_pr1() or
1186 // __aeabi_unwind_cpp_pr2() is used, then the handler data must be emitted
1187 // after the unwind opcodes. The handler data consists of several 32-bit
1188 // words, and should be terminated by zero.
1190 // In case that the .handlerdata directive is not specified by the
1191 // programmer, we should emit zero to terminate the handler data.
1192 if (NoHandlerData && !Personality)
1196 void ARMELFStreamer::emitHandlerData() { FlushUnwindOpcodes(false); }
1198 void ARMELFStreamer::emitPersonality(const MCSymbol *Per) {
1200 UnwindOpAsm.setPersonality(Per);
1203 void ARMELFStreamer::emitPersonalityIndex(unsigned Index) {
1204 assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX && "invalid index");
1205 PersonalityIndex = Index;
1208 void ARMELFStreamer::emitSetFP(unsigned NewFPReg, unsigned NewSPReg,
1210 assert((NewSPReg == ARM::SP || NewSPReg == FPReg) &&
1211 "the operand of .setfp directive should be either $sp or $fp");
1216 if (NewSPReg == ARM::SP)
1217 FPOffset = SPOffset + Offset;
1222 void ARMELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
1223 assert((Reg != ARM::SP && Reg != ARM::PC) &&
1224 "the operand of .movsp cannot be either sp or pc");
1225 assert(FPReg == ARM::SP && "current FP must be SP");
1227 FlushPendingOffset();
1230 FPOffset = SPOffset + Offset;
1232 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1233 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1236 void ARMELFStreamer::emitPad(int64_t Offset) {
1237 // Track the change of the $sp offset
1240 // To squash multiple .pad directives, we should delay the unwind opcode
1241 // until the .save, .vsave, .handlerdata, or .fnend directives.
1242 PendingOffset -= Offset;
1245 void ARMELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
1247 // Collect the registers in the register list
1250 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1251 for (size_t i = 0; i < RegList.size(); ++i) {
1252 unsigned Reg = MRI->getEncodingValue(RegList[i]);
1253 assert(Reg < (IsVector ? 32U : 16U) && "Register out of range");
1254 unsigned Bit = (1u << Reg);
1255 if ((Mask & Bit) == 0) {
1261 // Track the change the $sp offset: For the .save directive, the
1262 // corresponding push instruction will decrease the $sp by (4 * Count).
1263 // For the .vsave directive, the corresponding vpush instruction will
1264 // decrease $sp by (8 * Count).
1265 SPOffset -= Count * (IsVector ? 8 : 4);
1268 FlushPendingOffset();
1270 UnwindOpAsm.EmitVFPRegSave(Mask);
1272 UnwindOpAsm.EmitRegSave(Mask);
1275 void ARMELFStreamer::emitUnwindRaw(int64_t Offset,
1276 const SmallVectorImpl<uint8_t> &Opcodes) {
1277 FlushPendingOffset();
1278 SPOffset = SPOffset - Offset;
1279 UnwindOpAsm.EmitRaw(Opcodes);
1284 MCStreamer *createMCAsmStreamer(MCContext &Ctx, formatted_raw_ostream &OS,
1285 bool isVerboseAsm, bool useLoc, bool useCFI,
1286 bool useDwarfDirectory,
1287 MCInstPrinter *InstPrint, MCCodeEmitter *CE,
1288 MCAsmBackend *TAB, bool ShowInst) {
1290 llvm::createAsmStreamer(Ctx, OS, isVerboseAsm, useLoc, useCFI,
1291 useDwarfDirectory, InstPrint, CE, TAB, ShowInst);
1292 new ARMTargetAsmStreamer(*S, OS, *InstPrint, isVerboseAsm);
1296 MCELFStreamer* createARMELFStreamer(MCContext &Context, MCAsmBackend &TAB,
1297 raw_ostream &OS, MCCodeEmitter *Emitter,
1298 bool RelaxAll, bool NoExecStack,
1300 ARMELFStreamer *S = new ARMELFStreamer(Context, TAB, OS, Emitter, IsThumb);
1301 new ARMTargetELFStreamer(*S);
1302 // FIXME: This should eventually end up somewhere else where more
1303 // intelligent flag decisions can be made. For now we are just maintaining
1304 // the status quo for ARM and setting EF_ARM_EABI_VER5 as the default.
1305 S->getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
1308 S->getAssembler().setRelaxAll(true);
1310 S->getAssembler().setNoExecStack(true);