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/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/MC/MCAsmBackend.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCAssembler.h"
20 #include "llvm/MC/MCCodeEmitter.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCELF.h"
23 #include "llvm/MC/MCELFSymbolFlags.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCInst.h"
26 #include "llvm/MC/MCObjectFileInfo.h"
27 #include "llvm/MC/MCObjectStreamer.h"
28 #include "llvm/MC/MCSection.h"
29 #include "llvm/MC/MCSectionELF.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCValue.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ELF.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
39 MCELFStreamer::~MCELFStreamer() {
42 void MCELFStreamer::InitSections(bool NoExecStack) {
43 // This emulates the same behavior of GNU as. This makes it easier
44 // to compare the output as the major sections are in the same order.
45 MCContext &Ctx = getContext();
46 SwitchSection(Ctx.getObjectFileInfo()->getTextSection());
49 SwitchSection(Ctx.getObjectFileInfo()->getDataSection());
52 SwitchSection(Ctx.getObjectFileInfo()->getBSSSection());
55 SwitchSection(Ctx.getObjectFileInfo()->getTextSection());
58 SwitchSection(Ctx.getAsmInfo()->getNonexecutableStackSection(Ctx));
61 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
62 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
64 MCObjectStreamer::EmitLabel(Symbol);
66 const MCSectionELF &Section =
67 static_cast<const MCSectionELF&>(Symbol->getSection());
68 MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
69 if (Section.getFlags() & ELF::SHF_TLS)
70 MCELF::SetType(SD, ELF::STT_TLS);
73 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
74 // Let the target do whatever target specific stuff it needs to do.
75 getAssembler().getBackend().handleAssemblerFlag(Flag);
76 // Do any generic stuff we need to do.
78 case MCAF_SyntaxUnified: return; // no-op here.
79 case MCAF_Code16: return; // Change parsing mode; no-op here.
80 case MCAF_Code32: return; // Change parsing mode; no-op here.
81 case MCAF_Code64: return; // Change parsing mode; no-op here.
82 case MCAF_SubsectionsViaSymbols:
83 getAssembler().setSubsectionsViaSymbols(true);
87 llvm_unreachable("invalid assembler flag!");
90 void MCELFStreamer::ChangeSection(const MCSection *Section,
91 const MCExpr *Subsection) {
92 MCSectionData *CurSection = getCurrentSectionData();
93 if (CurSection && CurSection->isBundleLocked())
94 report_fatal_error("Unterminated .bundle_lock when changing a section");
96 MCAssembler &Asm = getAssembler();
97 auto *SectionELF = static_cast<const MCSectionELF *>(Section);
98 const MCSymbol *Grp = SectionELF->getGroup();
100 Asm.getOrCreateSymbolData(*Grp);
102 this->MCObjectStreamer::ChangeSection(Section, Subsection);
103 MCSymbol *SectionSymbol = getContext().getOrCreateSectionSymbol(*SectionELF);
104 if (SectionSymbol->isUndefined()) {
105 EmitLabel(SectionSymbol);
106 MCELF::SetType(Asm.getSymbolData(*SectionSymbol), ELF::STT_SECTION);
110 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
111 getAssembler().getOrCreateSymbolData(*Symbol);
112 const MCExpr *Value = MCSymbolRefExpr::Create(
113 Symbol, MCSymbolRefExpr::VK_WEAKREF, getContext());
114 Alias->setVariableValue(Value);
117 // When GNU as encounters more than one .type declaration for an object it seems
118 // to use a mechanism similar to the one below to decide which type is actually
119 // used in the object file. The greater of T1 and T2 is selected based on the
120 // following ordering:
121 // STT_NOTYPE < STT_OBJECT < STT_FUNC < STT_GNU_IFUNC < STT_TLS < anything else
122 // If neither T1 < T2 nor T2 < T1 according to this ordering, use T2 (the user
124 static unsigned CombineSymbolTypes(unsigned T1, unsigned T2) {
125 unsigned TypeOrdering[] = {ELF::STT_NOTYPE, ELF::STT_OBJECT, ELF::STT_FUNC,
126 ELF::STT_GNU_IFUNC, ELF::STT_TLS};
127 for (unsigned i = 0; i != array_lengthof(TypeOrdering); ++i) {
128 if (T1 == TypeOrdering[i])
130 if (T2 == TypeOrdering[i])
137 bool MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
138 MCSymbolAttr Attribute) {
139 // Indirect symbols are handled differently, to match how 'as' handles
140 // them. This makes writing matching .o files easier.
141 if (Attribute == MCSA_IndirectSymbol) {
142 // Note that we intentionally cannot use the symbol data here; this is
143 // important for matching the string table that 'as' generates.
144 IndirectSymbolData ISD;
146 ISD.SectionData = getCurrentSectionData();
147 getAssembler().getIndirectSymbols().push_back(ISD);
151 // Adding a symbol attribute always introduces the symbol, note that an
152 // important side effect of calling getOrCreateSymbolData here is to register
153 // the symbol with the assembler.
154 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
156 // The implementation of symbol attributes is designed to match 'as', but it
157 // leaves much to desired. It doesn't really make sense to arbitrarily add and
158 // remove flags, but 'as' allows this (in particular, see .desc).
160 // In the future it might be worth trying to make these operations more well
163 case MCSA_LazyReference:
165 case MCSA_SymbolResolver:
166 case MCSA_PrivateExtern:
167 case MCSA_WeakDefinition:
168 case MCSA_WeakDefAutoPrivate:
170 case MCSA_IndirectSymbol:
173 case MCSA_NoDeadStrip:
177 case MCSA_ELF_TypeGnuUniqueObject:
178 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD), ELF::STT_OBJECT));
179 MCELF::SetBinding(SD, ELF::STB_GNU_UNIQUE);
180 SD.setExternal(true);
181 BindingExplicitlySet.insert(Symbol);
185 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
186 SD.setExternal(true);
187 BindingExplicitlySet.insert(Symbol);
190 case MCSA_WeakReference:
192 MCELF::SetBinding(SD, ELF::STB_WEAK);
193 SD.setExternal(true);
194 BindingExplicitlySet.insert(Symbol);
198 MCELF::SetBinding(SD, ELF::STB_LOCAL);
199 SD.setExternal(false);
200 BindingExplicitlySet.insert(Symbol);
203 case MCSA_ELF_TypeFunction:
204 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
208 case MCSA_ELF_TypeIndFunction:
209 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
210 ELF::STT_GNU_IFUNC));
213 case MCSA_ELF_TypeObject:
214 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
218 case MCSA_ELF_TypeTLS:
219 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
223 case MCSA_ELF_TypeCommon:
224 // TODO: Emit these as a common symbol.
225 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
229 case MCSA_ELF_TypeNoType:
230 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
235 MCELF::SetVisibility(SD, ELF::STV_PROTECTED);
239 MCELF::SetVisibility(SD, ELF::STV_HIDDEN);
243 MCELF::SetVisibility(SD, ELF::STV_INTERNAL);
250 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
251 unsigned ByteAlignment) {
252 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
254 if (!BindingExplicitlySet.count(Symbol)) {
255 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
256 SD.setExternal(true);
259 MCELF::SetType(SD, ELF::STT_OBJECT);
261 if (MCELF::GetBinding(SD) == ELF_STB_Local) {
262 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
266 SectionKind::getBSS());
268 AssignSection(Symbol, Section);
270 struct LocalCommon L = {&SD, Size, ByteAlignment};
271 LocalCommons.push_back(L);
273 SD.setCommon(Size, ByteAlignment);
276 SD.setSize(MCConstantExpr::Create(Size, getContext()));
279 void MCELFStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
280 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
284 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
285 unsigned ByteAlignment) {
286 // FIXME: Should this be caught and done earlier?
287 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
288 MCELF::SetBinding(SD, ELF::STB_LOCAL);
289 SD.setExternal(false);
290 BindingExplicitlySet.insert(Symbol);
291 EmitCommonSymbol(Symbol, Size, ByteAlignment);
294 void MCELFStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
296 if (getCurrentSectionData()->isBundleLocked())
297 report_fatal_error("Emitting values inside a locked bundle is forbidden");
298 fixSymbolsInTLSFixups(Value);
299 MCObjectStreamer::EmitValueImpl(Value, Size, Loc);
302 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
305 unsigned MaxBytesToEmit) {
306 if (getCurrentSectionData()->isBundleLocked())
307 report_fatal_error("Emitting values inside a locked bundle is forbidden");
308 MCObjectStreamer::EmitValueToAlignment(ByteAlignment, Value,
309 ValueSize, MaxBytesToEmit);
312 // Add a symbol for the file name of this module. They start after the
313 // null symbol and don't count as normal symbol, i.e. a non-STT_FILE symbol
314 // with the same name may appear.
315 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
316 getAssembler().addFileName(Filename);
319 void MCELFStreamer::EmitIdent(StringRef IdentString) {
320 const MCSection *Comment = getAssembler().getContext().getELFSection(
321 ".comment", ELF::SHT_PROGBITS, ELF::SHF_MERGE | ELF::SHF_STRINGS,
322 SectionKind::getReadOnly(), 1, "");
324 SwitchSection(Comment);
329 EmitBytes(IdentString);
334 void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
335 switch (expr->getKind()) {
337 cast<MCTargetExpr>(expr)->fixELFSymbolsInTLSFixups(getAssembler());
339 case MCExpr::Constant:
342 case MCExpr::Binary: {
343 const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
344 fixSymbolsInTLSFixups(be->getLHS());
345 fixSymbolsInTLSFixups(be->getRHS());
349 case MCExpr::SymbolRef: {
350 const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
351 switch (symRef.getKind()) {
354 case MCSymbolRefExpr::VK_GOTTPOFF:
355 case MCSymbolRefExpr::VK_INDNTPOFF:
356 case MCSymbolRefExpr::VK_NTPOFF:
357 case MCSymbolRefExpr::VK_GOTNTPOFF:
358 case MCSymbolRefExpr::VK_TLSGD:
359 case MCSymbolRefExpr::VK_TLSLD:
360 case MCSymbolRefExpr::VK_TLSLDM:
361 case MCSymbolRefExpr::VK_TPOFF:
362 case MCSymbolRefExpr::VK_DTPOFF:
363 case MCSymbolRefExpr::VK_Mips_TLSGD:
364 case MCSymbolRefExpr::VK_Mips_GOTTPREL:
365 case MCSymbolRefExpr::VK_Mips_TPREL_HI:
366 case MCSymbolRefExpr::VK_Mips_TPREL_LO:
367 case MCSymbolRefExpr::VK_PPC_DTPMOD:
368 case MCSymbolRefExpr::VK_PPC_TPREL:
369 case MCSymbolRefExpr::VK_PPC_TPREL_LO:
370 case MCSymbolRefExpr::VK_PPC_TPREL_HI:
371 case MCSymbolRefExpr::VK_PPC_TPREL_HA:
372 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHER:
373 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHERA:
374 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHEST:
375 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHESTA:
376 case MCSymbolRefExpr::VK_PPC_DTPREL:
377 case MCSymbolRefExpr::VK_PPC_DTPREL_LO:
378 case MCSymbolRefExpr::VK_PPC_DTPREL_HI:
379 case MCSymbolRefExpr::VK_PPC_DTPREL_HA:
380 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHER:
381 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHERA:
382 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHEST:
383 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHESTA:
384 case MCSymbolRefExpr::VK_PPC_GOT_TPREL:
385 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO:
386 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HI:
387 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA:
388 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL:
389 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_LO:
390 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HI:
391 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HA:
392 case MCSymbolRefExpr::VK_PPC_TLS:
393 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD:
394 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO:
395 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HI:
396 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA:
397 case MCSymbolRefExpr::VK_PPC_TLSGD:
398 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD:
399 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO:
400 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HI:
401 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA:
402 case MCSymbolRefExpr::VK_PPC_TLSLD:
405 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
406 MCELF::SetType(SD, ELF::STT_TLS);
411 fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
416 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst,
417 const MCSubtargetInfo &STI) {
418 this->MCObjectStreamer::EmitInstToFragment(Inst, STI);
419 MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
421 for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
422 fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
425 void MCELFStreamer::EmitInstToData(const MCInst &Inst,
426 const MCSubtargetInfo &STI) {
427 MCAssembler &Assembler = getAssembler();
428 SmallVector<MCFixup, 4> Fixups;
429 SmallString<256> Code;
430 raw_svector_ostream VecOS(Code);
431 Assembler.getEmitter().EncodeInstruction(Inst, VecOS, Fixups, STI);
434 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
435 fixSymbolsInTLSFixups(Fixups[i].getValue());
437 // There are several possibilities here:
439 // If bundling is disabled, append the encoded instruction to the current data
440 // fragment (or create a new such fragment if the current fragment is not a
443 // If bundling is enabled:
444 // - If we're not in a bundle-locked group, emit the instruction into a
445 // fragment of its own. If there are no fixups registered for the
446 // instruction, emit a MCCompactEncodedInstFragment. Otherwise, emit a
448 // - If we're in a bundle-locked group, append the instruction to the current
449 // data fragment because we want all the instructions in a group to get into
450 // the same fragment. Be careful not to do that for the first instruction in
451 // the group, though.
454 if (Assembler.isBundlingEnabled()) {
455 MCSectionData *SD = getCurrentSectionData();
456 if (SD->isBundleLocked() && !SD->isBundleGroupBeforeFirstInst())
457 // If we are bundle-locked, we re-use the current fragment.
458 // The bundle-locking directive ensures this is a new data fragment.
459 DF = cast<MCDataFragment>(getCurrentFragment());
460 else if (!SD->isBundleLocked() && Fixups.size() == 0) {
461 // Optimize memory usage by emitting the instruction to a
462 // MCCompactEncodedInstFragment when not in a bundle-locked group and
463 // there are no fixups registered.
464 MCCompactEncodedInstFragment *CEIF = new MCCompactEncodedInstFragment();
466 CEIF->getContents().append(Code.begin(), Code.end());
469 DF = new MCDataFragment();
472 if (SD->getBundleLockState() == MCSectionData::BundleLockedAlignToEnd) {
473 // If this fragment is for a group marked "align_to_end", set a flag
474 // in the fragment. This can happen after the fragment has already been
475 // created if there are nested bundle_align groups and an inner one
476 // is the one marked align_to_end.
477 DF->setAlignToBundleEnd(true);
480 // We're now emitting an instruction in a bundle group, so this flag has
482 SD->setBundleGroupBeforeFirstInst(false);
484 DF = getOrCreateDataFragment();
487 // Add the fixups and data.
488 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
489 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
490 DF->getFixups().push_back(Fixups[i]);
492 DF->setHasInstructions(true);
493 DF->getContents().append(Code.begin(), Code.end());
496 void MCELFStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
497 assert(AlignPow2 <= 30 && "Invalid bundle alignment");
498 MCAssembler &Assembler = getAssembler();
499 if (AlignPow2 > 0 && (Assembler.getBundleAlignSize() == 0 ||
500 Assembler.getBundleAlignSize() == 1U << AlignPow2))
501 Assembler.setBundleAlignSize(1U << AlignPow2);
503 report_fatal_error(".bundle_align_mode cannot be changed once set");
506 void MCELFStreamer::EmitBundleLock(bool AlignToEnd) {
507 MCSectionData *SD = getCurrentSectionData();
511 if (!getAssembler().isBundlingEnabled())
512 report_fatal_error(".bundle_lock forbidden when bundling is disabled");
514 if (!SD->isBundleLocked())
515 SD->setBundleGroupBeforeFirstInst(true);
517 SD->setBundleLockState(AlignToEnd ? MCSectionData::BundleLockedAlignToEnd :
518 MCSectionData::BundleLocked);
521 void MCELFStreamer::EmitBundleUnlock() {
522 MCSectionData *SD = getCurrentSectionData();
525 if (!getAssembler().isBundlingEnabled())
526 report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
527 else if (!SD->isBundleLocked())
528 report_fatal_error(".bundle_unlock without matching lock");
529 else if (SD->isBundleGroupBeforeFirstInst())
530 report_fatal_error("Empty bundle-locked group is forbidden");
532 SD->setBundleLockState(MCSectionData::NotBundleLocked);
535 void MCELFStreamer::Flush() {
536 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
537 e = LocalCommons.end();
539 MCSymbolData *SD = i->SD;
540 uint64_t Size = i->Size;
541 unsigned ByteAlignment = i->ByteAlignment;
542 const MCSymbol &Symbol = SD->getSymbol();
543 const MCSection &Section = Symbol.getSection();
545 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
546 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
548 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
551 // Update the maximum alignment of the section if necessary.
552 if (ByteAlignment > SectData.getAlignment())
553 SectData.setAlignment(ByteAlignment);
556 LocalCommons.clear();
559 void MCELFStreamer::FinishImpl() {
564 this->MCObjectStreamer::FinishImpl();
567 MCStreamer *llvm::createELFStreamer(MCContext &Context, MCAsmBackend &MAB,
568 raw_ostream &OS, MCCodeEmitter *CE,
570 MCELFStreamer *S = new MCELFStreamer(Context, MAB, OS, CE);
572 S->getAssembler().setRelaxAll(true);
576 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
577 llvm_unreachable("Generic ELF doesn't support this directive");
580 void MCELFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
581 llvm_unreachable("ELF doesn't support this directive");
584 void MCELFStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
585 llvm_unreachable("ELF doesn't support this directive");
588 void MCELFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
589 llvm_unreachable("ELF doesn't support this directive");
592 void MCELFStreamer::EmitCOFFSymbolType(int Type) {
593 llvm_unreachable("ELF doesn't support this directive");
596 void MCELFStreamer::EndCOFFSymbolDef() {
597 llvm_unreachable("ELF doesn't support this directive");
600 void MCELFStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
601 uint64_t Size, unsigned ByteAlignment) {
602 llvm_unreachable("ELF doesn't support this directive");
605 void MCELFStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
606 uint64_t Size, unsigned ByteAlignment) {
607 llvm_unreachable("ELF doesn't support this directive");