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/MC/MCAssembler.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCELF.h"
20 #include "llvm/MC/MCELFSymbolFlags.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCObjectStreamer.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/MC/MCSectionELF.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCValue.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ELF.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
36 inline void MCELFStreamer::SetSection(StringRef Section, unsigned Type,
37 unsigned Flags, SectionKind Kind) {
38 SwitchSection(getContext().getELFSection(Section, Type, Flags, Kind));
41 inline void MCELFStreamer::SetSectionData() {
44 ELF::SHF_WRITE | ELF::SHF_ALLOC,
45 SectionKind::getDataRel());
46 EmitCodeAlignment(4, 0);
49 inline void MCELFStreamer::SetSectionText() {
52 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
53 SectionKind::getText());
54 EmitCodeAlignment(4, 0);
57 inline void MCELFStreamer::SetSectionBss() {
60 ELF::SHF_WRITE | ELF::SHF_ALLOC,
61 SectionKind::getBSS());
62 EmitCodeAlignment(4, 0);
65 MCELFStreamer::~MCELFStreamer() {
68 void MCELFStreamer::InitToTextSection() {
72 void MCELFStreamer::InitSections() {
73 // This emulates the same behavior of GNU as. This makes it easier
74 // to compare the output as the major sections are in the same order.
81 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
82 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
84 MCObjectStreamer::EmitLabel(Symbol);
86 const MCSectionELF &Section =
87 static_cast<const MCSectionELF&>(Symbol->getSection());
88 MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
89 if (Section.getFlags() & ELF::SHF_TLS)
90 MCELF::SetType(SD, ELF::STT_TLS);
93 void MCELFStreamer::EmitDebugLabel(MCSymbol *Symbol) {
97 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
99 case MCAF_SyntaxUnified: return; // no-op here.
100 case MCAF_Code16: return; // Change parsing mode; no-op here.
101 case MCAF_Code32: return; // Change parsing mode; no-op here.
102 case MCAF_Code64: return; // Change parsing mode; no-op here.
103 case MCAF_SubsectionsViaSymbols:
104 getAssembler().setSubsectionsViaSymbols(true);
108 llvm_unreachable("invalid assembler flag!");
111 void MCELFStreamer::ChangeSection(const MCSection *Section) {
112 MCSectionData *CurSection = getCurrentSectionData();
113 if (CurSection && CurSection->isBundleLocked())
114 report_fatal_error("Unterminated .bundle_lock when changing a section");
115 const MCSymbol *Grp = static_cast<const MCSectionELF *>(Section)->getGroup();
117 getAssembler().getOrCreateSymbolData(*Grp);
118 this->MCObjectStreamer::ChangeSection(Section);
121 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
122 getAssembler().getOrCreateSymbolData(*Symbol);
123 MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
124 AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
125 const MCExpr *Value = MCSymbolRefExpr::Create(Symbol, getContext());
126 Alias->setVariableValue(Value);
129 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
130 MCSymbolAttr Attribute) {
131 // Indirect symbols are handled differently, to match how 'as' handles
132 // them. This makes writing matching .o files easier.
133 if (Attribute == MCSA_IndirectSymbol) {
134 // Note that we intentionally cannot use the symbol data here; this is
135 // important for matching the string table that 'as' generates.
136 IndirectSymbolData ISD;
138 ISD.SectionData = getCurrentSectionData();
139 getAssembler().getIndirectSymbols().push_back(ISD);
143 // Adding a symbol attribute always introduces the symbol, note that an
144 // important side effect of calling getOrCreateSymbolData here is to register
145 // the symbol with the assembler.
146 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
148 // The implementation of symbol attributes is designed to match 'as', but it
149 // leaves much to desired. It doesn't really make sense to arbitrarily add and
150 // remove flags, but 'as' allows this (in particular, see .desc).
152 // In the future it might be worth trying to make these operations more well
155 case MCSA_LazyReference:
157 case MCSA_SymbolResolver:
158 case MCSA_PrivateExtern:
159 case MCSA_WeakDefinition:
160 case MCSA_WeakDefAutoPrivate:
162 case MCSA_IndirectSymbol:
163 llvm_unreachable("Invalid symbol attribute for ELF!");
165 case MCSA_NoDeadStrip:
166 case MCSA_ELF_TypeGnuUniqueObject:
171 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
172 SD.setExternal(true);
173 BindingExplicitlySet.insert(Symbol);
176 case MCSA_WeakReference:
178 MCELF::SetBinding(SD, ELF::STB_WEAK);
179 SD.setExternal(true);
180 BindingExplicitlySet.insert(Symbol);
184 MCELF::SetBinding(SD, ELF::STB_LOCAL);
185 SD.setExternal(false);
186 BindingExplicitlySet.insert(Symbol);
189 case MCSA_ELF_TypeFunction:
190 MCELF::SetType(SD, ELF::STT_FUNC);
193 case MCSA_ELF_TypeIndFunction:
194 MCELF::SetType(SD, ELF::STT_GNU_IFUNC);
197 case MCSA_ELF_TypeObject:
198 MCELF::SetType(SD, ELF::STT_OBJECT);
201 case MCSA_ELF_TypeTLS:
202 MCELF::SetType(SD, ELF::STT_TLS);
205 case MCSA_ELF_TypeCommon:
206 MCELF::SetType(SD, ELF::STT_COMMON);
209 case MCSA_ELF_TypeNoType:
210 MCELF::SetType(SD, ELF::STT_NOTYPE);
214 MCELF::SetVisibility(SD, ELF::STV_PROTECTED);
218 MCELF::SetVisibility(SD, ELF::STV_HIDDEN);
222 MCELF::SetVisibility(SD, ELF::STV_INTERNAL);
227 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
228 unsigned ByteAlignment) {
229 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
231 if (!BindingExplicitlySet.count(Symbol)) {
232 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
233 SD.setExternal(true);
236 MCELF::SetType(SD, ELF::STT_OBJECT);
238 if (MCELF::GetBinding(SD) == ELF_STB_Local) {
239 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
243 SectionKind::getBSS());
244 Symbol->setSection(*Section);
246 struct LocalCommon L = {&SD, Size, ByteAlignment};
247 LocalCommons.push_back(L);
249 SD.setCommon(Size, ByteAlignment);
252 SD.setSize(MCConstantExpr::Create(Size, getContext()));
255 void MCELFStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
256 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
260 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
261 unsigned ByteAlignment) {
262 // FIXME: Should this be caught and done earlier?
263 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
264 MCELF::SetBinding(SD, ELF::STB_LOCAL);
265 SD.setExternal(false);
266 BindingExplicitlySet.insert(Symbol);
267 EmitCommonSymbol(Symbol, Size, ByteAlignment);
270 void MCELFStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
271 unsigned AddrSpace) {
272 if (getCurrentSectionData()->isBundleLocked())
273 report_fatal_error("Emitting values inside a locked bundle is forbidden");
274 fixSymbolsInTLSFixups(Value);
275 MCObjectStreamer::EmitValueImpl(Value, Size, AddrSpace);
278 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
281 unsigned MaxBytesToEmit) {
282 if (getCurrentSectionData()->isBundleLocked())
283 report_fatal_error("Emitting values inside a locked bundle is forbidden");
284 MCObjectStreamer::EmitValueToAlignment(ByteAlignment, Value,
285 ValueSize, MaxBytesToEmit);
289 // Add a symbol for the file name of this module. This is the second
290 // entry in the module's symbol table (the first being the null symbol).
291 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
292 MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
293 Symbol->setSection(*getCurrentSection());
294 Symbol->setAbsolute();
296 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
298 SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
301 void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
302 switch (expr->getKind()) {
304 cast<MCTargetExpr>(expr)->fixELFSymbolsInTLSFixups(getAssembler());
306 case MCExpr::Constant:
309 case MCExpr::Binary: {
310 const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
311 fixSymbolsInTLSFixups(be->getLHS());
312 fixSymbolsInTLSFixups(be->getRHS());
316 case MCExpr::SymbolRef: {
317 const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
318 switch (symRef.getKind()) {
321 case MCSymbolRefExpr::VK_GOTTPOFF:
322 case MCSymbolRefExpr::VK_INDNTPOFF:
323 case MCSymbolRefExpr::VK_NTPOFF:
324 case MCSymbolRefExpr::VK_GOTNTPOFF:
325 case MCSymbolRefExpr::VK_TLSGD:
326 case MCSymbolRefExpr::VK_TLSLD:
327 case MCSymbolRefExpr::VK_TLSLDM:
328 case MCSymbolRefExpr::VK_TPOFF:
329 case MCSymbolRefExpr::VK_DTPOFF:
330 case MCSymbolRefExpr::VK_ARM_TLSGD:
331 case MCSymbolRefExpr::VK_ARM_TPOFF:
332 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
333 case MCSymbolRefExpr::VK_Mips_TLSGD:
334 case MCSymbolRefExpr::VK_Mips_GOTTPREL:
335 case MCSymbolRefExpr::VK_Mips_TPREL_HI:
336 case MCSymbolRefExpr::VK_Mips_TPREL_LO:
339 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
340 MCELF::SetType(SD, ELF::STT_TLS);
345 fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
350 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
351 this->MCObjectStreamer::EmitInstToFragment(Inst);
352 MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
354 for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
355 fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
358 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
359 MCAssembler &Assembler = getAssembler();
360 SmallVector<MCFixup, 4> Fixups;
361 SmallString<256> Code;
362 raw_svector_ostream VecOS(Code);
363 Assembler.getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
366 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
367 fixSymbolsInTLSFixups(Fixups[i].getValue());
369 // There are several possibilities here:
371 // If bundling is disabled, append the encoded instruction to the current data
372 // fragment (or create a new such fragment if the current fragment is not a
375 // If bundling is enabled:
376 // - If we're not in a bundle-locked group, emit the instruction into a
377 // fragment of its own. If there are no fixups registered for the
378 // instruction, emit a MCCompactEncodedInstFragment. Otherwise, emit a
380 // - If we're in a bundle-locked group, append the instruction to the current
381 // data fragment because we want all the instructions in a group to get into
382 // the same fragment. Be careful not to do that for the first instruction in
383 // the group, though.
386 if (Assembler.isBundlingEnabled()) {
387 MCSectionData *SD = getCurrentSectionData();
388 if (SD->isBundleLocked() && !SD->isBundleGroupBeforeFirstInst())
389 // If we are bundle-locked, we re-use the current fragment.
390 // The bundle-locking directive ensures this is a new data fragment.
391 DF = cast<MCDataFragment>(getCurrentFragment());
392 else if (!SD->isBundleLocked() && Fixups.size() == 0) {
393 // Optimize memory usage by emitting the instruction to a
394 // MCCompactEncodedInstFragment when not in a bundle-locked group and
395 // there are no fixups registered.
396 MCCompactEncodedInstFragment *CEIF = new MCCompactEncodedInstFragment(SD);
397 CEIF->getContents().append(Code.begin(), Code.end());
400 DF = new MCDataFragment(SD);
401 if (SD->getBundleLockState() == MCSectionData::BundleLockedAlignToEnd) {
402 // If this is a new fragment created for a bundle-locked group, and the
403 // group was marked as "align_to_end", set a flag in the fragment.
404 DF->setAlignToBundleEnd(true);
408 // We're now emitting an instruction in a bundle group, so this flag has
410 SD->setBundleGroupBeforeFirstInst(false);
412 DF = getOrCreateDataFragment();
415 // Add the fixups and data.
416 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
417 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
418 DF->getFixups().push_back(Fixups[i]);
420 DF->setHasInstructions(true);
421 DF->getContents().append(Code.begin(), Code.end());
424 void MCELFStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
425 assert(AlignPow2 <= 30 && "Invalid bundle alignment");
426 MCAssembler &Assembler = getAssembler();
427 if (Assembler.getBundleAlignSize() == 0 && AlignPow2 > 0)
428 Assembler.setBundleAlignSize(1 << AlignPow2);
430 report_fatal_error(".bundle_align_mode should be only set once per file");
433 void MCELFStreamer::EmitBundleLock(bool AlignToEnd) {
434 MCSectionData *SD = getCurrentSectionData();
438 if (!getAssembler().isBundlingEnabled())
439 report_fatal_error(".bundle_lock forbidden when bundling is disabled");
440 else if (SD->isBundleLocked())
441 report_fatal_error("Nesting of .bundle_lock is forbidden");
443 SD->setBundleLockState(AlignToEnd ? MCSectionData::BundleLockedAlignToEnd :
444 MCSectionData::BundleLocked);
445 SD->setBundleGroupBeforeFirstInst(true);
448 void MCELFStreamer::EmitBundleUnlock() {
449 MCSectionData *SD = getCurrentSectionData();
452 if (!getAssembler().isBundlingEnabled())
453 report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
454 else if (!SD->isBundleLocked())
455 report_fatal_error(".bundle_unlock without matching lock");
456 else if (SD->isBundleGroupBeforeFirstInst())
457 report_fatal_error("Empty bundle-locked group is forbidden");
459 SD->setBundleLockState(MCSectionData::NotBundleLocked);
462 void MCELFStreamer::FinishImpl() {
465 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
466 e = LocalCommons.end();
468 MCSymbolData *SD = i->SD;
469 uint64_t Size = i->Size;
470 unsigned ByteAlignment = i->ByteAlignment;
471 const MCSymbol &Symbol = SD->getSymbol();
472 const MCSection &Section = Symbol.getSection();
474 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
475 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
477 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
480 // Update the maximum alignment of the section if necessary.
481 if (ByteAlignment > SectData.getAlignment())
482 SectData.setAlignment(ByteAlignment);
485 this->MCObjectStreamer::FinishImpl();
487 void MCELFStreamer::EmitTCEntry(const MCSymbol &S) {
488 // Creates a R_PPC64_TOC relocation
489 MCObjectStreamer::EmitSymbolValue(&S, 8);
492 MCStreamer *llvm::createELFStreamer(MCContext &Context, MCAsmBackend &MAB,
493 raw_ostream &OS, MCCodeEmitter *CE,
494 bool RelaxAll, bool NoExecStack) {
495 MCELFStreamer *S = new MCELFStreamer(Context, MAB, OS, CE);
497 S->getAssembler().setRelaxAll(true);
499 S->getAssembler().setNoExecStack(true);
503 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
504 llvm_unreachable("Generic ELF doesn't support this directive");
507 MCSymbolData &MCELFStreamer::getOrCreateSymbolData(MCSymbol *Symbol) {
508 return getAssembler().getOrCreateSymbolData(*Symbol);
511 void MCELFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
512 llvm_unreachable("ELF doesn't support this directive");
515 void MCELFStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
516 llvm_unreachable("ELF doesn't support this directive");
519 void MCELFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
520 llvm_unreachable("ELF doesn't support this directive");
523 void MCELFStreamer::EmitCOFFSymbolType(int Type) {
524 llvm_unreachable("ELF doesn't support this directive");
527 void MCELFStreamer::EndCOFFSymbolDef() {
528 llvm_unreachable("ELF doesn't support this directive");
531 void MCELFStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
532 uint64_t Size, unsigned ByteAlignment) {
533 llvm_unreachable("ELF doesn't support this directive");
536 void MCELFStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
537 uint64_t Size, unsigned ByteAlignment) {
538 llvm_unreachable("ELF doesn't support this directive");