1 //===- lib/MC/MCELFStreamer.cpp - ELF Object Output -----------------------===//
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 ELF .o object files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/MC/MCELFStreamer.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/MC/MCAssembler.h"
18 #include "llvm/MC/MCAsmBackend.h"
19 #include "llvm/MC/MCCodeEmitter.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCELF.h"
22 #include "llvm/MC/MCELFSymbolFlags.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCInst.h"
25 #include "llvm/MC/MCObjectStreamer.h"
26 #include "llvm/MC/MCSection.h"
27 #include "llvm/MC/MCSectionELF.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCValue.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ELF.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
38 inline void MCELFStreamer::SetSection(StringRef Section, unsigned Type,
39 unsigned Flags, SectionKind Kind) {
40 SwitchSection(getContext().getELFSection(Section, Type, Flags, Kind));
43 inline void MCELFStreamer::SetSectionData() {
46 ELF::SHF_WRITE | ELF::SHF_ALLOC,
47 SectionKind::getDataRel());
48 EmitCodeAlignment(4, 0);
51 inline void MCELFStreamer::SetSectionText() {
54 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
55 SectionKind::getText());
56 EmitCodeAlignment(4, 0);
59 inline void MCELFStreamer::SetSectionBss() {
62 ELF::SHF_WRITE | ELF::SHF_ALLOC,
63 SectionKind::getBSS());
64 EmitCodeAlignment(4, 0);
67 MCELFStreamer::~MCELFStreamer() {
70 void MCELFStreamer::InitToTextSection() {
74 void MCELFStreamer::InitSections() {
75 // This emulates the same behavior of GNU as. This makes it easier
76 // to compare the output as the major sections are in the same order.
83 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
84 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
86 MCObjectStreamer::EmitLabel(Symbol);
88 const MCSectionELF &Section =
89 static_cast<const MCSectionELF&>(Symbol->getSection());
90 MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
91 if (Section.getFlags() & ELF::SHF_TLS)
92 MCELF::SetType(SD, ELF::STT_TLS);
95 void MCELFStreamer::EmitDebugLabel(MCSymbol *Symbol) {
99 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
100 // Let the target do whatever target specific stuff it needs to do.
101 getAssembler().getBackend().handleAssemblerFlag(Flag);
102 // Do any generic stuff we need to do.
104 case MCAF_SyntaxUnified: return; // no-op here.
105 case MCAF_Code16: return; // Change parsing mode; no-op here.
106 case MCAF_Code32: return; // Change parsing mode; no-op here.
107 case MCAF_Code64: return; // Change parsing mode; no-op here.
108 case MCAF_SubsectionsViaSymbols:
109 getAssembler().setSubsectionsViaSymbols(true);
113 llvm_unreachable("invalid assembler flag!");
116 void MCELFStreamer::ChangeSection(const MCSection *Section,
117 const MCExpr *Subsection) {
118 MCSectionData *CurSection = getCurrentSectionData();
119 if (CurSection && CurSection->isBundleLocked())
120 report_fatal_error("Unterminated .bundle_lock when changing a section");
121 const MCSymbol *Grp = static_cast<const MCSectionELF *>(Section)->getGroup();
123 getAssembler().getOrCreateSymbolData(*Grp);
124 this->MCObjectStreamer::ChangeSection(Section, Subsection);
127 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
128 getAssembler().getOrCreateSymbolData(*Symbol);
129 MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
130 AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
131 const MCExpr *Value = MCSymbolRefExpr::Create(Symbol, getContext());
132 Alias->setVariableValue(Value);
135 // When GNU as encounters more than one .type declaration for an object it seems
136 // to use a mechanism similar to the one below to decide which type is actually
137 // used in the object file. The greater of T1 and T2 is selected based on the
138 // following ordering:
139 // STT_NOTYPE < STT_OBJECT < STT_FUNC < STT_GNU_IFUNC < STT_TLS < anything else
140 // If neither T1 < T2 nor T2 < T1 according to this ordering, use T2 (the user
142 static unsigned CombineSymbolTypes(unsigned T1, unsigned T2) {
143 unsigned TypeOrdering[] = {ELF::STT_NOTYPE, ELF::STT_OBJECT, ELF::STT_FUNC,
144 ELF::STT_GNU_IFUNC, ELF::STT_TLS};
145 for (unsigned i = 0; i != array_lengthof(TypeOrdering); ++i) {
146 if (T1 == TypeOrdering[i])
148 if (T2 == TypeOrdering[i])
155 bool MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
156 MCSymbolAttr Attribute) {
157 // Indirect symbols are handled differently, to match how 'as' handles
158 // them. This makes writing matching .o files easier.
159 if (Attribute == MCSA_IndirectSymbol) {
160 // Note that we intentionally cannot use the symbol data here; this is
161 // important for matching the string table that 'as' generates.
162 IndirectSymbolData ISD;
164 ISD.SectionData = getCurrentSectionData();
165 getAssembler().getIndirectSymbols().push_back(ISD);
169 // Adding a symbol attribute always introduces the symbol, note that an
170 // important side effect of calling getOrCreateSymbolData here is to register
171 // the symbol with the assembler.
172 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
174 // The implementation of symbol attributes is designed to match 'as', but it
175 // leaves much to desired. It doesn't really make sense to arbitrarily add and
176 // remove flags, but 'as' allows this (in particular, see .desc).
178 // In the future it might be worth trying to make these operations more well
181 case MCSA_LazyReference:
183 case MCSA_SymbolResolver:
184 case MCSA_PrivateExtern:
185 case MCSA_WeakDefinition:
186 case MCSA_WeakDefAutoPrivate:
188 case MCSA_IndirectSymbol:
191 case MCSA_NoDeadStrip:
192 case MCSA_ELF_TypeGnuUniqueObject:
197 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
198 SD.setExternal(true);
199 BindingExplicitlySet.insert(Symbol);
202 case MCSA_WeakReference:
204 MCELF::SetBinding(SD, ELF::STB_WEAK);
205 SD.setExternal(true);
206 BindingExplicitlySet.insert(Symbol);
210 MCELF::SetBinding(SD, ELF::STB_LOCAL);
211 SD.setExternal(false);
212 BindingExplicitlySet.insert(Symbol);
215 case MCSA_ELF_TypeFunction:
216 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
220 case MCSA_ELF_TypeIndFunction:
221 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
222 ELF::STT_GNU_IFUNC));
225 case MCSA_ELF_TypeObject:
226 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
230 case MCSA_ELF_TypeTLS:
231 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
235 case MCSA_ELF_TypeCommon:
236 // TODO: Emit these as a common symbol.
237 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
241 case MCSA_ELF_TypeNoType:
242 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
247 MCELF::SetVisibility(SD, ELF::STV_PROTECTED);
251 MCELF::SetVisibility(SD, ELF::STV_HIDDEN);
255 MCELF::SetVisibility(SD, ELF::STV_INTERNAL);
262 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
263 unsigned ByteAlignment) {
264 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
266 if (!BindingExplicitlySet.count(Symbol)) {
267 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
268 SD.setExternal(true);
271 MCELF::SetType(SD, ELF::STT_OBJECT);
273 if (MCELF::GetBinding(SD) == ELF_STB_Local) {
274 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
278 SectionKind::getBSS());
280 AssignSection(Symbol, Section);
282 struct LocalCommon L = {&SD, Size, ByteAlignment};
283 LocalCommons.push_back(L);
285 SD.setCommon(Size, ByteAlignment);
288 SD.setSize(MCConstantExpr::Create(Size, getContext()));
291 void MCELFStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
292 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
296 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
297 unsigned ByteAlignment) {
298 // FIXME: Should this be caught and done earlier?
299 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
300 MCELF::SetBinding(SD, ELF::STB_LOCAL);
301 SD.setExternal(false);
302 BindingExplicitlySet.insert(Symbol);
303 EmitCommonSymbol(Symbol, Size, ByteAlignment);
306 void MCELFStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size) {
307 if (getCurrentSectionData()->isBundleLocked())
308 report_fatal_error("Emitting values inside a locked bundle is forbidden");
309 fixSymbolsInTLSFixups(Value);
310 MCObjectStreamer::EmitValueImpl(Value, Size);
313 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
316 unsigned MaxBytesToEmit) {
317 if (getCurrentSectionData()->isBundleLocked())
318 report_fatal_error("Emitting values inside a locked bundle is forbidden");
319 MCObjectStreamer::EmitValueToAlignment(ByteAlignment, Value,
320 ValueSize, MaxBytesToEmit);
323 // Add a symbol for the file name of this module. They start after the
324 // null symbol and don't count as normal symbol, i.e. a non-STT_FILE symbol
325 // with the same name may appear.
326 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
327 getAssembler().addFileName(Filename);
330 void MCELFStreamer::EmitIdent(StringRef IdentString) {
331 const MCSection *Comment = getAssembler().getContext().getELFSection(
332 ".comment", ELF::SHT_PROGBITS, ELF::SHF_MERGE | ELF::SHF_STRINGS,
333 SectionKind::getReadOnly(), 1, "");
335 SwitchSection(Comment);
340 EmitBytes(IdentString);
345 void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
346 switch (expr->getKind()) {
348 cast<MCTargetExpr>(expr)->fixELFSymbolsInTLSFixups(getAssembler());
350 case MCExpr::Constant:
353 case MCExpr::Binary: {
354 const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
355 fixSymbolsInTLSFixups(be->getLHS());
356 fixSymbolsInTLSFixups(be->getRHS());
360 case MCExpr::SymbolRef: {
361 const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
362 switch (symRef.getKind()) {
365 case MCSymbolRefExpr::VK_GOTTPOFF:
366 case MCSymbolRefExpr::VK_INDNTPOFF:
367 case MCSymbolRefExpr::VK_NTPOFF:
368 case MCSymbolRefExpr::VK_GOTNTPOFF:
369 case MCSymbolRefExpr::VK_TLSGD:
370 case MCSymbolRefExpr::VK_TLSLD:
371 case MCSymbolRefExpr::VK_TLSLDM:
372 case MCSymbolRefExpr::VK_TPOFF:
373 case MCSymbolRefExpr::VK_DTPOFF:
374 case MCSymbolRefExpr::VK_ARM_TLSGD:
375 case MCSymbolRefExpr::VK_ARM_TPOFF:
376 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
377 case MCSymbolRefExpr::VK_Mips_TLSGD:
378 case MCSymbolRefExpr::VK_Mips_GOTTPREL:
379 case MCSymbolRefExpr::VK_Mips_TPREL_HI:
380 case MCSymbolRefExpr::VK_Mips_TPREL_LO:
381 case MCSymbolRefExpr::VK_PPC_DTPMOD:
382 case MCSymbolRefExpr::VK_PPC_TPREL:
383 case MCSymbolRefExpr::VK_PPC_TPREL_LO:
384 case MCSymbolRefExpr::VK_PPC_TPREL_HI:
385 case MCSymbolRefExpr::VK_PPC_TPREL_HA:
386 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHER:
387 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHERA:
388 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHEST:
389 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHESTA:
390 case MCSymbolRefExpr::VK_PPC_DTPREL:
391 case MCSymbolRefExpr::VK_PPC_DTPREL_LO:
392 case MCSymbolRefExpr::VK_PPC_DTPREL_HI:
393 case MCSymbolRefExpr::VK_PPC_DTPREL_HA:
394 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHER:
395 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHERA:
396 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHEST:
397 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHESTA:
398 case MCSymbolRefExpr::VK_PPC_GOT_TPREL:
399 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO:
400 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HI:
401 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA:
402 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL:
403 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_LO:
404 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HI:
405 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HA:
406 case MCSymbolRefExpr::VK_PPC_TLS:
407 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD:
408 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO:
409 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HI:
410 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA:
411 case MCSymbolRefExpr::VK_PPC_TLSGD:
412 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD:
413 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO:
414 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HI:
415 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA:
416 case MCSymbolRefExpr::VK_PPC_TLSLD:
419 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
420 MCELF::SetType(SD, ELF::STT_TLS);
425 fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
430 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
431 this->MCObjectStreamer::EmitInstToFragment(Inst);
432 MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
434 for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
435 fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
438 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
439 MCAssembler &Assembler = getAssembler();
440 SmallVector<MCFixup, 4> Fixups;
441 SmallString<256> Code;
442 raw_svector_ostream VecOS(Code);
443 Assembler.getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
446 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
447 fixSymbolsInTLSFixups(Fixups[i].getValue());
449 // There are several possibilities here:
451 // If bundling is disabled, append the encoded instruction to the current data
452 // fragment (or create a new such fragment if the current fragment is not a
455 // If bundling is enabled:
456 // - If we're not in a bundle-locked group, emit the instruction into a
457 // fragment of its own. If there are no fixups registered for the
458 // instruction, emit a MCCompactEncodedInstFragment. Otherwise, emit a
460 // - If we're in a bundle-locked group, append the instruction to the current
461 // data fragment because we want all the instructions in a group to get into
462 // the same fragment. Be careful not to do that for the first instruction in
463 // the group, though.
466 if (Assembler.isBundlingEnabled()) {
467 MCSectionData *SD = getCurrentSectionData();
468 if (SD->isBundleLocked() && !SD->isBundleGroupBeforeFirstInst())
469 // If we are bundle-locked, we re-use the current fragment.
470 // The bundle-locking directive ensures this is a new data fragment.
471 DF = cast<MCDataFragment>(getCurrentFragment());
472 else if (!SD->isBundleLocked() && Fixups.size() == 0) {
473 // Optimize memory usage by emitting the instruction to a
474 // MCCompactEncodedInstFragment when not in a bundle-locked group and
475 // there are no fixups registered.
476 MCCompactEncodedInstFragment *CEIF = new MCCompactEncodedInstFragment();
478 CEIF->getContents().append(Code.begin(), Code.end());
481 DF = new MCDataFragment();
483 if (SD->getBundleLockState() == MCSectionData::BundleLockedAlignToEnd) {
484 // If this is a new fragment created for a bundle-locked group, and the
485 // group was marked as "align_to_end", set a flag in the fragment.
486 DF->setAlignToBundleEnd(true);
490 // We're now emitting an instruction in a bundle group, so this flag has
492 SD->setBundleGroupBeforeFirstInst(false);
494 DF = getOrCreateDataFragment();
497 // Add the fixups and data.
498 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
499 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
500 DF->getFixups().push_back(Fixups[i]);
502 DF->setHasInstructions(true);
503 DF->getContents().append(Code.begin(), Code.end());
506 void MCELFStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
507 assert(AlignPow2 <= 30 && "Invalid bundle alignment");
508 MCAssembler &Assembler = getAssembler();
509 if (Assembler.getBundleAlignSize() == 0 && AlignPow2 > 0)
510 Assembler.setBundleAlignSize(1 << AlignPow2);
512 report_fatal_error(".bundle_align_mode should be only set once per file");
515 void MCELFStreamer::EmitBundleLock(bool AlignToEnd) {
516 MCSectionData *SD = getCurrentSectionData();
520 if (!getAssembler().isBundlingEnabled())
521 report_fatal_error(".bundle_lock forbidden when bundling is disabled");
522 else if (SD->isBundleLocked())
523 report_fatal_error("Nesting of .bundle_lock is forbidden");
525 SD->setBundleLockState(AlignToEnd ? MCSectionData::BundleLockedAlignToEnd :
526 MCSectionData::BundleLocked);
527 SD->setBundleGroupBeforeFirstInst(true);
530 void MCELFStreamer::EmitBundleUnlock() {
531 MCSectionData *SD = getCurrentSectionData();
534 if (!getAssembler().isBundlingEnabled())
535 report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
536 else if (!SD->isBundleLocked())
537 report_fatal_error(".bundle_unlock without matching lock");
538 else if (SD->isBundleGroupBeforeFirstInst())
539 report_fatal_error("Empty bundle-locked group is forbidden");
541 SD->setBundleLockState(MCSectionData::NotBundleLocked);
544 void MCELFStreamer::Flush() {
545 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
546 e = LocalCommons.end();
548 MCSymbolData *SD = i->SD;
549 uint64_t Size = i->Size;
550 unsigned ByteAlignment = i->ByteAlignment;
551 const MCSymbol &Symbol = SD->getSymbol();
552 const MCSection &Section = Symbol.getSection();
554 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
555 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
557 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
560 // Update the maximum alignment of the section if necessary.
561 if (ByteAlignment > SectData.getAlignment())
562 SectData.setAlignment(ByteAlignment);
565 LocalCommons.clear();
568 void MCELFStreamer::FinishImpl() {
569 EmitFrames(NULL, true);
573 this->MCObjectStreamer::FinishImpl();
576 MCStreamer *llvm::createELFStreamer(MCContext &Context,
577 MCTargetStreamer *Streamer,
578 MCAsmBackend &MAB, raw_ostream &OS,
579 MCCodeEmitter *CE, bool RelaxAll,
581 MCELFStreamer *S = new MCELFStreamer(Context, Streamer, MAB, OS, CE);
583 S->getAssembler().setRelaxAll(true);
585 S->getAssembler().setNoExecStack(true);
589 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
590 llvm_unreachable("Generic ELF doesn't support this directive");
593 MCSymbolData &MCELFStreamer::getOrCreateSymbolData(MCSymbol *Symbol) {
594 return getAssembler().getOrCreateSymbolData(*Symbol);
597 void MCELFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
598 llvm_unreachable("ELF doesn't support this directive");
601 void MCELFStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
602 llvm_unreachable("ELF doesn't support this directive");
605 void MCELFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
606 llvm_unreachable("ELF doesn't support this directive");
609 void MCELFStreamer::EmitCOFFSymbolType(int Type) {
610 llvm_unreachable("ELF doesn't support this directive");
613 void MCELFStreamer::EndCOFFSymbolDef() {
614 llvm_unreachable("ELF doesn't support this directive");
617 void MCELFStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
618 uint64_t Size, unsigned ByteAlignment) {
619 llvm_unreachable("ELF doesn't support this directive");
622 void MCELFStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
623 uint64_t Size, unsigned ByteAlignment) {
624 llvm_unreachable("ELF doesn't support this directive");