LLVM 20.0.0git
MCELFStreamer.cpp
Go to the documentation of this file.
1//===- lib/MC/MCELFStreamer.cpp - ELF Object Output -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file assembles .s files and emits ELF .o object files.
10//
11//===----------------------------------------------------------------------===//
12
17#include "llvm/MC/MCAsmInfo.h"
18#include "llvm/MC/MCAssembler.h"
20#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCExpr.h"
23#include "llvm/MC/MCFixup.h"
24#include "llvm/MC/MCFragment.h"
27#include "llvm/MC/MCSection.h"
29#include "llvm/MC/MCStreamer.h"
30#include "llvm/MC/MCSymbol.h"
31#include "llvm/MC/MCSymbolELF.h"
35#include "llvm/Support/LEB128.h"
36#include <cassert>
37#include <cstdint>
38
39using namespace llvm;
40
42 std::unique_ptr<MCAsmBackend> TAB,
43 std::unique_ptr<MCObjectWriter> OW,
44 std::unique_ptr<MCCodeEmitter> Emitter)
45 : MCObjectStreamer(Context, std::move(TAB), std::move(OW),
46 std::move(Emitter)) {}
47
49 return static_cast<ELFObjectWriter &>(getAssembler().getWriter());
50}
51
52bool MCELFStreamer::isBundleLocked() const {
54}
55
56void MCELFStreamer::initSections(bool NoExecStack, const MCSubtargetInfo &STI) {
57 MCContext &Ctx = getContext();
60 &STI);
61
62 if (NoExecStack)
64}
65
67 auto *Symbol = cast<MCSymbolELF>(S);
68 MCObjectStreamer::emitLabel(Symbol, Loc);
69
70 const MCSectionELF &Section =
71 static_cast<const MCSectionELF &>(*getCurrentSectionOnly());
72 if (Section.getFlags() & ELF::SHF_TLS)
73 Symbol->setType(ELF::STT_TLS);
74}
75
78 auto *Symbol = cast<MCSymbolELF>(S);
80
81 const MCSectionELF &Section =
82 static_cast<const MCSectionELF &>(*getCurrentSectionOnly());
83 if (Section.getFlags() & ELF::SHF_TLS)
84 Symbol->setType(ELF::STT_TLS);
85}
86
88 // Let the target do whatever target specific stuff it needs to do.
90}
91
92// If bundle alignment is used and there are any instructions in the section, it
93// needs to be aligned to at least the bundle size.
94static void setSectionAlignmentForBundling(const MCAssembler &Assembler,
95 MCSection *Section) {
96 if (Assembler.isBundlingEnabled() && Section->hasInstructions())
97 Section->ensureMinAlignment(Align(Assembler.getBundleAlignSize()));
98}
99
101 MCAssembler &Asm = getAssembler();
102 if (auto *F = getCurrentFragment()) {
103 if (isBundleLocked())
104 report_fatal_error("Unterminated .bundle_lock when changing a section");
105
106 // Ensure the previous section gets aligned if necessary.
107 setSectionAlignmentForBundling(Asm, F->getParent());
108 }
109 auto *SectionELF = static_cast<const MCSectionELF *>(Section);
110 const MCSymbol *Grp = SectionELF->getGroup();
111 if (Grp)
112 Asm.registerSymbol(*Grp);
113 if (SectionELF->getFlags() & ELF::SHF_GNU_RETAIN)
115
116 changeSectionImpl(Section, Subsection);
117 Asm.registerSymbol(*Section->getBeginSymbol());
118}
119
121 getAssembler().registerSymbol(*Symbol);
124 Alias->setVariableValue(Value);
125}
126
127// When GNU as encounters more than one .type declaration for an object it seems
128// to use a mechanism similar to the one below to decide which type is actually
129// used in the object file. The greater of T1 and T2 is selected based on the
130// following ordering:
131// STT_NOTYPE < STT_OBJECT < STT_FUNC < STT_GNU_IFUNC < STT_TLS < anything else
132// If neither T1 < T2 nor T2 < T1 according to this ordering, use T2 (the user
133// provided type).
134static unsigned CombineSymbolTypes(unsigned T1, unsigned T2) {
137 if (T1 == Type)
138 return T2;
139 if (T2 == Type)
140 return T1;
141 }
142
143 return T2;
144}
145
147 auto *Symbol = cast<MCSymbolELF>(S);
148
149 // Adding a symbol attribute always introduces the symbol, note that an
150 // important side effect of calling registerSymbol here is to register
151 // the symbol with the assembler.
152 getAssembler().registerSymbol(*Symbol);
153
154 // The implementation of symbol attributes is designed to match 'as', but it
155 // leaves much to desired. It doesn't really make sense to arbitrarily add and
156 // remove flags, but 'as' allows this (in particular, see .desc).
157 //
158 // In the future it might be worth trying to make these operations more well
159 // defined.
160 switch (Attribute) {
161 case MCSA_Cold:
162 case MCSA_Extern:
164 case MCSA_Reference:
169 case MCSA_Invalid:
171 case MCSA_Exported:
172 case MCSA_WeakAntiDep:
173 return false;
174
175 case MCSA_NoDeadStrip:
176 // Ignore for now.
177 break;
178
180 Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_OBJECT));
181 Symbol->setBinding(ELF::STB_GNU_UNIQUE);
183 break;
184
185 case MCSA_Global:
186 // For `.weak x; .global x`, GNU as sets the binding to STB_WEAK while we
187 // traditionally set the binding to STB_GLOBAL. This is error-prone, so we
188 // error on such cases. Note, we also disallow changed binding from .local.
189 if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_GLOBAL)
191 Symbol->getName() +
192 " changed binding to STB_GLOBAL");
193 Symbol->setBinding(ELF::STB_GLOBAL);
194 break;
195
197 case MCSA_Weak:
198 // For `.global x; .weak x`, both MC and GNU as set the binding to STB_WEAK.
199 // We emit a warning for now but may switch to an error in the future.
200 if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_WEAK)
202 getStartTokLoc(), Symbol->getName() + " changed binding to STB_WEAK");
203 Symbol->setBinding(ELF::STB_WEAK);
204 break;
205
206 case MCSA_Local:
207 if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_LOCAL)
209 Symbol->getName() +
210 " changed binding to STB_LOCAL");
211 Symbol->setBinding(ELF::STB_LOCAL);
212 break;
213
215 Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_FUNC));
216 break;
217
219 Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_GNU_IFUNC));
221 break;
222
224 Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_OBJECT));
225 break;
226
227 case MCSA_ELF_TypeTLS:
228 Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_TLS));
229 break;
230
232 // TODO: Emit these as a common symbol.
233 Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_OBJECT));
234 break;
235
237 Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_NOTYPE));
238 break;
239
240 case MCSA_Protected:
241 Symbol->setVisibility(ELF::STV_PROTECTED);
242 break;
243
244 case MCSA_Memtag:
245 Symbol->setMemtag(true);
246 break;
247
248 case MCSA_Hidden:
249 Symbol->setVisibility(ELF::STV_HIDDEN);
250 break;
251
252 case MCSA_Internal:
253 Symbol->setVisibility(ELF::STV_INTERNAL);
254 break;
255
256 case MCSA_AltEntry:
257 llvm_unreachable("ELF doesn't support the .alt_entry attribute");
258
259 case MCSA_LGlobal:
260 llvm_unreachable("ELF doesn't support the .lglobl attribute");
261 }
262
263 return true;
264}
265
267 Align ByteAlignment) {
268 auto *Symbol = cast<MCSymbolELF>(S);
269 getAssembler().registerSymbol(*Symbol);
270
271 if (!Symbol->isBindingSet())
272 Symbol->setBinding(ELF::STB_GLOBAL);
273
274 Symbol->setType(ELF::STT_OBJECT);
275
276 if (Symbol->getBinding() == ELF::STB_LOCAL) {
280 switchSection(&Section);
281
282 emitValueToAlignment(ByteAlignment, 0, 1, 0);
283 emitLabel(Symbol);
285
286 switchSection(P.first, P.second);
287 } else {
288 if (Symbol->declareCommon(Size, ByteAlignment))
289 report_fatal_error(Twine("Symbol: ") + Symbol->getName() +
290 " redeclared as different type");
291 }
292
293 cast<MCSymbolELF>(Symbol)
295}
296
298 cast<MCSymbolELF>(Symbol)->setSize(Value);
299}
300
303 bool KeepOriginalSym) {
305 getStartTokLoc(), OriginalSym, Name, KeepOriginalSym});
306}
307
309 Align ByteAlignment) {
310 auto *Symbol = cast<MCSymbolELF>(S);
311 // FIXME: Should this be caught and done earlier?
312 getAssembler().registerSymbol(*Symbol);
313 Symbol->setBinding(ELF::STB_LOCAL);
314 emitCommonSymbol(Symbol, Size, ByteAlignment);
315}
316
318 SMLoc Loc) {
319 if (isBundleLocked())
320 report_fatal_error("Emitting values inside a locked bundle is forbidden");
321 fixSymbolsInTLSFixups(Value);
323}
324
326 unsigned ValueSize,
327 unsigned MaxBytesToEmit) {
328 if (isBundleLocked())
329 report_fatal_error("Emitting values inside a locked bundle is forbidden");
330 MCObjectStreamer::emitValueToAlignment(Alignment, Value, ValueSize,
331 MaxBytesToEmit);
332}
333
335 const MCSymbolRefExpr *To,
336 uint64_t Count) {
337 getWriter().getCGProfile().push_back({From, To, Count});
338}
339
343 pushSection();
344 switchSection(Comment);
345 if (!SeenIdent) {
346 emitInt8(0);
347 SeenIdent = true;
348 }
349 emitBytes(IdentString);
350 emitInt8(0);
351 popSection();
352}
353
354void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
355 switch (expr->getKind()) {
356 case MCExpr::Target:
357 cast<MCTargetExpr>(expr)->fixELFSymbolsInTLSFixups(getAssembler());
358 break;
359 case MCExpr::Constant:
360 break;
361
362 case MCExpr::Binary: {
363 const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
364 fixSymbolsInTLSFixups(be->getLHS());
365 fixSymbolsInTLSFixups(be->getRHS());
366 break;
367 }
368
369 case MCExpr::SymbolRef: {
370 const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
371 switch (symRef.getKind()) {
372 default:
373 return;
428 break;
429 }
431 cast<MCSymbolELF>(symRef.getSymbol()).setType(ELF::STT_TLS);
432 break;
433 }
434
435 case MCExpr::Unary:
436 fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
437 break;
438 }
439}
440
441void MCELFStreamer::finalizeCGProfileEntry(const MCSymbolRefExpr *&SRE,
443 const MCSymbol *S = &SRE->getSymbol();
444 if (S->isTemporary()) {
445 if (!S->isInSection()) {
447 SRE->getLoc(), Twine("Reference to undefined temporary symbol ") +
448 "`" + S->getName() + "`");
449 return;
450 }
451 S = S->getSection().getBeginSymbol();
452 S->setUsedInReloc();
454 SRE->getLoc());
455 }
457 if (std::optional<std::pair<bool, std::string>> Err =
459 *MCOffset, "BFD_RELOC_NONE", SRE, SRE->getLoc(),
460 *getContext().getSubtargetInfo()))
461 report_fatal_error("Relocation for CG Profile could not be created: " +
462 Twine(Err->second));
463}
464
465void MCELFStreamer::finalizeCGProfile() {
467 if (W.getCGProfile().empty())
468 return;
470 ".llvm.call-graph-profile", ELF::SHT_LLVM_CALL_GRAPH_PROFILE,
471 ELF::SHF_EXCLUDE, /*sizeof(Elf_CGProfile_Impl<>)=*/8);
472 pushSection();
473 switchSection(CGProfile);
474 uint64_t Offset = 0;
475 for (auto &E : W.getCGProfile()) {
476 finalizeCGProfileEntry(E.From, Offset);
477 finalizeCGProfileEntry(E.To, Offset);
478 emitIntValue(E.Count, sizeof(uint64_t));
479 Offset += sizeof(uint64_t);
480 }
481 popSection();
482}
483
484void MCELFStreamer::emitInstToFragment(const MCInst &Inst,
485 const MCSubtargetInfo &STI) {
487 MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
488
489 for (auto &Fixup : F.getFixups())
490 fixSymbolsInTLSFixups(Fixup.getValue());
491}
492
493// A fragment can only have one Subtarget, and when bundling is enabled we
494// sometimes need to use the same fragment. We give an error if there
495// are conflicting Subtargets.
496static void CheckBundleSubtargets(const MCSubtargetInfo *OldSTI,
497 const MCSubtargetInfo *NewSTI) {
498 if (OldSTI && NewSTI && OldSTI != NewSTI)
499 report_fatal_error("A Bundle can only have one Subtarget.");
500}
501
502void MCELFStreamer::emitInstToData(const MCInst &Inst,
503 const MCSubtargetInfo &STI) {
504 MCAssembler &Assembler = getAssembler();
505
506 // There are several possibilities here:
507 //
508 // If bundling is disabled, append the encoded instruction to the current data
509 // fragment (or create a new such fragment if the current fragment is not a
510 // data fragment, or the Subtarget has changed).
511 //
512 // If bundling is enabled:
513 // - If we're not in a bundle-locked group, emit the instruction into a
514 // fragment of its own.
515 // - If we're in a bundle-locked group, append the instruction to the current
516 // data fragment because we want all the instructions in a group to get into
517 // the same fragment. Be careful not to do that for the first instruction in
518 // the group, though.
520
521 if (Assembler.isBundlingEnabled()) {
523 if (isBundleLocked() && !Sec.isBundleGroupBeforeFirstInst()) {
524 // If we are bundle-locked, we re-use the current fragment.
525 // The bundle-locking directive ensures this is a new data fragment.
526 DF = cast<MCDataFragment>(getCurrentFragment());
527 CheckBundleSubtargets(DF->getSubtargetInfo(), &STI);
528 } else {
530 insert(DF);
531 }
533 // If this fragment is for a group marked "align_to_end", set a flag
534 // in the fragment. This can happen after the fragment has already been
535 // created if there are nested bundle_align groups and an inner one
536 // is the one marked align_to_end.
537 DF->setAlignToBundleEnd(true);
538 }
539
540 // We're now emitting an instruction in a bundle group, so this flag has
541 // to be turned off.
543 } else {
545 }
546
547 // Emit instruction directly into data fragment.
548 size_t FixupStartIndex = DF->getFixups().size();
549 size_t CodeOffset = DF->getContents().size();
550 Assembler.getEmitter().encodeInstruction(Inst, DF->getContents(),
551 DF->getFixups(), STI);
552
553 auto Fixups = MutableArrayRef(DF->getFixups()).slice(FixupStartIndex);
554 for (auto &Fixup : Fixups) {
555 Fixup.setOffset(Fixup.getOffset() + CodeOffset);
556 fixSymbolsInTLSFixups(Fixup.getValue());
557 }
558
559 DF->setHasInstructions(STI);
560 if (!Fixups.empty() && Fixups.back().getTargetKind() ==
561 getAssembler().getBackend().RelaxFixupKind)
562 DF->setLinkerRelaxable();
563}
564
566 assert(Log2(Alignment) <= 30 && "Invalid bundle alignment");
567 MCAssembler &Assembler = getAssembler();
568 if (Alignment > 1 && (Assembler.getBundleAlignSize() == 0 ||
569 Assembler.getBundleAlignSize() == Alignment.value()))
570 Assembler.setBundleAlignSize(Alignment.value());
571 else
572 report_fatal_error(".bundle_align_mode cannot be changed once set");
573}
574
575void MCELFStreamer::emitBundleLock(bool AlignToEnd) {
577
578 if (!getAssembler().isBundlingEnabled())
579 report_fatal_error(".bundle_lock forbidden when bundling is disabled");
580
581 if (!isBundleLocked())
583
586}
587
590
591 if (!getAssembler().isBundlingEnabled())
592 report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
593 else if (!isBundleLocked())
594 report_fatal_error(".bundle_unlock without matching lock");
595 else if (Sec.isBundleGroupBeforeFirstInst())
596 report_fatal_error("Empty bundle-locked group is forbidden");
597
599}
600
602 // Emit the .gnu attributes section if any attributes have been added.
603 if (!GNUAttributes.empty()) {
604 MCSection *DummyAttributeSection = nullptr;
605 createAttributesSection("gnu", ".gnu.attributes", ELF::SHT_GNU_ATTRIBUTES,
606 DummyAttributeSection, GNUAttributes);
607 }
608
609 // Ensure the last section gets aligned if necessary.
612
613 finalizeCGProfile();
614 emitFrames(nullptr);
615
617}
618
620 llvm_unreachable("Generic ELF doesn't support this directive");
621}
622
623void MCELFStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
624 llvm_unreachable("ELF doesn't support this directive");
625}
626
628 uint64_t Size, Align ByteAlignment,
629 SMLoc Loc) {
630 llvm_unreachable("ELF doesn't support this directive");
631}
632
634 uint64_t Size, Align ByteAlignment) {
635 llvm_unreachable("ELF doesn't support this directive");
636}
637
639 bool OverwriteExisting) {
640 // Look for existing attribute item
641 if (AttributeItem *Item = getAttributeItem(Attribute)) {
642 if (!OverwriteExisting)
643 return;
645 Item->IntValue = Value;
646 return;
647 }
648
649 // Create new attribute item
651 std::string(StringRef(""))};
652 Contents.push_back(Item);
653}
654
656 bool OverwriteExisting) {
657 // Look for existing attribute item
658 if (AttributeItem *Item = getAttributeItem(Attribute)) {
659 if (!OverwriteExisting)
660 return;
661 Item->Type = AttributeItem::TextAttribute;
662 Item->StringValue = std::string(Value);
663 return;
664 }
665
666 // Create new attribute item
668 std::string(Value)};
669 Contents.push_back(Item);
670}
671
672void MCELFStreamer::setAttributeItems(unsigned Attribute, unsigned IntValue,
673 StringRef StringValue,
674 bool OverwriteExisting) {
675 // Look for existing attribute item
676 if (AttributeItem *Item = getAttributeItem(Attribute)) {
677 if (!OverwriteExisting)
678 return;
680 Item->IntValue = IntValue;
681 Item->StringValue = std::string(StringValue);
682 return;
683 }
684
685 // Create new attribute item
687 IntValue, std::string(StringValue)};
688 Contents.push_back(Item);
689}
690
692MCELFStreamer::getAttributeItem(unsigned Attribute) {
693 for (AttributeItem &Item : Contents)
694 if (Item.Tag == Attribute)
695 return &Item;
696 return nullptr;
697}
698
699size_t
700MCELFStreamer::calculateContentSize(SmallVector<AttributeItem, 64> &AttrsVec) {
701 size_t Result = 0;
702 for (const AttributeItem &Item : AttrsVec) {
703 switch (Item.Type) {
705 break;
707 Result += getULEB128Size(Item.Tag);
708 Result += getULEB128Size(Item.IntValue);
709 break;
711 Result += getULEB128Size(Item.Tag);
712 Result += Item.StringValue.size() + 1; // string + '\0'
713 break;
715 Result += getULEB128Size(Item.Tag);
716 Result += getULEB128Size(Item.IntValue);
717 Result += Item.StringValue.size() + 1; // string + '\0';
718 break;
719 }
720 }
721 return Result;
722}
723
724void MCELFStreamer::createAttributesSection(
725 StringRef Vendor, const Twine &Section, unsigned Type,
726 MCSection *&AttributeSection, SmallVector<AttributeItem, 64> &AttrsVec) {
727 // <format-version>
728 // [ <section-length> "vendor-name"
729 // [ <file-tag> <size> <attribute>*
730 // | <section-tag> <size> <section-number>* 0 <attribute>*
731 // | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
732 // ]+
733 // ]*
734
735 // Switch section to AttributeSection or get/create the section.
736 if (AttributeSection) {
737 switchSection(AttributeSection);
738 } else {
739 AttributeSection = getContext().getELFSection(Section, Type, 0);
740 switchSection(AttributeSection);
741
742 // Format version
743 emitInt8(0x41);
744 }
745
746 // Vendor size + Vendor name + '\0'
747 const size_t VendorHeaderSize = 4 + Vendor.size() + 1;
748
749 // Tag + Tag Size
750 const size_t TagHeaderSize = 1 + 4;
751
752 const size_t ContentsSize = calculateContentSize(AttrsVec);
753
754 emitInt32(VendorHeaderSize + TagHeaderSize + ContentsSize);
755 emitBytes(Vendor);
756 emitInt8(0); // '\0'
757
759 emitInt32(TagHeaderSize + ContentsSize);
760
761 // Size should have been accounted for already, now
762 // emit each field as its type (ULEB or String)
763 for (const AttributeItem &Item : AttrsVec) {
764 emitULEB128IntValue(Item.Tag);
765 switch (Item.Type) {
766 default:
767 llvm_unreachable("Invalid attribute type");
769 emitULEB128IntValue(Item.IntValue);
770 break;
772 emitBytes(Item.StringValue);
773 emitInt8(0); // '\0'
774 break;
776 emitULEB128IntValue(Item.IntValue);
777 emitBytes(Item.StringValue);
778 emitInt8(0); // '\0'
779 break;
780 }
781 }
782
783 AttrsVec.clear();
784}
785
787 std::unique_ptr<MCAsmBackend> &&MAB,
788 std::unique_ptr<MCObjectWriter> &&OW,
789 std::unique_ptr<MCCodeEmitter> &&CE) {
790 MCELFStreamer *S =
791 new MCELFStreamer(Context, std::move(MAB), std::move(OW), std::move(CE));
792 return S;
793}
BlockVerifier::State From
dxil DXContainer Global Emitter
static RegisterPass< DebugifyFunctionPass > DF("debugify-function", "Attach debug info to a function")
std::string Name
uint64_t Size
static unsigned CombineSymbolTypes(unsigned T1, unsigned T2)
static void CheckBundleSubtargets(const MCSubtargetInfo *OldSTI, const MCSubtargetInfo *NewSTI)
static void setSectionAlignmentForBundling(const MCAssembler &Assembler, MCSection *Section)
#define F(x, y, z)
Definition: MD5.cpp:55
#define T1
#define P(N)
PowerPC TLS Dynamic Call Fixup
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
SmallVector< Symver, 0 > Symvers
virtual void handleAssemblerFlag(MCAssemblerFlag Flag)
Handle any target-specific assembler flags. By default, do nothing.
Definition: MCAsmBackend.h:226
virtual MCSection * getNonexecutableStackSection(MCContext &Ctx) const
Targets can implement this method to specify a section to switch to if the translation unit doesn't h...
Definition: MCAsmInfo.h:551
MCContext & getContext() const
Definition: MCAssembler.h:182
unsigned getBundleAlignSize() const
Definition: MCAssembler.h:210
bool isBundlingEnabled() const
Definition: MCAssembler.h:208
void setBundleAlignSize(unsigned Size)
Definition: MCAssembler.h:212
MCObjectWriter & getWriter() const
Definition: MCAssembler.h:192
MCCodeEmitter & getEmitter() const
Definition: MCAssembler.h:190
MCAsmBackend & getBackend() const
Definition: MCAssembler.h:188
bool registerSymbol(const MCSymbol &Symbol)
Binary assembler expressions.
Definition: MCExpr.h:493
const MCExpr * getLHS() const
Get the left-hand side expression of the binary operator.
Definition: MCExpr.h:640
const MCExpr * getRHS() const
Get the right-hand side expression of the binary operator.
Definition: MCExpr.h:643
virtual void encodeInstruction(const MCInst &Inst, SmallVectorImpl< char > &CB, SmallVectorImpl< MCFixup > &Fixups, const MCSubtargetInfo &STI) const =0
Encode the given Inst to bytes and append to CB.
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:222
Context object for machine code objects.
Definition: MCContext.h:83
const MCObjectFileInfo * getObjectFileInfo() const
Definition: MCContext.h:416
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:551
void reportWarning(SMLoc L, const Twine &Msg)
Definition: MCContext.cpp:1079
const MCAsmInfo * getAsmInfo() const
Definition: MCContext.h:412
void reportError(SMLoc L, const Twine &Msg)
Definition: MCContext.cpp:1072
F * allocFragment(Args &&...args)
Definition: MCContext.h:440
Fragment for data and encoded instructions.
Definition: MCFragment.h:219
void emitBundleLock(bool AlignToEnd) override
The following instructions are a bundle-locked group.
SmallVector< AttributeItem, 64 > Contents
void emitValueToAlignment(Align, int64_t, unsigned, unsigned) override
Emit some number of copies of Value until the byte alignment ByteAlignment is reached.
void changeSection(MCSection *Section, uint32_t Subsection=0) override
This is called by popSection and switchSection, if the current section changes.
void emitIdent(StringRef IdentString) override
Emit the "identifiers" directive.
void setAttributeItems(unsigned Attribute, unsigned IntValue, StringRef StringValue, bool OverwriteExisting)
void emitBundleUnlock() override
Ends a bundle-locked group.
void emitCommonSymbol(MCSymbol *Symbol, uint64_t Size, Align ByteAlignment) override
Emit a common symbol.
void emitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc=SMLoc()) override
Emit the expression Value into the output as a native integer of the given Size bytes.
void emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size, Align ByteAlignment) override
Emit a local common (.lcomm) symbol.
void emitAssemblerFlag(MCAssemblerFlag Flag) override
Note in the output the specified Flag.
void emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override
Set the DescValue for the Symbol.
void emitELFSize(MCSymbol *Symbol, const MCExpr *Value) override
Emit an ELF .size directive.
void emitThumbFunc(MCSymbol *Func) override
Note in the output that the specified Func is a Thumb mode function (ARM target only).
void emitELFSymverDirective(const MCSymbol *OriginalSym, StringRef Name, bool KeepOriginalSym) override
Emit an ELF .symver directive.
void emitCGProfileEntry(const MCSymbolRefExpr *From, const MCSymbolRefExpr *To, uint64_t Count) override
ELFObjectWriter & getWriter()
void emitZerofill(MCSection *Section, MCSymbol *Symbol=nullptr, uint64_t Size=0, Align ByteAlignment=Align(1), SMLoc L=SMLoc()) override
Emit the zerofill section and an optional symbol.
void setAttributeItem(unsigned Attribute, unsigned Value, bool OverwriteExisting)
void finishImpl() final
Streamer specific finalization.
void emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override
Emit an weak reference from Alias to Symbol.
void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc()) override
Emit a label for Symbol into the current section.
void emitBundleAlignMode(Align Alignment) override
Set the bundle alignment mode from now on in the section.
bool emitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override
Add the given Attribute to Symbol.
void emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size, Align ByteAlignment=Align(1)) override
Emit a thread local bss (.tbss) symbol.
void initSections(bool NoExecStack, const MCSubtargetInfo &STI) override
Create the default sections and set the initial one.
void emitLabelAtPos(MCSymbol *Symbol, SMLoc Loc, MCDataFragment &F, uint64_t Offset) override
MCELFStreamer(MCContext &Context, std::unique_ptr< MCAsmBackend > TAB, std::unique_ptr< MCObjectWriter > OW, std::unique_ptr< MCCodeEmitter > Emitter)
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:34
@ Unary
Unary expressions.
Definition: MCExpr.h:40
@ Constant
Constant expressions.
Definition: MCExpr.h:38
@ SymbolRef
References to labels and assigned expressions.
Definition: MCExpr.h:39
@ Target
Target specific expression.
Definition: MCExpr.h:41
@ Binary
Binary expressions.
Definition: MCExpr.h:37
ExprKind getKind() const
Definition: MCExpr.h:78
SMLoc getLoc() const
Definition: MCExpr.h:79
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:185
virtual unsigned getTextSectionAlignment() const
MCSection * getTextSection() const
Streaming object file generation interface.
void emitValueToAlignment(Align Alignment, int64_t Value=0, unsigned ValueSize=1, unsigned MaxBytesToEmit=0) override
Emit some number of copies of Value until the byte alignment ByteAlignment is reached.
MCDataFragment * getOrCreateDataFragment(const MCSubtargetInfo *STI=nullptr)
Get a data fragment to write into, creating a new one if the current fragment is not a data fragment.
MCAssembler & getAssembler()
void emitBytes(StringRef Data) override
Emit the bytes in Data into the output.
bool changeSectionImpl(MCSection *Section, uint32_t Subsection)
std::optional< std::pair< bool, std::string > > emitRelocDirective(const MCExpr &Offset, StringRef Name, const MCExpr *Expr, SMLoc Loc, const MCSubtargetInfo &STI) override
Record a relocation described by the .reloc directive.
void insert(MCFragment *F)
virtual void emitInstToFragment(const MCInst &Inst, const MCSubtargetInfo &)
Emit an instruction to a special fragment, because this instruction can change its size during relaxa...
void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc()) override
Emit a label for Symbol into the current section.
void emitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc=SMLoc()) override
Emit the expression Value into the output as a native integer of the given Size bytes.
void finishImpl() override
Streamer specific finalization.
void emitCodeAlignment(Align ByteAlignment, const MCSubtargetInfo *STI, unsigned MaxBytesToEmit=0) override
Emit nops until the byte alignment ByteAlignment is reached.
void emitFrames(MCAsmBackend *MAB)
virtual void emitLabelAtPos(MCSymbol *Symbol, SMLoc Loc, MCDataFragment &F, uint64_t Offset)
SmallVector< CGProfileEntry, 0 > & getCGProfile()
A relaxable fragment holds on to its MCInst, since it may need to be relaxed during the assembler lay...
Definition: MCFragment.h:234
This represents a section on linux, lots of unix variants and some bare metal systems.
Definition: MCSectionELF.h:27
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:36
void setBundleLockState(BundleLockStateType NewState)
Definition: MCSection.cpp:49
bool isBundleGroupBeforeFirstInst() const
Definition: MCSection.h:162
bool isBundleLocked() const
Definition: MCSection.h:160
@ BundleLockedAlignToEnd
Definition: MCSection.h:57
MCSymbol * getBeginSymbol()
Definition: MCSection.h:135
BundleLockStateType getBundleLockState() const
Definition: MCSection.h:158
void setBundleGroupBeforeFirstInst(bool IsFirst)
Definition: MCSection.h:165
Streaming machine code generation interface.
Definition: MCStreamer.h:213
bool popSection()
Restore the current and previous section from the section stack.
MCFragment * getCurrentFragment() const
Definition: MCStreamer.h:411
MCContext & getContext() const
Definition: MCStreamer.h:300
SMLoc getStartTokLoc() const
Definition: MCStreamer.h:292
virtual void emitIntValue(uint64_t Value, unsigned Size)
Special case of EmitValue that avoids the client having to pass in a MCExpr for constant integers.
Definition: MCStreamer.cpp:133
void pushSection()
Save the current and previous section on the section stack.
Definition: MCStreamer.h:418
unsigned emitULEB128IntValue(uint64_t Value, unsigned PadTo=0)
Special case of EmitULEB128Value that avoids the client having to pass in a MCExpr for constant integ...
Definition: MCStreamer.cpp:161
virtual void switchSection(MCSection *Section, uint32_t Subsec=0)
Set the current section where code is being emitted to Section.
void emitInt32(uint64_t Value)
Definition: MCStreamer.h:721
MCSectionSubPair getCurrentSection() const
Return the current section that the streamer is emitting code to.
Definition: MCStreamer.h:395
MCSection * getCurrentSectionOnly() const
Definition: MCStreamer.h:400
void emitZeros(uint64_t NumBytes)
Emit NumBytes worth of zeros.
Definition: MCStreamer.cpp:229
void emitInt8(uint64_t Value)
Definition: MCStreamer.h:719
Generic base class for all target subtargets.
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:192
const MCSymbol & getSymbol() const
Definition: MCExpr.h:411
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:398
VariantKind getKind() const
Definition: MCExpr.h:413
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute).
Definition: MCSymbol.h:254
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:205
void setVariableValue(const MCExpr *Value)
Definition: MCSymbol.cpp:47
void setUsedInReloc() const
Definition: MCSymbol.h:215
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition: MCSymbol.h:269
bool isTemporary() const
isTemporary - Check if this is an assembler temporary symbol.
Definition: MCSymbol.h:222
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:310
MutableArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition: ArrayRef.h:379
Represents a location in source code.
Definition: SMLoc.h:23
bool empty() const
Definition: SmallVector.h:81
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:150
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ SHT_PROGBITS
Definition: ELF.h:1090
@ SHT_LLVM_CALL_GRAPH_PROFILE
Definition: ELF.h:1129
@ SHT_NOBITS
Definition: ELF.h:1097
@ SHT_GNU_ATTRIBUTES
Definition: ELF.h:1137
@ SHF_MERGE
Definition: ELF.h:1194
@ SHF_STRINGS
Definition: ELF.h:1197
@ SHF_EXCLUDE
Definition: ELF.h:1222
@ SHF_ALLOC
Definition: ELF.h:1188
@ SHF_GNU_RETAIN
Definition: ELF.h:1219
@ SHF_WRITE
Definition: ELF.h:1185
@ SHF_TLS
Definition: ELF.h:1213
@ STB_GLOBAL
Definition: ELF.h:1342
@ STB_LOCAL
Definition: ELF.h:1341
@ STB_GNU_UNIQUE
Definition: ELF.h:1344
@ STB_WEAK
Definition: ELF.h:1343
@ STT_FUNC
Definition: ELF.h:1355
@ STT_NOTYPE
Definition: ELF.h:1353
@ STT_GNU_IFUNC
Definition: ELF.h:1360
@ STT_OBJECT
Definition: ELF.h:1354
@ STT_TLS
Definition: ELF.h:1359
@ STV_INTERNAL
Definition: ELF.h:1372
@ STV_HIDDEN
Definition: ELF.h:1373
@ STV_PROTECTED
Definition: ELF.h:1374
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
MCStreamer * createELFStreamer(MCContext &Ctx, std::unique_ptr< MCAsmBackend > &&TAB, std::unique_ptr< MCObjectWriter > &&OW, std::unique_ptr< MCCodeEmitter > &&CE)
std::pair< MCSection *, uint32_t > MCSectionSubPair
Definition: MCStreamer.h:67
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
unsigned getULEB128Size(uint64_t Value)
Utility function to get the size of the ULEB128-encoded value.
Definition: LEB128.cpp:19
MCAssemblerFlag
Definition: MCDirectives.h:53
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1873
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition: Alignment.h:208
MCSymbolAttr
Definition: MCDirectives.h:18
@ MCSA_Local
.local (ELF)
Definition: MCDirectives.h:38
@ MCSA_WeakDefAutoPrivate
.weak_def_can_be_hidden (MachO)
Definition: MCDirectives.h:48
@ MCSA_Memtag
.memtag (ELF)
Definition: MCDirectives.h:50
@ MCSA_Protected
.protected (ELF)
Definition: MCDirectives.h:43
@ MCSA_Exported
.globl _foo, exported (XCOFF)
Definition: MCDirectives.h:34
@ MCSA_PrivateExtern
.private_extern (MachO)
Definition: MCDirectives.h:42
@ MCSA_Internal
.internal (ELF)
Definition: MCDirectives.h:36
@ MCSA_WeakReference
.weak_reference (MachO)
Definition: MCDirectives.h:47
@ MCSA_AltEntry
.alt_entry (MachO)
Definition: MCDirectives.h:41
@ MCSA_ELF_TypeIndFunction
.type _foo, STT_GNU_IFUNC
Definition: MCDirectives.h:24
@ MCSA_LazyReference
.lazy_reference (MachO)
Definition: MCDirectives.h:37
@ MCSA_ELF_TypeNoType
.type _foo, STT_NOTYPE # aka @notype
Definition: MCDirectives.h:28
@ MCSA_Reference
.reference (MachO)
Definition: MCDirectives.h:44
@ MCSA_SymbolResolver
.symbol_resolver (MachO)
Definition: MCDirectives.h:40
@ MCSA_Weak
.weak
Definition: MCDirectives.h:45
@ MCSA_ELF_TypeTLS
.type _foo, STT_TLS # aka @tls_object
Definition: MCDirectives.h:26
@ MCSA_IndirectSymbol
.indirect_symbol (MachO)
Definition: MCDirectives.h:35
@ MCSA_WeakDefinition
.weak_definition (MachO)
Definition: MCDirectives.h:46
@ MCSA_ELF_TypeCommon
.type _foo, STT_COMMON # aka @common
Definition: MCDirectives.h:27
@ MCSA_Global
.type _foo, @gnu_unique_object
Definition: MCDirectives.h:30
@ MCSA_WeakAntiDep
.weak_anti_dep (COFF)
Definition: MCDirectives.h:49
@ MCSA_Extern
.extern (XCOFF)
Definition: MCDirectives.h:32
@ MCSA_Cold
.cold (MachO)
Definition: MCDirectives.h:22
@ MCSA_ELF_TypeObject
.type _foo, STT_OBJECT # aka @object
Definition: MCDirectives.h:25
@ MCSA_ELF_TypeGnuUniqueObject
Definition: MCDirectives.h:29
@ MCSA_ELF_TypeFunction
.type _foo, STT_FUNC # aka @function
Definition: MCDirectives.h:23
@ MCSA_Hidden
.hidden (ELF)
Definition: MCDirectives.h:33
@ MCSA_LGlobal
.lglobl (XCOFF)
Definition: MCDirectives.h:31
@ MCSA_Invalid
Not a valid directive.
Definition: MCDirectives.h:19
@ MCSA_NoDeadStrip
.no_dead_strip (MachO)
Definition: MCDirectives.h:39
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
ELF object attributes section emission support.
Definition: MCELFStreamer.h:95