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 const MCExpr *Subsection) {
114 MCSectionData *CurSection = getCurrentSectionData();
115 if (CurSection && CurSection->isBundleLocked())
116 report_fatal_error("Unterminated .bundle_lock when changing a section");
117 const MCSymbol *Grp = static_cast<const MCSectionELF *>(Section)->getGroup();
119 getAssembler().getOrCreateSymbolData(*Grp);
120 this->MCObjectStreamer::ChangeSection(Section, Subsection);
123 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
124 getAssembler().getOrCreateSymbolData(*Symbol);
125 MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
126 AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
127 const MCExpr *Value = MCSymbolRefExpr::Create(Symbol, getContext());
128 Alias->setVariableValue(Value);
131 // When GNU as encounters more than one .type declaration for an object it seems
132 // to use a mechanism similar to the one below to decide which type is actually
133 // used in the object file. The greater of T1 and T2 is selected based on the
134 // following ordering:
135 // STT_NOTYPE < STT_OBJECT < STT_FUNC < STT_GNU_IFUNC < STT_TLS < anything else
136 // If neither T1 < T2 nor T2 < T1 according to this ordering, use T2 (the user
138 static unsigned CombineSymbolTypes(unsigned T1, unsigned T2) {
139 unsigned TypeOrdering[] = {ELF::STT_NOTYPE, ELF::STT_OBJECT, ELF::STT_FUNC,
140 ELF::STT_GNU_IFUNC, ELF::STT_TLS};
141 for (unsigned i = 0; i != array_lengthof(TypeOrdering); ++i) {
142 if (T1 == TypeOrdering[i])
144 if (T2 == TypeOrdering[i])
151 bool MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
152 MCSymbolAttr Attribute) {
153 // Indirect symbols are handled differently, to match how 'as' handles
154 // them. This makes writing matching .o files easier.
155 if (Attribute == MCSA_IndirectSymbol) {
156 // Note that we intentionally cannot use the symbol data here; this is
157 // important for matching the string table that 'as' generates.
158 IndirectSymbolData ISD;
160 ISD.SectionData = getCurrentSectionData();
161 getAssembler().getIndirectSymbols().push_back(ISD);
165 // Adding a symbol attribute always introduces the symbol, note that an
166 // important side effect of calling getOrCreateSymbolData here is to register
167 // the symbol with the assembler.
168 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
170 // The implementation of symbol attributes is designed to match 'as', but it
171 // leaves much to desired. It doesn't really make sense to arbitrarily add and
172 // remove flags, but 'as' allows this (in particular, see .desc).
174 // In the future it might be worth trying to make these operations more well
177 case MCSA_LazyReference:
179 case MCSA_SymbolResolver:
180 case MCSA_PrivateExtern:
181 case MCSA_WeakDefinition:
182 case MCSA_WeakDefAutoPrivate:
184 case MCSA_IndirectSymbol:
187 case MCSA_NoDeadStrip:
188 case MCSA_ELF_TypeGnuUniqueObject:
193 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
194 SD.setExternal(true);
195 BindingExplicitlySet.insert(Symbol);
198 case MCSA_WeakReference:
200 MCELF::SetBinding(SD, ELF::STB_WEAK);
201 SD.setExternal(true);
202 BindingExplicitlySet.insert(Symbol);
206 MCELF::SetBinding(SD, ELF::STB_LOCAL);
207 SD.setExternal(false);
208 BindingExplicitlySet.insert(Symbol);
211 case MCSA_ELF_TypeFunction:
212 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
216 case MCSA_ELF_TypeIndFunction:
217 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
218 ELF::STT_GNU_IFUNC));
221 case MCSA_ELF_TypeObject:
222 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
226 case MCSA_ELF_TypeTLS:
227 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
231 case MCSA_ELF_TypeCommon:
232 // TODO: Emit these as a common symbol.
233 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
237 case MCSA_ELF_TypeNoType:
238 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
243 MCELF::SetVisibility(SD, ELF::STV_PROTECTED);
247 MCELF::SetVisibility(SD, ELF::STV_HIDDEN);
251 MCELF::SetVisibility(SD, ELF::STV_INTERNAL);
258 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
259 unsigned ByteAlignment) {
260 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
262 if (!BindingExplicitlySet.count(Symbol)) {
263 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
264 SD.setExternal(true);
267 MCELF::SetType(SD, ELF::STT_OBJECT);
269 if (MCELF::GetBinding(SD) == ELF_STB_Local) {
270 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
274 SectionKind::getBSS());
276 AssignSection(Symbol, Section);
278 struct LocalCommon L = {&SD, Size, ByteAlignment};
279 LocalCommons.push_back(L);
281 SD.setCommon(Size, ByteAlignment);
284 SD.setSize(MCConstantExpr::Create(Size, getContext()));
287 void MCELFStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
288 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
292 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
293 unsigned ByteAlignment) {
294 // FIXME: Should this be caught and done earlier?
295 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
296 MCELF::SetBinding(SD, ELF::STB_LOCAL);
297 SD.setExternal(false);
298 BindingExplicitlySet.insert(Symbol);
299 EmitCommonSymbol(Symbol, Size, ByteAlignment);
302 void MCELFStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size) {
303 if (getCurrentSectionData()->isBundleLocked())
304 report_fatal_error("Emitting values inside a locked bundle is forbidden");
305 fixSymbolsInTLSFixups(Value);
306 MCObjectStreamer::EmitValueImpl(Value, Size);
309 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
312 unsigned MaxBytesToEmit) {
313 if (getCurrentSectionData()->isBundleLocked())
314 report_fatal_error("Emitting values inside a locked bundle is forbidden");
315 MCObjectStreamer::EmitValueToAlignment(ByteAlignment, Value,
316 ValueSize, MaxBytesToEmit);
320 // Add a symbol for the file name of this module. This is the second
321 // entry in the module's symbol table (the first being the null symbol).
322 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
323 MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
324 Symbol->setSection(*getCurrentSection().first);
325 Symbol->setAbsolute();
327 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
329 SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
332 void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
333 switch (expr->getKind()) {
335 cast<MCTargetExpr>(expr)->fixELFSymbolsInTLSFixups(getAssembler());
337 case MCExpr::Constant:
340 case MCExpr::Binary: {
341 const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
342 fixSymbolsInTLSFixups(be->getLHS());
343 fixSymbolsInTLSFixups(be->getRHS());
347 case MCExpr::SymbolRef: {
348 const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
349 switch (symRef.getKind()) {
352 case MCSymbolRefExpr::VK_GOTTPOFF:
353 case MCSymbolRefExpr::VK_INDNTPOFF:
354 case MCSymbolRefExpr::VK_NTPOFF:
355 case MCSymbolRefExpr::VK_GOTNTPOFF:
356 case MCSymbolRefExpr::VK_TLSGD:
357 case MCSymbolRefExpr::VK_TLSLD:
358 case MCSymbolRefExpr::VK_TLSLDM:
359 case MCSymbolRefExpr::VK_TPOFF:
360 case MCSymbolRefExpr::VK_DTPOFF:
361 case MCSymbolRefExpr::VK_ARM_TLSGD:
362 case MCSymbolRefExpr::VK_ARM_TPOFF:
363 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
364 case MCSymbolRefExpr::VK_Mips_TLSGD:
365 case MCSymbolRefExpr::VK_Mips_GOTTPREL:
366 case MCSymbolRefExpr::VK_Mips_TPREL_HI:
367 case MCSymbolRefExpr::VK_Mips_TPREL_LO:
368 case MCSymbolRefExpr::VK_PPC_DTPMOD:
369 case MCSymbolRefExpr::VK_PPC_TPREL:
370 case MCSymbolRefExpr::VK_PPC_TPREL_LO:
371 case MCSymbolRefExpr::VK_PPC_TPREL_HI:
372 case MCSymbolRefExpr::VK_PPC_TPREL_HA:
373 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHER:
374 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHERA:
375 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHEST:
376 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHESTA:
377 case MCSymbolRefExpr::VK_PPC_DTPREL:
378 case MCSymbolRefExpr::VK_PPC_DTPREL_LO:
379 case MCSymbolRefExpr::VK_PPC_DTPREL_HI:
380 case MCSymbolRefExpr::VK_PPC_DTPREL_HA:
381 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHER:
382 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHERA:
383 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHEST:
384 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHESTA:
385 case MCSymbolRefExpr::VK_PPC_GOT_TPREL:
386 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO:
387 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HI:
388 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA:
389 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL:
390 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_LO:
391 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HI:
392 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HA:
393 case MCSymbolRefExpr::VK_PPC_TLS:
394 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD:
395 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO:
396 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HI:
397 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA:
398 case MCSymbolRefExpr::VK_PPC_TLSGD:
399 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD:
400 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO:
401 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HI:
402 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA:
403 case MCSymbolRefExpr::VK_PPC_TLSLD:
406 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
407 MCELF::SetType(SD, ELF::STT_TLS);
412 fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
417 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
418 this->MCObjectStreamer::EmitInstToFragment(Inst);
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 MCAssembler &Assembler = getAssembler();
427 SmallVector<MCFixup, 4> Fixups;
428 SmallString<256> Code;
429 raw_svector_ostream VecOS(Code);
430 Assembler.getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
433 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
434 fixSymbolsInTLSFixups(Fixups[i].getValue());
436 // There are several possibilities here:
438 // If bundling is disabled, append the encoded instruction to the current data
439 // fragment (or create a new such fragment if the current fragment is not a
442 // If bundling is enabled:
443 // - If we're not in a bundle-locked group, emit the instruction into a
444 // fragment of its own. If there are no fixups registered for the
445 // instruction, emit a MCCompactEncodedInstFragment. Otherwise, emit a
447 // - If we're in a bundle-locked group, append the instruction to the current
448 // data fragment because we want all the instructions in a group to get into
449 // the same fragment. Be careful not to do that for the first instruction in
450 // the group, though.
453 if (Assembler.isBundlingEnabled()) {
454 MCSectionData *SD = getCurrentSectionData();
455 if (SD->isBundleLocked() && !SD->isBundleGroupBeforeFirstInst())
456 // If we are bundle-locked, we re-use the current fragment.
457 // The bundle-locking directive ensures this is a new data fragment.
458 DF = cast<MCDataFragment>(getCurrentFragment());
459 else if (!SD->isBundleLocked() && Fixups.size() == 0) {
460 // Optimize memory usage by emitting the instruction to a
461 // MCCompactEncodedInstFragment when not in a bundle-locked group and
462 // there are no fixups registered.
463 MCCompactEncodedInstFragment *CEIF = new MCCompactEncodedInstFragment();
465 CEIF->getContents().append(Code.begin(), Code.end());
468 DF = new MCDataFragment();
470 if (SD->getBundleLockState() == MCSectionData::BundleLockedAlignToEnd) {
471 // If this is a new fragment created for a bundle-locked group, and the
472 // group was marked as "align_to_end", set a flag in the fragment.
473 DF->setAlignToBundleEnd(true);
477 // We're now emitting an instruction in a bundle group, so this flag has
479 SD->setBundleGroupBeforeFirstInst(false);
481 DF = getOrCreateDataFragment();
484 // Add the fixups and data.
485 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
486 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
487 DF->getFixups().push_back(Fixups[i]);
489 DF->setHasInstructions(true);
490 DF->getContents().append(Code.begin(), Code.end());
493 void MCELFStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
494 assert(AlignPow2 <= 30 && "Invalid bundle alignment");
495 MCAssembler &Assembler = getAssembler();
496 if (Assembler.getBundleAlignSize() == 0 && AlignPow2 > 0)
497 Assembler.setBundleAlignSize(1 << AlignPow2);
499 report_fatal_error(".bundle_align_mode should be only set once per file");
502 void MCELFStreamer::EmitBundleLock(bool AlignToEnd) {
503 MCSectionData *SD = getCurrentSectionData();
507 if (!getAssembler().isBundlingEnabled())
508 report_fatal_error(".bundle_lock forbidden when bundling is disabled");
509 else if (SD->isBundleLocked())
510 report_fatal_error("Nesting of .bundle_lock is forbidden");
512 SD->setBundleLockState(AlignToEnd ? MCSectionData::BundleLockedAlignToEnd :
513 MCSectionData::BundleLocked);
514 SD->setBundleGroupBeforeFirstInst(true);
517 void MCELFStreamer::EmitBundleUnlock() {
518 MCSectionData *SD = getCurrentSectionData();
521 if (!getAssembler().isBundlingEnabled())
522 report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
523 else if (!SD->isBundleLocked())
524 report_fatal_error(".bundle_unlock without matching lock");
525 else if (SD->isBundleGroupBeforeFirstInst())
526 report_fatal_error("Empty bundle-locked group is forbidden");
528 SD->setBundleLockState(MCSectionData::NotBundleLocked);
531 void MCELFStreamer::Flush() {
532 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
533 e = LocalCommons.end();
535 MCSymbolData *SD = i->SD;
536 uint64_t Size = i->Size;
537 unsigned ByteAlignment = i->ByteAlignment;
538 const MCSymbol &Symbol = SD->getSymbol();
539 const MCSection &Section = Symbol.getSection();
541 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
542 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
544 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
547 // Update the maximum alignment of the section if necessary.
548 if (ByteAlignment > SectData.getAlignment())
549 SectData.setAlignment(ByteAlignment);
552 LocalCommons.clear();
555 void MCELFStreamer::FinishImpl() {
556 EmitFrames(NULL, true);
560 this->MCObjectStreamer::FinishImpl();
563 void MCELFStreamer::EmitTCEntry(const MCSymbol &S) {
564 // Creates a R_PPC64_TOC relocation
565 MCObjectStreamer::EmitSymbolValue(&S, 8);
568 MCStreamer *llvm::createELFStreamer(MCContext &Context, MCAsmBackend &MAB,
569 raw_ostream &OS, MCCodeEmitter *CE,
570 bool RelaxAll, bool NoExecStack) {
571 MCELFStreamer *S = new MCELFStreamer(Context, MAB, OS, CE);
573 S->getAssembler().setRelaxAll(true);
575 S->getAssembler().setNoExecStack(true);
579 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
580 llvm_unreachable("Generic ELF doesn't support this directive");
583 MCSymbolData &MCELFStreamer::getOrCreateSymbolData(MCSymbol *Symbol) {
584 return getAssembler().getOrCreateSymbolData(*Symbol);
587 void MCELFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
588 llvm_unreachable("ELF doesn't support this directive");
591 void MCELFStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
592 llvm_unreachable("ELF doesn't support this directive");
595 void MCELFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
596 llvm_unreachable("ELF doesn't support this directive");
599 void MCELFStreamer::EmitCOFFSymbolType(int Type) {
600 llvm_unreachable("ELF doesn't support this directive");
603 void MCELFStreamer::EndCOFFSymbolDef() {
604 llvm_unreachable("ELF doesn't support this directive");
607 void MCELFStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
608 uint64_t Size, unsigned ByteAlignment) {
609 llvm_unreachable("ELF doesn't support this directive");
612 void MCELFStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
613 uint64_t Size, unsigned ByteAlignment) {
614 llvm_unreachable("ELF doesn't support this directive");