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/MCCodeEmitter.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCELF.h"
21 #include "llvm/MC/MCELFSymbolFlags.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCObjectStreamer.h"
25 #include "llvm/MC/MCSection.h"
26 #include "llvm/MC/MCSectionELF.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/MC/MCValue.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ELF.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
37 inline void MCELFStreamer::SetSection(StringRef Section, unsigned Type,
38 unsigned Flags, SectionKind Kind) {
39 SwitchSection(getContext().getELFSection(Section, Type, Flags, Kind));
42 inline void MCELFStreamer::SetSectionData() {
45 ELF::SHF_WRITE | ELF::SHF_ALLOC,
46 SectionKind::getDataRel());
47 EmitCodeAlignment(4, 0);
50 inline void MCELFStreamer::SetSectionText() {
53 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
54 SectionKind::getText());
55 EmitCodeAlignment(4, 0);
58 inline void MCELFStreamer::SetSectionBss() {
61 ELF::SHF_WRITE | ELF::SHF_ALLOC,
62 SectionKind::getBSS());
63 EmitCodeAlignment(4, 0);
66 MCELFStreamer::~MCELFStreamer() {
69 void MCELFStreamer::InitToTextSection() {
73 void MCELFStreamer::InitSections() {
74 // This emulates the same behavior of GNU as. This makes it easier
75 // to compare the output as the major sections are in the same order.
82 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
83 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
85 MCObjectStreamer::EmitLabel(Symbol);
87 const MCSectionELF &Section =
88 static_cast<const MCSectionELF&>(Symbol->getSection());
89 MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
90 if (Section.getFlags() & ELF::SHF_TLS)
91 MCELF::SetType(SD, ELF::STT_TLS);
94 void MCELFStreamer::EmitDebugLabel(MCSymbol *Symbol) {
98 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
100 case MCAF_SyntaxUnified: return; // no-op here.
101 case MCAF_Code16: return; // Change parsing mode; no-op here.
102 case MCAF_Code32: return; // Change parsing mode; no-op here.
103 case MCAF_Code64: return; // Change parsing mode; no-op here.
104 case MCAF_SubsectionsViaSymbols:
105 getAssembler().setSubsectionsViaSymbols(true);
109 llvm_unreachable("invalid assembler flag!");
112 void MCELFStreamer::ChangeSection(const MCSection *Section) {
113 MCSectionData *CurSection = getCurrentSectionData();
114 if (CurSection && CurSection->isBundleLocked())
115 report_fatal_error("Unterminated .bundle_lock when changing a section");
116 const MCSymbol *Grp = static_cast<const MCSectionELF *>(Section)->getGroup();
118 getAssembler().getOrCreateSymbolData(*Grp);
119 this->MCObjectStreamer::ChangeSection(Section);
122 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
123 getAssembler().getOrCreateSymbolData(*Symbol);
124 MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
125 AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
126 const MCExpr *Value = MCSymbolRefExpr::Create(Symbol, getContext());
127 Alias->setVariableValue(Value);
130 // When GNU as encounters more than one .type declaration for an object it seems
131 // to use a mechanism similar to the one below to decide which type is actually
132 // used in the object file. The greater of T1 and T2 is selected based on the
133 // following ordering:
134 // STT_NOTYPE < STT_OBJECT < STT_FUNC < STT_GNU_IFUNC < STT_TLS < anything else
135 // If neither T1 < T2 nor T2 < T1 according to this ordering, use T2 (the user
137 static unsigned CombineSymbolTypes(unsigned T1, unsigned T2) {
138 unsigned TypeOrdering[] = {ELF::STT_NOTYPE, ELF::STT_OBJECT, ELF::STT_FUNC,
139 ELF::STT_GNU_IFUNC, ELF::STT_TLS};
140 for (unsigned i = 0; i != array_lengthof(TypeOrdering); ++i) {
141 if (T1 == TypeOrdering[i])
143 if (T2 == TypeOrdering[i])
150 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
151 MCSymbolAttr Attribute) {
152 // Indirect symbols are handled differently, to match how 'as' handles
153 // them. This makes writing matching .o files easier.
154 if (Attribute == MCSA_IndirectSymbol) {
155 // Note that we intentionally cannot use the symbol data here; this is
156 // important for matching the string table that 'as' generates.
157 IndirectSymbolData ISD;
159 ISD.SectionData = getCurrentSectionData();
160 getAssembler().getIndirectSymbols().push_back(ISD);
164 // Adding a symbol attribute always introduces the symbol, note that an
165 // important side effect of calling getOrCreateSymbolData here is to register
166 // the symbol with the assembler.
167 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
169 // The implementation of symbol attributes is designed to match 'as', but it
170 // leaves much to desired. It doesn't really make sense to arbitrarily add and
171 // remove flags, but 'as' allows this (in particular, see .desc).
173 // In the future it might be worth trying to make these operations more well
176 case MCSA_LazyReference:
178 case MCSA_SymbolResolver:
179 case MCSA_PrivateExtern:
180 case MCSA_WeakDefinition:
181 case MCSA_WeakDefAutoPrivate:
183 case MCSA_IndirectSymbol:
184 llvm_unreachable("Invalid symbol attribute for ELF!");
186 case MCSA_NoDeadStrip:
187 case MCSA_ELF_TypeGnuUniqueObject:
192 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
193 SD.setExternal(true);
194 BindingExplicitlySet.insert(Symbol);
197 case MCSA_WeakReference:
199 MCELF::SetBinding(SD, ELF::STB_WEAK);
200 SD.setExternal(true);
201 BindingExplicitlySet.insert(Symbol);
205 MCELF::SetBinding(SD, ELF::STB_LOCAL);
206 SD.setExternal(false);
207 BindingExplicitlySet.insert(Symbol);
210 case MCSA_ELF_TypeFunction:
211 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
215 case MCSA_ELF_TypeIndFunction:
216 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
217 ELF::STT_GNU_IFUNC));
220 case MCSA_ELF_TypeObject:
221 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
225 case MCSA_ELF_TypeTLS:
226 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
230 case MCSA_ELF_TypeCommon:
231 // TODO: Emit these as a common symbol.
232 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
236 case MCSA_ELF_TypeNoType:
237 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
242 MCELF::SetVisibility(SD, ELF::STV_PROTECTED);
246 MCELF::SetVisibility(SD, ELF::STV_HIDDEN);
250 MCELF::SetVisibility(SD, ELF::STV_INTERNAL);
255 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
256 unsigned ByteAlignment) {
257 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
259 if (!BindingExplicitlySet.count(Symbol)) {
260 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
261 SD.setExternal(true);
264 MCELF::SetType(SD, ELF::STT_OBJECT);
266 if (MCELF::GetBinding(SD) == ELF_STB_Local) {
267 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
271 SectionKind::getBSS());
272 Symbol->setSection(*Section);
274 struct LocalCommon L = {&SD, Size, ByteAlignment};
275 LocalCommons.push_back(L);
277 SD.setCommon(Size, ByteAlignment);
280 SD.setSize(MCConstantExpr::Create(Size, getContext()));
283 void MCELFStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
284 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
288 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
289 unsigned ByteAlignment) {
290 // FIXME: Should this be caught and done earlier?
291 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
292 MCELF::SetBinding(SD, ELF::STB_LOCAL);
293 SD.setExternal(false);
294 BindingExplicitlySet.insert(Symbol);
295 EmitCommonSymbol(Symbol, Size, ByteAlignment);
298 void MCELFStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
299 unsigned AddrSpace) {
300 if (getCurrentSectionData()->isBundleLocked())
301 report_fatal_error("Emitting values inside a locked bundle is forbidden");
302 fixSymbolsInTLSFixups(Value);
303 MCObjectStreamer::EmitValueImpl(Value, Size, AddrSpace);
306 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
309 unsigned MaxBytesToEmit) {
310 if (getCurrentSectionData()->isBundleLocked())
311 report_fatal_error("Emitting values inside a locked bundle is forbidden");
312 MCObjectStreamer::EmitValueToAlignment(ByteAlignment, Value,
313 ValueSize, MaxBytesToEmit);
317 // Add a symbol for the file name of this module. This is the second
318 // entry in the module's symbol table (the first being the null symbol).
319 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
320 MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
321 Symbol->setSection(*getCurrentSection());
322 Symbol->setAbsolute();
324 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
326 SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
329 void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
330 switch (expr->getKind()) {
332 cast<MCTargetExpr>(expr)->fixELFSymbolsInTLSFixups(getAssembler());
334 case MCExpr::Constant:
337 case MCExpr::Binary: {
338 const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
339 fixSymbolsInTLSFixups(be->getLHS());
340 fixSymbolsInTLSFixups(be->getRHS());
344 case MCExpr::SymbolRef: {
345 const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
346 switch (symRef.getKind()) {
349 case MCSymbolRefExpr::VK_GOTTPOFF:
350 case MCSymbolRefExpr::VK_INDNTPOFF:
351 case MCSymbolRefExpr::VK_NTPOFF:
352 case MCSymbolRefExpr::VK_GOTNTPOFF:
353 case MCSymbolRefExpr::VK_TLSGD:
354 case MCSymbolRefExpr::VK_TLSLD:
355 case MCSymbolRefExpr::VK_TLSLDM:
356 case MCSymbolRefExpr::VK_TPOFF:
357 case MCSymbolRefExpr::VK_DTPOFF:
358 case MCSymbolRefExpr::VK_ARM_TLSGD:
359 case MCSymbolRefExpr::VK_ARM_TPOFF:
360 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
361 case MCSymbolRefExpr::VK_Mips_TLSGD:
362 case MCSymbolRefExpr::VK_Mips_GOTTPREL:
363 case MCSymbolRefExpr::VK_Mips_TPREL_HI:
364 case MCSymbolRefExpr::VK_Mips_TPREL_LO:
365 case MCSymbolRefExpr::VK_PPC_TPREL16_HA:
366 case MCSymbolRefExpr::VK_PPC_TPREL16_LO:
367 case MCSymbolRefExpr::VK_PPC_DTPREL16_HA:
368 case MCSymbolRefExpr::VK_PPC_DTPREL16_LO:
369 case MCSymbolRefExpr::VK_PPC_GOT_TPREL16_HA:
370 case MCSymbolRefExpr::VK_PPC_GOT_TPREL16_LO:
371 case MCSymbolRefExpr::VK_PPC_TLS:
372 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD16_HA:
373 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD16_LO:
374 case MCSymbolRefExpr::VK_PPC_TLSGD:
375 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD16_HA:
376 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD16_LO:
377 case MCSymbolRefExpr::VK_PPC_TLSLD:
380 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
381 MCELF::SetType(SD, ELF::STT_TLS);
386 fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
391 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
392 this->MCObjectStreamer::EmitInstToFragment(Inst);
393 MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
395 for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
396 fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
399 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
400 MCAssembler &Assembler = getAssembler();
401 SmallVector<MCFixup, 4> Fixups;
402 SmallString<256> Code;
403 raw_svector_ostream VecOS(Code);
404 Assembler.getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
407 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
408 fixSymbolsInTLSFixups(Fixups[i].getValue());
410 // There are several possibilities here:
412 // If bundling is disabled, append the encoded instruction to the current data
413 // fragment (or create a new such fragment if the current fragment is not a
416 // If bundling is enabled:
417 // - If we're not in a bundle-locked group, emit the instruction into a
418 // fragment of its own. If there are no fixups registered for the
419 // instruction, emit a MCCompactEncodedInstFragment. Otherwise, emit a
421 // - If we're in a bundle-locked group, append the instruction to the current
422 // data fragment because we want all the instructions in a group to get into
423 // the same fragment. Be careful not to do that for the first instruction in
424 // the group, though.
427 if (Assembler.isBundlingEnabled()) {
428 MCSectionData *SD = getCurrentSectionData();
429 if (SD->isBundleLocked() && !SD->isBundleGroupBeforeFirstInst())
430 // If we are bundle-locked, we re-use the current fragment.
431 // The bundle-locking directive ensures this is a new data fragment.
432 DF = cast<MCDataFragment>(getCurrentFragment());
433 else if (!SD->isBundleLocked() && Fixups.size() == 0) {
434 // Optimize memory usage by emitting the instruction to a
435 // MCCompactEncodedInstFragment when not in a bundle-locked group and
436 // there are no fixups registered.
437 MCCompactEncodedInstFragment *CEIF = new MCCompactEncodedInstFragment(SD);
438 CEIF->getContents().append(Code.begin(), Code.end());
441 DF = new MCDataFragment(SD);
442 if (SD->getBundleLockState() == MCSectionData::BundleLockedAlignToEnd) {
443 // If this is a new fragment created for a bundle-locked group, and the
444 // group was marked as "align_to_end", set a flag in the fragment.
445 DF->setAlignToBundleEnd(true);
449 // We're now emitting an instruction in a bundle group, so this flag has
451 SD->setBundleGroupBeforeFirstInst(false);
453 DF = getOrCreateDataFragment();
456 // Add the fixups and data.
457 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
458 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
459 DF->getFixups().push_back(Fixups[i]);
461 DF->setHasInstructions(true);
462 DF->getContents().append(Code.begin(), Code.end());
465 void MCELFStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
466 assert(AlignPow2 <= 30 && "Invalid bundle alignment");
467 MCAssembler &Assembler = getAssembler();
468 if (Assembler.getBundleAlignSize() == 0 && AlignPow2 > 0)
469 Assembler.setBundleAlignSize(1 << AlignPow2);
471 report_fatal_error(".bundle_align_mode should be only set once per file");
474 void MCELFStreamer::EmitBundleLock(bool AlignToEnd) {
475 MCSectionData *SD = getCurrentSectionData();
479 if (!getAssembler().isBundlingEnabled())
480 report_fatal_error(".bundle_lock forbidden when bundling is disabled");
481 else if (SD->isBundleLocked())
482 report_fatal_error("Nesting of .bundle_lock is forbidden");
484 SD->setBundleLockState(AlignToEnd ? MCSectionData::BundleLockedAlignToEnd :
485 MCSectionData::BundleLocked);
486 SD->setBundleGroupBeforeFirstInst(true);
489 void MCELFStreamer::EmitBundleUnlock() {
490 MCSectionData *SD = getCurrentSectionData();
493 if (!getAssembler().isBundlingEnabled())
494 report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
495 else if (!SD->isBundleLocked())
496 report_fatal_error(".bundle_unlock without matching lock");
497 else if (SD->isBundleGroupBeforeFirstInst())
498 report_fatal_error("Empty bundle-locked group is forbidden");
500 SD->setBundleLockState(MCSectionData::NotBundleLocked);
503 void MCELFStreamer::FinishImpl() {
506 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
507 e = LocalCommons.end();
509 MCSymbolData *SD = i->SD;
510 uint64_t Size = i->Size;
511 unsigned ByteAlignment = i->ByteAlignment;
512 const MCSymbol &Symbol = SD->getSymbol();
513 const MCSection &Section = Symbol.getSection();
515 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
516 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
518 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
521 // Update the maximum alignment of the section if necessary.
522 if (ByteAlignment > SectData.getAlignment())
523 SectData.setAlignment(ByteAlignment);
526 this->MCObjectStreamer::FinishImpl();
528 void MCELFStreamer::EmitTCEntry(const MCSymbol &S) {
529 // Creates a R_PPC64_TOC relocation
530 MCObjectStreamer::EmitSymbolValue(&S, 8);
533 MCStreamer *llvm::createELFStreamer(MCContext &Context, MCAsmBackend &MAB,
534 raw_ostream &OS, MCCodeEmitter *CE,
535 bool RelaxAll, bool NoExecStack) {
536 MCELFStreamer *S = new MCELFStreamer(Context, MAB, OS, CE);
538 S->getAssembler().setRelaxAll(true);
540 S->getAssembler().setNoExecStack(true);
544 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
545 llvm_unreachable("Generic ELF doesn't support this directive");
548 MCSymbolData &MCELFStreamer::getOrCreateSymbolData(MCSymbol *Symbol) {
549 return getAssembler().getOrCreateSymbolData(*Symbol);
552 void MCELFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
553 llvm_unreachable("ELF doesn't support this directive");
556 void MCELFStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
557 llvm_unreachable("ELF doesn't support this directive");
560 void MCELFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
561 llvm_unreachable("ELF doesn't support this directive");
564 void MCELFStreamer::EmitCOFFSymbolType(int Type) {
565 llvm_unreachable("ELF doesn't support this directive");
568 void MCELFStreamer::EndCOFFSymbolDef() {
569 llvm_unreachable("ELF doesn't support this directive");
572 void MCELFStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
573 uint64_t Size, unsigned ByteAlignment) {
574 llvm_unreachable("ELF doesn't support this directive");
577 void MCELFStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
578 uint64_t Size, unsigned ByteAlignment) {
579 llvm_unreachable("ELF doesn't support this directive");