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 "ARMUnwindOp.h"
18 #include "ARMUnwindOpAsm.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/MC/MCAsmBackend.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/MCObjectStreamer.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCSection.h"
33 #include "llvm/MC/MCSectionELF.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/MC/MCValue.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ELF.h"
39 #include "llvm/Support/raw_ostream.h"
43 static std::string GetAEABIUnwindPersonalityName(unsigned Index) {
44 assert(Index < NUM_PERSONALITY_INDEX && "Invalid personality index");
45 return (Twine("__aeabi_unwind_cpp_pr") + Twine(Index)).str();
50 /// Extend the generic ELFStreamer class so that it can emit mapping symbols at
51 /// the appropriate points in the object files. These symbols are defined in the
52 /// ARM ELF ABI: infocenter.arm.com/help/topic/com.arm.../IHI0044D_aaelf.pdf.
54 /// In brief: $a, $t or $d should be emitted at the start of each contiguous
55 /// region of ARM code, Thumb code or data in a section. In practice, this
56 /// emission does not rely on explicit assembler directives but on inherent
57 /// properties of the directives doing the emission (e.g. ".byte" is data, "add
58 /// r0, r0, r0" an instruction).
60 /// As a result this system is orthogonal to the DataRegion infrastructure used
62 class ARMELFStreamer : public MCELFStreamer {
64 ARMELFStreamer(MCContext &Context, MCAsmBackend &TAB, raw_ostream &OS,
65 MCCodeEmitter *Emitter, bool IsThumb)
66 : MCELFStreamer(Context, TAB, OS, Emitter), IsThumb(IsThumb),
67 MappingSymbolCounter(0), LastEMS(EMS_None) {
73 // ARM exception handling directives
74 virtual void EmitFnStart();
75 virtual void EmitFnEnd();
76 virtual void EmitCantUnwind();
77 virtual void EmitPersonality(const MCSymbol *Per);
78 virtual void EmitHandlerData();
79 virtual void EmitSetFP(unsigned NewFpReg,
82 virtual void EmitPad(int64_t Offset);
83 virtual void EmitRegSave(const SmallVectorImpl<unsigned> &RegList,
86 virtual void ChangeSection(const MCSection *Section,
87 const MCExpr *Subsection) {
88 // We have to keep track of the mapping symbol state of any sections we
89 // use. Each one should start off as EMS_None, which is provided as the
90 // default constructor by DenseMap::lookup.
91 LastMappingSymbols[getPreviousSection().first] = LastEMS;
92 LastEMS = LastMappingSymbols.lookup(Section);
94 MCELFStreamer::ChangeSection(Section, Subsection);
97 /// This function is the one used to emit instruction data into the ELF
98 /// streamer. We override it to add the appropriate mapping symbol if
100 virtual void EmitInstruction(const MCInst& Inst) {
102 EmitThumbMappingSymbol();
104 EmitARMMappingSymbol();
106 MCELFStreamer::EmitInstruction(Inst);
109 /// This is one of the functions used to emit data into an ELF section, so the
110 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
112 virtual void EmitBytes(StringRef Data) {
113 EmitDataMappingSymbol();
114 MCELFStreamer::EmitBytes(Data);
117 /// This is one of the functions used to emit data into an ELF section, so the
118 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
120 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {
121 EmitDataMappingSymbol();
122 MCELFStreamer::EmitValueImpl(Value, Size);
125 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {
126 MCELFStreamer::EmitAssemblerFlag(Flag);
129 case MCAF_SyntaxUnified:
130 return; // no-op here.
133 return; // Change to Thumb mode
136 return; // Change to ARM mode
139 case MCAF_SubsectionsViaSymbols:
145 enum ElfMappingSymbol {
152 void EmitDataMappingSymbol() {
153 if (LastEMS == EMS_Data) return;
154 EmitMappingSymbol("$d");
158 void EmitThumbMappingSymbol() {
159 if (LastEMS == EMS_Thumb) return;
160 EmitMappingSymbol("$t");
164 void EmitARMMappingSymbol() {
165 if (LastEMS == EMS_ARM) return;
166 EmitMappingSymbol("$a");
170 void EmitMappingSymbol(StringRef Name) {
171 MCSymbol *Start = getContext().CreateTempSymbol();
175 getContext().GetOrCreateSymbol(Name + "." +
176 Twine(MappingSymbolCounter++));
178 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
179 MCELF::SetType(SD, ELF::STT_NOTYPE);
180 MCELF::SetBinding(SD, ELF::STB_LOCAL);
181 SD.setExternal(false);
182 AssignSection(Symbol, getCurrentSection().first);
184 const MCExpr *Value = MCSymbolRefExpr::Create(Start, getContext());
185 Symbol->setVariableValue(Value);
188 void EmitThumbFunc(MCSymbol *Func) {
189 // FIXME: Anything needed here to flag the function as thumb?
191 getAssembler().setIsThumbFunc(Func);
193 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Func);
194 SD.setFlags(SD.getFlags() | ELF_Other_ThumbFunc);
197 // Helper functions for ARM exception handling directives
200 void EmitPersonalityFixup(StringRef Name);
201 void FlushPendingOffset();
202 void FlushUnwindOpcodes(bool NoHandlerData);
204 void SwitchToEHSection(const char *Prefix, unsigned Type, unsigned Flags,
205 SectionKind Kind, const MCSymbol &Fn);
206 void SwitchToExTabSection(const MCSymbol &FnStart);
207 void SwitchToExIdxSection(const MCSymbol &FnStart);
210 int64_t MappingSymbolCounter;
212 DenseMap<const MCSection *, ElfMappingSymbol> LastMappingSymbols;
213 ElfMappingSymbol LastEMS;
215 // ARM Exception Handling Frame Information
218 const MCSymbol *Personality;
219 unsigned PersonalityIndex;
220 unsigned FPReg; // Frame pointer register
221 int64_t FPOffset; // Offset: (final frame pointer) - (initial $sp)
222 int64_t SPOffset; // Offset: (final $sp) - (initial $sp)
223 int64_t PendingOffset; // Offset: (final $sp) - (emitted $sp)
226 SmallVector<uint8_t, 64> Opcodes;
227 UnwindOpcodeAssembler UnwindOpAsm;
229 } // end anonymous namespace
231 inline void ARMELFStreamer::SwitchToEHSection(const char *Prefix,
235 const MCSymbol &Fn) {
236 const MCSectionELF &FnSection =
237 static_cast<const MCSectionELF &>(Fn.getSection());
239 // Create the name for new section
240 StringRef FnSecName(FnSection.getSectionName());
241 SmallString<128> EHSecName(Prefix);
242 if (FnSecName != ".text") {
243 EHSecName += FnSecName;
246 // Get .ARM.extab or .ARM.exidx section
247 const MCSectionELF *EHSection = NULL;
248 if (const MCSymbol *Group = FnSection.getGroup()) {
249 EHSection = getContext().getELFSection(
250 EHSecName, Type, Flags | ELF::SHF_GROUP, Kind,
251 FnSection.getEntrySize(), Group->getName());
253 EHSection = getContext().getELFSection(EHSecName, Type, Flags, Kind);
255 assert(EHSection && "Failed to get the required EH section");
257 // Switch to .ARM.extab or .ARM.exidx section
258 SwitchSection(EHSection);
259 EmitCodeAlignment(4, 0);
262 inline void ARMELFStreamer::SwitchToExTabSection(const MCSymbol &FnStart) {
263 SwitchToEHSection(".ARM.extab",
266 SectionKind::getDataRel(),
270 inline void ARMELFStreamer::SwitchToExIdxSection(const MCSymbol &FnStart) {
271 SwitchToEHSection(".ARM.exidx",
273 ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER,
274 SectionKind::getDataRel(),
278 void ARMELFStreamer::Reset() {
282 PersonalityIndex = NUM_PERSONALITY_INDEX;
294 // Add the R_ARM_NONE fixup at the same position
295 void ARMELFStreamer::EmitPersonalityFixup(StringRef Name) {
296 const MCSymbol *PersonalitySym = getContext().GetOrCreateSymbol(Name);
298 const MCSymbolRefExpr *PersonalityRef =
299 MCSymbolRefExpr::Create(PersonalitySym,
300 MCSymbolRefExpr::VK_ARM_NONE,
303 AddValueSymbols(PersonalityRef);
304 MCDataFragment *DF = getOrCreateDataFragment();
305 DF->getFixups().push_back(
306 MCFixup::Create(DF->getContents().size(), PersonalityRef,
307 MCFixup::getKindForSize(4, false)));
310 void ARMELFStreamer::EmitFnStart() {
311 assert(FnStart == 0);
312 FnStart = getContext().CreateTempSymbol();
316 void ARMELFStreamer::EmitFnEnd() {
317 assert(FnStart && ".fnstart must preceeds .fnend");
319 // Emit unwind opcodes if there is no .handlerdata directive
320 if (!ExTab && !CantUnwind)
321 FlushUnwindOpcodes(true);
323 // Emit the exception index table entry
324 SwitchToExIdxSection(*FnStart);
326 if (PersonalityIndex < NUM_PERSONALITY_INDEX)
327 EmitPersonalityFixup(GetAEABIUnwindPersonalityName(PersonalityIndex));
329 const MCSymbolRefExpr *FnStartRef =
330 MCSymbolRefExpr::Create(FnStart,
331 MCSymbolRefExpr::VK_ARM_PREL31,
334 EmitValue(FnStartRef, 4);
337 EmitIntValue(EXIDX_CANTUNWIND, 4);
339 // Emit a reference to the unwind opcodes in the ".ARM.extab" section.
340 const MCSymbolRefExpr *ExTabEntryRef =
341 MCSymbolRefExpr::Create(ExTab,
342 MCSymbolRefExpr::VK_ARM_PREL31,
344 EmitValue(ExTabEntryRef, 4);
346 // For the __aeabi_unwind_cpp_pr0, we have to emit the unwind opcodes in
347 // the second word of exception index table entry. The size of the unwind
348 // opcodes should always be 4 bytes.
349 assert(PersonalityIndex == AEABI_UNWIND_CPP_PR0 &&
350 "Compact model must use __aeabi_cpp_unwind_pr0 as personality");
351 assert(Opcodes.size() == 4u &&
352 "Unwind opcode size for __aeabi_cpp_unwind_pr0 must be equal to 4");
353 EmitBytes(StringRef(reinterpret_cast<const char*>(Opcodes.data()),
357 // Switch to the section containing FnStart
358 SwitchSection(&FnStart->getSection());
360 // Clean exception handling frame information
364 void ARMELFStreamer::EmitCantUnwind() {
368 void ARMELFStreamer::FlushPendingOffset() {
369 if (PendingOffset != 0) {
370 UnwindOpAsm.EmitSPOffset(-PendingOffset);
375 void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) {
376 // Emit the unwind opcode to restore $sp.
378 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
379 int64_t LastRegSaveSPOffset = SPOffset - PendingOffset;
380 UnwindOpAsm.EmitSPOffset(LastRegSaveSPOffset - FPOffset);
381 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
383 FlushPendingOffset();
386 // Finalize the unwind opcode sequence
387 UnwindOpAsm.Finalize(PersonalityIndex, Opcodes);
389 // For compact model 0, we have to emit the unwind opcodes in the .ARM.exidx
390 // section. Thus, we don't have to create an entry in the .ARM.extab
392 if (NoHandlerData && PersonalityIndex == AEABI_UNWIND_CPP_PR0)
395 // Switch to .ARM.extab section.
396 SwitchToExTabSection(*FnStart);
398 // Create .ARM.extab label for offset in .ARM.exidx
400 ExTab = getContext().CreateTempSymbol();
405 const MCSymbolRefExpr *PersonalityRef =
406 MCSymbolRefExpr::Create(Personality,
407 MCSymbolRefExpr::VK_ARM_PREL31,
410 EmitValue(PersonalityRef, 4);
413 // Emit unwind opcodes
414 EmitBytes(StringRef(reinterpret_cast<const char *>(Opcodes.data()),
417 // According to ARM EHABI section 9.2, if the __aeabi_unwind_cpp_pr1() or
418 // __aeabi_unwind_cpp_pr2() is used, then the handler data must be emitted
419 // after the unwind opcodes. The handler data consists of several 32-bit
420 // words, and should be terminated by zero.
422 // In case that the .handlerdata directive is not specified by the
423 // programmer, we should emit zero to terminate the handler data.
424 if (NoHandlerData && !Personality)
428 void ARMELFStreamer::EmitHandlerData() {
429 FlushUnwindOpcodes(false);
432 void ARMELFStreamer::EmitPersonality(const MCSymbol *Per) {
434 UnwindOpAsm.setPersonality(Per);
437 void ARMELFStreamer::EmitSetFP(unsigned NewFPReg,
440 assert((NewSPReg == ARM::SP || NewSPReg == FPReg) &&
441 "the operand of .setfp directive should be either $sp or $fp");
446 if (NewSPReg == ARM::SP)
447 FPOffset = SPOffset + Offset;
452 void ARMELFStreamer::EmitPad(int64_t Offset) {
453 // Track the change of the $sp offset
456 // To squash multiple .pad directives, we should delay the unwind opcode
457 // until the .save, .vsave, .handlerdata, or .fnend directives.
458 PendingOffset -= Offset;
461 void ARMELFStreamer::EmitRegSave(const SmallVectorImpl<unsigned> &RegList,
463 // Collect the registers in the register list
466 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
467 for (size_t i = 0; i < RegList.size(); ++i) {
468 unsigned Reg = MRI->getEncodingValue(RegList[i]);
469 assert(Reg < (IsVector ? 32U : 16U) && "Register out of range");
470 unsigned Bit = (1u << Reg);
471 if ((Mask & Bit) == 0) {
477 // Track the change the $sp offset: For the .save directive, the
478 // corresponding push instruction will decrease the $sp by (4 * Count).
479 // For the .vsave directive, the corresponding vpush instruction will
480 // decrease $sp by (8 * Count).
481 SPOffset -= Count * (IsVector ? 8 : 4);
484 FlushPendingOffset();
486 UnwindOpAsm.EmitVFPRegSave(Mask);
488 UnwindOpAsm.EmitRegSave(Mask);
492 MCELFStreamer* createARMELFStreamer(MCContext &Context, MCAsmBackend &TAB,
493 raw_ostream &OS, MCCodeEmitter *Emitter,
494 bool RelaxAll, bool NoExecStack,
496 ARMELFStreamer *S = new ARMELFStreamer(Context, TAB, OS, Emitter, IsThumb);
497 // FIXME: This should eventually end up somewhere else where more
498 // intelligent flag decisions can be made. For now we are just maintaining
499 // the status quo for ARM and setting EF_ARM_EABI_VER5 as the default.
500 S->getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
503 S->getAssembler().setRelaxAll(true);
505 S->getAssembler().setNoExecStack(true);