1 //===- llvm/MC/MCWinCOFFStreamer.cpp --------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file contains an implementation of a Windows COFF object file streamer.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/MC/MCWinCOFFStreamer.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/BinaryFormat/COFF.h"
18 #include "llvm/MC/MCAsmBackend.h"
19 #include "llvm/MC/MCAssembler.h"
20 #include "llvm/MC/MCCodeEmitter.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCFixup.h"
24 #include "llvm/MC/MCFragment.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCObjectStreamer.h"
27 #include "llvm/MC/MCObjectWriter.h"
28 #include "llvm/MC/MCSectionCOFF.h"
29 #include "llvm/MC/MCSymbolCOFF.h"
30 #include "llvm/MC/MCTargetOptions.h"
31 #include "llvm/MC/MCWinCOFFObjectWriter.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/SMLoc.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/TargetParser/Triple.h"
43 #define DEBUG_TYPE "WinCOFFStreamer"
45 MCWinCOFFStreamer::MCWinCOFFStreamer(MCContext
&Context
,
46 std::unique_ptr
<MCAsmBackend
> MAB
,
47 std::unique_ptr
<MCCodeEmitter
> CE
,
48 std::unique_ptr
<MCObjectWriter
> OW
)
49 : MCObjectStreamer(Context
, std::move(MAB
), std::move(OW
), std::move(CE
)),
51 auto *TO
= Context
.getTargetOptions();
52 if (TO
&& TO
->MCIncrementalLinkerCompatible
)
53 getWriter().setIncrementalLinkerCompatible(true);
56 WinCOFFObjectWriter
&MCWinCOFFStreamer::getWriter() {
57 return static_cast<WinCOFFObjectWriter
&>(getAssembler().getWriter());
60 void MCWinCOFFStreamer::emitInstToData(const MCInst
&Inst
,
61 const MCSubtargetInfo
&STI
) {
62 MCDataFragment
*DF
= getOrCreateDataFragment();
64 SmallVector
<MCFixup
, 4> Fixups
;
65 SmallString
<256> Code
;
66 getAssembler().getEmitter().encodeInstruction(Inst
, Code
, Fixups
, STI
);
68 // Add the fixups and data.
69 for (unsigned i
= 0, e
= Fixups
.size(); i
!= e
; ++i
) {
70 Fixups
[i
].setOffset(Fixups
[i
].getOffset() + DF
->getContents().size());
71 DF
->getFixups().push_back(Fixups
[i
]);
73 DF
->setHasInstructions(STI
);
74 DF
->getContents().append(Code
.begin(), Code
.end());
77 void MCWinCOFFStreamer::initSections(bool NoExecStack
,
78 const MCSubtargetInfo
&STI
) {
79 // FIXME: this is identical to the ELF one.
80 // This emulates the same behavior of GNU as. This makes it easier
81 // to compare the output as the major sections are in the same order.
82 switchSection(getContext().getObjectFileInfo()->getTextSection());
83 emitCodeAlignment(Align(4), &STI
);
85 switchSection(getContext().getObjectFileInfo()->getDataSection());
86 emitCodeAlignment(Align(4), &STI
);
88 switchSection(getContext().getObjectFileInfo()->getBSSSection());
89 emitCodeAlignment(Align(4), &STI
);
91 switchSection(getContext().getObjectFileInfo()->getTextSection());
94 void MCWinCOFFStreamer::changeSection(MCSection
*Section
, uint32_t Subsection
) {
95 changeSectionImpl(Section
, Subsection
);
96 // Ensure that the first and the second symbols relative to the section are
97 // the section symbol and the COMDAT symbol.
98 getAssembler().registerSymbol(*Section
->getBeginSymbol());
99 if (auto *Sym
= cast
<MCSectionCOFF
>(Section
)->getCOMDATSymbol())
100 getAssembler().registerSymbol(*Sym
);
103 void MCWinCOFFStreamer::emitLabel(MCSymbol
*S
, SMLoc Loc
) {
104 auto *Symbol
= cast
<MCSymbolCOFF
>(S
);
105 MCObjectStreamer::emitLabel(Symbol
, Loc
);
108 void MCWinCOFFStreamer::emitAssemblerFlag(MCAssemblerFlag Flag
) {
109 // Let the target do whatever target specific stuff it needs to do.
110 getAssembler().getBackend().handleAssemblerFlag(Flag
);
113 // None of these require COFF specific handling.
114 case MCAF_SyntaxUnified
:
119 case MCAF_SubsectionsViaSymbols
:
120 llvm_unreachable("COFF doesn't support .subsections_via_symbols");
124 void MCWinCOFFStreamer::emitThumbFunc(MCSymbol
*Func
) {
125 llvm_unreachable("not implemented");
128 bool MCWinCOFFStreamer::emitSymbolAttribute(MCSymbol
*S
,
129 MCSymbolAttr Attribute
) {
130 auto *Symbol
= cast
<MCSymbolCOFF
>(S
);
131 getAssembler().registerSymbol(*Symbol
);
134 default: return false;
135 case MCSA_WeakReference
:
137 Symbol
->setWeakExternalCharacteristics(COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS
);
138 Symbol
->setExternal(true);
140 case MCSA_WeakAntiDep
:
141 Symbol
->setWeakExternalCharacteristics(COFF::IMAGE_WEAK_EXTERN_ANTI_DEPENDENCY
);
142 Symbol
->setExternal(true);
143 Symbol
->setIsWeakExternal(true);
146 Symbol
->setExternal(true);
149 llvm_unreachable("COFF doesn't support the .alt_entry attribute");
155 void MCWinCOFFStreamer::emitSymbolDesc(MCSymbol
*Symbol
, unsigned DescValue
) {
156 llvm_unreachable("not implemented");
159 void MCWinCOFFStreamer::beginCOFFSymbolDef(MCSymbol
const *S
) {
160 auto *Symbol
= cast
<MCSymbolCOFF
>(S
);
162 Error("starting a new symbol definition without completing the "
167 void MCWinCOFFStreamer::emitCOFFSymbolStorageClass(int StorageClass
) {
169 Error("storage class specified outside of symbol definition");
173 if (StorageClass
& ~COFF::SSC_Invalid
) {
174 Error("storage class value '" + Twine(StorageClass
) +
179 getAssembler().registerSymbol(*CurSymbol
);
180 cast
<MCSymbolCOFF
>(CurSymbol
)->setClass((uint16_t)StorageClass
);
183 void MCWinCOFFStreamer::emitCOFFSymbolType(int Type
) {
185 Error("symbol type specified outside of a symbol definition");
189 if (Type
& ~0xffff) {
190 Error("type value '" + Twine(Type
) + "' out of range");
194 getAssembler().registerSymbol(*CurSymbol
);
195 cast
<MCSymbolCOFF
>(CurSymbol
)->setType((uint16_t)Type
);
198 void MCWinCOFFStreamer::endCOFFSymbolDef() {
200 Error("ending symbol definition without starting one");
204 void MCWinCOFFStreamer::emitCOFFSafeSEH(MCSymbol
const *Symbol
) {
205 // SafeSEH is a feature specific to 32-bit x86. It does not exist (and is
206 // unnecessary) on all platforms which use table-based exception dispatch.
207 if (getContext().getTargetTriple().getArch() != Triple::x86
)
210 const MCSymbolCOFF
*CSymbol
= cast
<MCSymbolCOFF
>(Symbol
);
211 if (CSymbol
->isSafeSEH())
214 MCSection
*SXData
= getContext().getObjectFileInfo()->getSXDataSection();
215 changeSection(SXData
);
216 SXData
->ensureMinAlignment(Align(4));
218 insert(getContext().allocFragment
<MCSymbolIdFragment
>(Symbol
));
219 getAssembler().registerSymbol(*Symbol
);
220 CSymbol
->setIsSafeSEH();
222 // The Microsoft linker requires that the symbol type of a handler be
223 // function. Go ahead and oblige it here.
224 CSymbol
->setType(COFF::IMAGE_SYM_DTYPE_FUNCTION
225 << COFF::SCT_COMPLEX_TYPE_SHIFT
);
228 void MCWinCOFFStreamer::emitCOFFSymbolIndex(MCSymbol
const *Symbol
) {
229 MCSection
*Sec
= getCurrentSectionOnly();
230 Sec
->ensureMinAlignment(Align(4));
232 insert(getContext().allocFragment
<MCSymbolIdFragment
>(Symbol
));
233 getAssembler().registerSymbol(*Symbol
);
236 void MCWinCOFFStreamer::emitCOFFSectionIndex(const MCSymbol
*Symbol
) {
237 visitUsedSymbol(*Symbol
);
238 MCDataFragment
*DF
= getOrCreateDataFragment();
239 const MCSymbolRefExpr
*SRE
= MCSymbolRefExpr::create(Symbol
, getContext());
240 MCFixup Fixup
= MCFixup::create(DF
->getContents().size(), SRE
, FK_SecRel_2
);
241 DF
->getFixups().push_back(Fixup
);
242 DF
->getContents().resize(DF
->getContents().size() + 2, 0);
245 void MCWinCOFFStreamer::emitCOFFSecRel32(const MCSymbol
*Symbol
,
247 visitUsedSymbol(*Symbol
);
248 MCDataFragment
*DF
= getOrCreateDataFragment();
249 // Create Symbol A for the relocation relative reference.
250 const MCExpr
*MCE
= MCSymbolRefExpr::create(Symbol
, getContext());
251 // Add the constant offset, if given.
253 MCE
= MCBinaryExpr::createAdd(
254 MCE
, MCConstantExpr::create(Offset
, getContext()), getContext());
255 // Build the secrel32 relocation.
256 MCFixup Fixup
= MCFixup::create(DF
->getContents().size(), MCE
, FK_SecRel_4
);
257 // Record the relocation.
258 DF
->getFixups().push_back(Fixup
);
259 // Emit 4 bytes (zeros) to the object file.
260 DF
->getContents().resize(DF
->getContents().size() + 4, 0);
263 void MCWinCOFFStreamer::emitCOFFImgRel32(const MCSymbol
*Symbol
,
265 visitUsedSymbol(*Symbol
);
266 MCDataFragment
*DF
= getOrCreateDataFragment();
267 // Create Symbol A for the relocation relative reference.
268 const MCExpr
*MCE
= MCSymbolRefExpr::create(
269 Symbol
, MCSymbolRefExpr::VK_COFF_IMGREL32
, getContext());
270 // Add the constant offset, if given.
272 MCE
= MCBinaryExpr::createAdd(
273 MCE
, MCConstantExpr::create(Offset
, getContext()), getContext());
274 // Build the imgrel relocation.
275 MCFixup Fixup
= MCFixup::create(DF
->getContents().size(), MCE
, FK_Data_4
);
276 // Record the relocation.
277 DF
->getFixups().push_back(Fixup
);
278 // Emit 4 bytes (zeros) to the object file.
279 DF
->getContents().resize(DF
->getContents().size() + 4, 0);
282 void MCWinCOFFStreamer::emitCommonSymbol(MCSymbol
*S
, uint64_t Size
,
283 Align ByteAlignment
) {
284 auto *Symbol
= cast
<MCSymbolCOFF
>(S
);
286 const Triple
&T
= getContext().getTargetTriple();
287 if (T
.isWindowsMSVCEnvironment()) {
288 if (ByteAlignment
> 32)
289 report_fatal_error("alignment is limited to 32-bytes");
291 // Round size up to alignment so that we will honor the alignment request.
292 Size
= std::max(Size
, ByteAlignment
.value());
295 getAssembler().registerSymbol(*Symbol
);
296 Symbol
->setExternal(true);
297 Symbol
->setCommon(Size
, ByteAlignment
);
299 if (!T
.isWindowsMSVCEnvironment() && ByteAlignment
> 1) {
300 SmallString
<128> Directive
;
301 raw_svector_ostream
OS(Directive
);
302 const MCObjectFileInfo
*MFI
= getContext().getObjectFileInfo();
304 OS
<< " -aligncomm:\"" << Symbol
->getName() << "\","
305 << Log2_32_Ceil(ByteAlignment
.value());
308 switchSection(MFI
->getDrectveSection());
309 emitBytes(Directive
);
314 void MCWinCOFFStreamer::emitLocalCommonSymbol(MCSymbol
*S
, uint64_t Size
,
315 Align ByteAlignment
) {
316 auto *Symbol
= cast
<MCSymbolCOFF
>(S
);
318 MCSection
*Section
= getContext().getObjectFileInfo()->getBSSSection();
320 switchSection(Section
);
321 emitValueToAlignment(ByteAlignment
, 0, 1, 0);
323 Symbol
->setExternal(false);
328 void MCWinCOFFStreamer::emitWeakReference(MCSymbol
*AliasS
,
329 const MCSymbol
*Symbol
) {
330 auto *Alias
= cast
<MCSymbolCOFF
>(AliasS
);
331 emitSymbolAttribute(Alias
, MCSA_Weak
);
333 getAssembler().registerSymbol(*Symbol
);
334 Alias
->setVariableValue(MCSymbolRefExpr::create(
335 Symbol
, MCSymbolRefExpr::VK_WEAKREF
, getContext()));
338 void MCWinCOFFStreamer::emitZerofill(MCSection
*Section
, MCSymbol
*Symbol
,
339 uint64_t Size
, Align ByteAlignment
,
341 llvm_unreachable("not implemented");
344 void MCWinCOFFStreamer::emitTBSSSymbol(MCSection
*Section
, MCSymbol
*Symbol
,
345 uint64_t Size
, Align ByteAlignment
) {
346 llvm_unreachable("not implemented");
349 // TODO: Implement this if you want to emit .comment section in COFF obj files.
350 void MCWinCOFFStreamer::emitIdent(StringRef IdentString
) {
351 llvm_unreachable("not implemented");
354 void MCWinCOFFStreamer::emitWinEHHandlerData(SMLoc Loc
) {
355 llvm_unreachable("not implemented");
358 void MCWinCOFFStreamer::emitCGProfileEntry(const MCSymbolRefExpr
*From
,
359 const MCSymbolRefExpr
*To
,
361 // Ignore temporary symbols for now.
362 if (!From
->getSymbol().isTemporary() && !To
->getSymbol().isTemporary())
363 getWriter().getCGProfile().push_back({From
, To
, Count
});
366 void MCWinCOFFStreamer::finalizeCGProfileEntry(const MCSymbolRefExpr
*&SRE
) {
367 const MCSymbol
*S
= &SRE
->getSymbol();
368 if (getAssembler().registerSymbol(*S
))
369 cast
<MCSymbolCOFF
>(S
)->setExternal(true);
372 void MCWinCOFFStreamer::finishImpl() {
373 MCAssembler
&Asm
= getAssembler();
374 if (Asm
.getWriter().getEmitAddrsigSection()) {
375 // Register the section.
376 switchSection(Asm
.getContext().getCOFFSection(".llvm_addrsig",
377 COFF::IMAGE_SCN_LNK_REMOVE
));
379 if (!Asm
.getWriter().getCGProfile().empty()) {
380 for (auto &E
: Asm
.getWriter().getCGProfile()) {
381 finalizeCGProfileEntry(E
.From
);
382 finalizeCGProfileEntry(E
.To
);
384 switchSection(Asm
.getContext().getCOFFSection(".llvm.call-graph-profile",
385 COFF::IMAGE_SCN_LNK_REMOVE
));
388 MCObjectStreamer::finishImpl();
391 void MCWinCOFFStreamer::Error(const Twine
&Msg
) const {
392 getContext().reportError(SMLoc(), Msg
);