1 //===- lib/MC/MCAsmStreamer.cpp - Text Assembly Output ----------*- C++ -*-===//
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 #include "llvm/ADT/Optional.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/StringExtras.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCAssembler.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCCodeView.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCFixupKindInfo.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCObjectFileInfo.h"
25 #include "llvm/MC/MCObjectWriter.h"
26 #include "llvm/MC/MCRegisterInfo.h"
27 #include "llvm/MC/MCSectionMachO.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/Format.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/LEB128.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/TargetRegistry.h"
42 class MCAsmStreamer final
: public MCStreamer
{
43 std::unique_ptr
<formatted_raw_ostream
> OSOwner
;
44 formatted_raw_ostream
&OS
;
46 std::unique_ptr
<MCInstPrinter
> InstPrinter
;
47 std::unique_ptr
<MCAssembler
> Assembler
;
49 SmallString
<128> ExplicitCommentToEmit
;
50 SmallString
<128> CommentToEmit
;
51 raw_svector_ostream CommentStream
;
52 raw_null_ostream NullStream
;
54 unsigned IsVerboseAsm
: 1;
55 unsigned ShowInst
: 1;
56 unsigned UseDwarfDirectory
: 1;
58 void EmitRegisterName(int64_t Register
);
59 void EmitCFIStartProcImpl(MCDwarfFrameInfo
&Frame
) override
;
60 void EmitCFIEndProcImpl(MCDwarfFrameInfo
&Frame
) override
;
63 MCAsmStreamer(MCContext
&Context
, std::unique_ptr
<formatted_raw_ostream
> os
,
64 bool isVerboseAsm
, bool useDwarfDirectory
,
65 MCInstPrinter
*printer
, std::unique_ptr
<MCCodeEmitter
> emitter
,
66 std::unique_ptr
<MCAsmBackend
> asmbackend
, bool showInst
)
67 : MCStreamer(Context
), OSOwner(std::move(os
)), OS(*OSOwner
),
68 MAI(Context
.getAsmInfo()), InstPrinter(printer
),
69 Assembler(llvm::make_unique
<MCAssembler
>(
70 Context
, std::move(asmbackend
), std::move(emitter
),
71 (asmbackend
) ? asmbackend
->createObjectWriter(NullStream
)
73 CommentStream(CommentToEmit
), IsVerboseAsm(isVerboseAsm
),
74 ShowInst(showInst
), UseDwarfDirectory(useDwarfDirectory
) {
77 InstPrinter
->setCommentStream(CommentStream
);
80 MCAssembler
&getAssembler() { return *Assembler
; }
81 MCAssembler
*getAssemblerPtr() override
{ return nullptr; }
83 inline void EmitEOL() {
84 // Dump Explicit Comments here.
85 emitExplicitComments();
86 // If we don't have any comments, just emit a \n.
94 void EmitSyntaxDirective() override
;
96 void EmitCommentsAndEOL();
98 /// Return true if this streamer supports verbose assembly at all.
99 bool isVerboseAsm() const override
{ return IsVerboseAsm
; }
101 /// Do we support EmitRawText?
102 bool hasRawTextSupport() const override
{ return true; }
104 /// Add a comment that can be emitted to the generated .s file to make the
105 /// output of the compiler more readable. This only affects the MCAsmStreamer
106 /// and only when verbose assembly output is enabled.
107 void AddComment(const Twine
&T
, bool EOL
= true) override
;
109 /// Add a comment showing the encoding of an instruction.
110 void AddEncodingComment(const MCInst
&Inst
, const MCSubtargetInfo
&);
112 /// Return a raw_ostream that comments can be written to.
113 /// Unlike AddComment, you are required to terminate comments with \n if you
115 raw_ostream
&GetCommentOS() override
{
117 return nulls(); // Discard comments unless in verbose asm mode.
118 return CommentStream
;
121 void emitRawComment(const Twine
&T
, bool TabPrefix
= true) override
;
123 void addExplicitComment(const Twine
&T
) override
;
124 void emitExplicitComments() override
;
126 /// Emit a blank line to a .s file to pretty it up.
127 void AddBlankLine() override
{
131 /// @name MCStreamer Interface
134 void ChangeSection(MCSection
*Section
, const MCExpr
*Subsection
) override
;
136 void emitELFSymverDirective(StringRef AliasName
,
137 const MCSymbol
*Aliasee
) override
;
139 void EmitLOHDirective(MCLOHType Kind
, const MCLOHArgs
&Args
) override
;
140 void EmitLabel(MCSymbol
*Symbol
, SMLoc Loc
= SMLoc()) override
;
142 void EmitAssemblerFlag(MCAssemblerFlag Flag
) override
;
143 void EmitLinkerOptions(ArrayRef
<std::string
> Options
) override
;
144 void EmitDataRegion(MCDataRegionType Kind
) override
;
145 void EmitVersionMin(MCVersionMinType Kind
, unsigned Major
, unsigned Minor
,
146 unsigned Update
, VersionTuple SDKVersion
) override
;
147 void EmitBuildVersion(unsigned Platform
, unsigned Major
, unsigned Minor
,
148 unsigned Update
, VersionTuple SDKVersion
) override
;
149 void EmitThumbFunc(MCSymbol
*Func
) override
;
151 void EmitAssignment(MCSymbol
*Symbol
, const MCExpr
*Value
) override
;
152 void EmitWeakReference(MCSymbol
*Alias
, const MCSymbol
*Symbol
) override
;
153 bool EmitSymbolAttribute(MCSymbol
*Symbol
, MCSymbolAttr Attribute
) override
;
155 void EmitSymbolDesc(MCSymbol
*Symbol
, unsigned DescValue
) override
;
156 void BeginCOFFSymbolDef(const MCSymbol
*Symbol
) override
;
157 void EmitCOFFSymbolStorageClass(int StorageClass
) override
;
158 void EmitCOFFSymbolType(int Type
) override
;
159 void EndCOFFSymbolDef() override
;
160 void EmitCOFFSafeSEH(MCSymbol
const *Symbol
) override
;
161 void EmitCOFFSymbolIndex(MCSymbol
const *Symbol
) override
;
162 void EmitCOFFSectionIndex(MCSymbol
const *Symbol
) override
;
163 void EmitCOFFSecRel32(MCSymbol
const *Symbol
, uint64_t Offset
) override
;
164 void EmitCOFFImgRel32(MCSymbol
const *Symbol
, int64_t Offset
) override
;
165 void emitELFSize(MCSymbol
*Symbol
, const MCExpr
*Value
) override
;
166 void EmitCommonSymbol(MCSymbol
*Symbol
, uint64_t Size
,
167 unsigned ByteAlignment
) override
;
169 /// Emit a local common (.lcomm) symbol.
171 /// @param Symbol - The common symbol to emit.
172 /// @param Size - The size of the common symbol.
173 /// @param ByteAlignment - The alignment of the common symbol in bytes.
174 void EmitLocalCommonSymbol(MCSymbol
*Symbol
, uint64_t Size
,
175 unsigned ByteAlignment
) override
;
177 void EmitZerofill(MCSection
*Section
, MCSymbol
*Symbol
= nullptr,
178 uint64_t Size
= 0, unsigned ByteAlignment
= 0,
179 SMLoc Loc
= SMLoc()) override
;
181 void EmitTBSSSymbol(MCSection
*Section
, MCSymbol
*Symbol
, uint64_t Size
,
182 unsigned ByteAlignment
= 0) override
;
184 void EmitBinaryData(StringRef Data
) override
;
186 void EmitBytes(StringRef Data
) override
;
188 void EmitValueImpl(const MCExpr
*Value
, unsigned Size
,
189 SMLoc Loc
= SMLoc()) override
;
190 void EmitIntValue(uint64_t Value
, unsigned Size
) override
;
192 void EmitULEB128Value(const MCExpr
*Value
) override
;
194 void EmitSLEB128Value(const MCExpr
*Value
) override
;
196 void EmitDTPRel32Value(const MCExpr
*Value
) override
;
197 void EmitDTPRel64Value(const MCExpr
*Value
) override
;
198 void EmitTPRel32Value(const MCExpr
*Value
) override
;
199 void EmitTPRel64Value(const MCExpr
*Value
) override
;
201 void EmitGPRel64Value(const MCExpr
*Value
) override
;
203 void EmitGPRel32Value(const MCExpr
*Value
) override
;
205 void emitFill(const MCExpr
&NumBytes
, uint64_t FillValue
,
206 SMLoc Loc
= SMLoc()) override
;
208 void emitFill(const MCExpr
&NumValues
, int64_t Size
, int64_t Expr
,
209 SMLoc Loc
= SMLoc()) override
;
211 void EmitValueToAlignment(unsigned ByteAlignment
, int64_t Value
= 0,
212 unsigned ValueSize
= 1,
213 unsigned MaxBytesToEmit
= 0) override
;
215 void EmitCodeAlignment(unsigned ByteAlignment
,
216 unsigned MaxBytesToEmit
= 0) override
;
218 void emitValueToOffset(const MCExpr
*Offset
,
222 void EmitFileDirective(StringRef Filename
) override
;
223 Expected
<unsigned> tryEmitDwarfFileDirective(unsigned FileNo
,
226 MD5::MD5Result
*Checksum
= 0,
227 Optional
<StringRef
> Source
= None
,
228 unsigned CUID
= 0) override
;
229 void emitDwarfFile0Directive(StringRef Directory
, StringRef Filename
,
230 MD5::MD5Result
*Checksum
,
231 Optional
<StringRef
> Source
,
232 unsigned CUID
= 0) override
;
233 void EmitDwarfLocDirective(unsigned FileNo
, unsigned Line
,
234 unsigned Column
, unsigned Flags
,
235 unsigned Isa
, unsigned Discriminator
,
236 StringRef FileName
) override
;
237 MCSymbol
*getDwarfLineTableSymbol(unsigned CUID
) override
;
239 bool EmitCVFileDirective(unsigned FileNo
, StringRef Filename
,
240 ArrayRef
<uint8_t> Checksum
,
241 unsigned ChecksumKind
) override
;
242 bool EmitCVFuncIdDirective(unsigned FuncId
) override
;
243 bool EmitCVInlineSiteIdDirective(unsigned FunctionId
, unsigned IAFunc
,
244 unsigned IAFile
, unsigned IALine
,
245 unsigned IACol
, SMLoc Loc
) override
;
246 void EmitCVLocDirective(unsigned FunctionId
, unsigned FileNo
, unsigned Line
,
247 unsigned Column
, bool PrologueEnd
, bool IsStmt
,
248 StringRef FileName
, SMLoc Loc
) override
;
249 void EmitCVLinetableDirective(unsigned FunctionId
, const MCSymbol
*FnStart
,
250 const MCSymbol
*FnEnd
) override
;
251 void EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId
,
252 unsigned SourceFileId
,
253 unsigned SourceLineNum
,
254 const MCSymbol
*FnStartSym
,
255 const MCSymbol
*FnEndSym
) override
;
256 void EmitCVDefRangeDirective(
257 ArrayRef
<std::pair
<const MCSymbol
*, const MCSymbol
*>> Ranges
,
258 StringRef FixedSizePortion
) override
;
259 void EmitCVStringTableDirective() override
;
260 void EmitCVFileChecksumsDirective() override
;
261 void EmitCVFileChecksumOffsetDirective(unsigned FileNo
) override
;
262 void EmitCVFPOData(const MCSymbol
*ProcSym
, SMLoc L
) override
;
264 void EmitIdent(StringRef IdentString
) override
;
265 void EmitCFIBKeyFrame() override
;
266 void EmitCFISections(bool EH
, bool Debug
) override
;
267 void EmitCFIDefCfa(int64_t Register
, int64_t Offset
) override
;
268 void EmitCFIDefCfaOffset(int64_t Offset
) override
;
269 void EmitCFIDefCfaRegister(int64_t Register
) override
;
270 void EmitCFIOffset(int64_t Register
, int64_t Offset
) override
;
271 void EmitCFIPersonality(const MCSymbol
*Sym
, unsigned Encoding
) override
;
272 void EmitCFILsda(const MCSymbol
*Sym
, unsigned Encoding
) override
;
273 void EmitCFIRememberState() override
;
274 void EmitCFIRestoreState() override
;
275 void EmitCFIRestore(int64_t Register
) override
;
276 void EmitCFISameValue(int64_t Register
) override
;
277 void EmitCFIRelOffset(int64_t Register
, int64_t Offset
) override
;
278 void EmitCFIAdjustCfaOffset(int64_t Adjustment
) override
;
279 void EmitCFIEscape(StringRef Values
) override
;
280 void EmitCFIGnuArgsSize(int64_t Size
) override
;
281 void EmitCFISignalFrame() override
;
282 void EmitCFIUndefined(int64_t Register
) override
;
283 void EmitCFIRegister(int64_t Register1
, int64_t Register2
) override
;
284 void EmitCFIWindowSave() override
;
285 void EmitCFINegateRAState() override
;
286 void EmitCFIReturnColumn(int64_t Register
) override
;
288 void EmitWinCFIStartProc(const MCSymbol
*Symbol
, SMLoc Loc
) override
;
289 void EmitWinCFIEndProc(SMLoc Loc
) override
;
290 void EmitWinCFIFuncletOrFuncEnd(SMLoc Loc
) override
;
291 void EmitWinCFIStartChained(SMLoc Loc
) override
;
292 void EmitWinCFIEndChained(SMLoc Loc
) override
;
293 void EmitWinCFIPushReg(unsigned Register
, SMLoc Loc
) override
;
294 void EmitWinCFISetFrame(unsigned Register
, unsigned Offset
,
296 void EmitWinCFIAllocStack(unsigned Size
, SMLoc Loc
) override
;
297 void EmitWinCFISaveReg(unsigned Register
, unsigned Offset
,
299 void EmitWinCFISaveXMM(unsigned Register
, unsigned Offset
,
301 void EmitWinCFIPushFrame(bool Code
, SMLoc Loc
) override
;
302 void EmitWinCFIEndProlog(SMLoc Loc
) override
;
304 void EmitWinEHHandler(const MCSymbol
*Sym
, bool Unwind
, bool Except
,
306 void EmitWinEHHandlerData(SMLoc Loc
) override
;
308 void emitCGProfileEntry(const MCSymbolRefExpr
*From
,
309 const MCSymbolRefExpr
*To
, uint64_t Count
) override
;
311 void EmitInstruction(const MCInst
&Inst
, const MCSubtargetInfo
&STI
) override
;
313 void EmitBundleAlignMode(unsigned AlignPow2
) override
;
314 void EmitBundleLock(bool AlignToEnd
) override
;
315 void EmitBundleUnlock() override
;
317 bool EmitRelocDirective(const MCExpr
&Offset
, StringRef Name
,
318 const MCExpr
*Expr
, SMLoc Loc
,
319 const MCSubtargetInfo
&STI
) override
;
321 void EmitAddrsig() override
;
322 void EmitAddrsigSym(const MCSymbol
*Sym
) override
;
324 /// If this file is backed by an assembly streamer, this dumps the specified
325 /// string in the output .s file. This capability is indicated by the
326 /// hasRawTextSupport() predicate.
327 void EmitRawTextImpl(StringRef String
) override
;
329 void FinishImpl() override
;
332 } // end anonymous namespace.
334 void MCAsmStreamer::AddComment(const Twine
&T
, bool EOL
) {
335 if (!IsVerboseAsm
) return;
337 T
.toVector(CommentToEmit
);
340 CommentToEmit
.push_back('\n'); // Place comment in a new line.
343 void MCAsmStreamer::EmitCommentsAndEOL() {
344 if (CommentToEmit
.empty() && CommentStream
.GetNumBytesInBuffer() == 0) {
349 StringRef Comments
= CommentToEmit
;
351 assert(Comments
.back() == '\n' &&
352 "Comment array not newline terminated");
354 // Emit a line of comments.
355 OS
.PadToColumn(MAI
->getCommentColumn());
356 size_t Position
= Comments
.find('\n');
357 OS
<< MAI
->getCommentString() << ' ' << Comments
.substr(0, Position
) <<'\n';
359 Comments
= Comments
.substr(Position
+1);
360 } while (!Comments
.empty());
362 CommentToEmit
.clear();
365 static inline int64_t truncateToSize(int64_t Value
, unsigned Bytes
) {
366 assert(Bytes
> 0 && Bytes
<= 8 && "Invalid size!");
367 return Value
& ((uint64_t) (int64_t) -1 >> (64 - Bytes
* 8));
370 void MCAsmStreamer::emitRawComment(const Twine
&T
, bool TabPrefix
) {
373 OS
<< MAI
->getCommentString() << T
;
377 void MCAsmStreamer::addExplicitComment(const Twine
&T
) {
378 StringRef c
= T
.getSingleStringRef();
379 if (c
.equals(StringRef(MAI
->getSeparatorString())))
381 if (c
.startswith(StringRef("//"))) {
382 ExplicitCommentToEmit
.append("\t");
383 ExplicitCommentToEmit
.append(MAI
->getCommentString());
385 ExplicitCommentToEmit
.append(c
.slice(2, c
.size()).str());
386 } else if (c
.startswith(StringRef("/*"))) {
387 size_t p
= 2, len
= c
.size() - 2;
388 // emit each line in comment as separate newline.
390 size_t newp
= std::min(len
, c
.find_first_of("\r\n", p
));
391 ExplicitCommentToEmit
.append("\t");
392 ExplicitCommentToEmit
.append(MAI
->getCommentString());
393 ExplicitCommentToEmit
.append(c
.slice(p
, newp
).str());
394 // If we have another line in this comment add line
396 ExplicitCommentToEmit
.append("\n");
399 } else if (c
.startswith(StringRef(MAI
->getCommentString()))) {
400 ExplicitCommentToEmit
.append("\t");
401 ExplicitCommentToEmit
.append(c
.str());
402 } else if (c
.front() == '#') {
404 ExplicitCommentToEmit
.append("\t");
405 ExplicitCommentToEmit
.append(MAI
->getCommentString());
406 ExplicitCommentToEmit
.append(c
.slice(1, c
.size()).str());
408 assert(false && "Unexpected Assembly Comment");
409 // full line comments immediately output
410 if (c
.back() == '\n')
411 emitExplicitComments();
414 void MCAsmStreamer::emitExplicitComments() {
415 StringRef Comments
= ExplicitCommentToEmit
;
416 if (!Comments
.empty())
418 ExplicitCommentToEmit
.clear();
421 void MCAsmStreamer::ChangeSection(MCSection
*Section
,
422 const MCExpr
*Subsection
) {
423 assert(Section
&& "Cannot switch to a null section!");
424 if (MCTargetStreamer
*TS
= getTargetStreamer()) {
425 TS
->changeSection(getCurrentSectionOnly(), Section
, Subsection
, OS
);
427 Section
->PrintSwitchToSection(
428 *MAI
, getContext().getObjectFileInfo()->getTargetTriple(), OS
,
433 void MCAsmStreamer::emitELFSymverDirective(StringRef AliasName
,
434 const MCSymbol
*Aliasee
) {
436 Aliasee
->print(OS
, MAI
);
437 OS
<< ", " << AliasName
;
441 void MCAsmStreamer::EmitLabel(MCSymbol
*Symbol
, SMLoc Loc
) {
442 MCStreamer::EmitLabel(Symbol
, Loc
);
444 Symbol
->print(OS
, MAI
);
445 OS
<< MAI
->getLabelSuffix();
450 void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind
, const MCLOHArgs
&Args
) {
451 StringRef str
= MCLOHIdToName(Kind
);
454 int NbArgs
= MCLOHIdToNbArgs(Kind
);
455 assert(NbArgs
!= -1 && ((size_t)NbArgs
) == Args
.size() && "Malformed LOH!");
456 assert(str
!= "" && "Invalid LOH name");
459 OS
<< "\t" << MCLOHDirectiveName() << " " << str
<< "\t";
461 for (const MCSymbol
*Arg
: Args
) {
470 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag
) {
472 case MCAF_SyntaxUnified
: OS
<< "\t.syntax unified"; break;
473 case MCAF_SubsectionsViaSymbols
: OS
<< ".subsections_via_symbols"; break;
474 case MCAF_Code16
: OS
<< '\t'<< MAI
->getCode16Directive();break;
475 case MCAF_Code32
: OS
<< '\t'<< MAI
->getCode32Directive();break;
476 case MCAF_Code64
: OS
<< '\t'<< MAI
->getCode64Directive();break;
481 void MCAsmStreamer::EmitLinkerOptions(ArrayRef
<std::string
> Options
) {
482 assert(!Options
.empty() && "At least one option is required!");
483 OS
<< "\t.linker_option \"" << Options
[0] << '"';
484 for (ArrayRef
<std::string
>::iterator it
= Options
.begin() + 1,
485 ie
= Options
.end(); it
!= ie
; ++it
) {
486 OS
<< ", " << '"' << *it
<< '"';
491 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind
) {
492 if (!MAI
->doesSupportDataRegionDirectives())
495 case MCDR_DataRegion
: OS
<< "\t.data_region"; break;
496 case MCDR_DataRegionJT8
: OS
<< "\t.data_region jt8"; break;
497 case MCDR_DataRegionJT16
: OS
<< "\t.data_region jt16"; break;
498 case MCDR_DataRegionJT32
: OS
<< "\t.data_region jt32"; break;
499 case MCDR_DataRegionEnd
: OS
<< "\t.end_data_region"; break;
504 static const char *getVersionMinDirective(MCVersionMinType Type
) {
506 case MCVM_WatchOSVersionMin
: return ".watchos_version_min";
507 case MCVM_TvOSVersionMin
: return ".tvos_version_min";
508 case MCVM_IOSVersionMin
: return ".ios_version_min";
509 case MCVM_OSXVersionMin
: return ".macosx_version_min";
511 llvm_unreachable("Invalid MC version min type");
514 static void EmitSDKVersionSuffix(raw_ostream
&OS
,
515 const VersionTuple
&SDKVersion
) {
516 if (SDKVersion
.empty())
518 OS
<< '\t' << "sdk_version " << SDKVersion
.getMajor();
519 if (auto Minor
= SDKVersion
.getMinor()) {
520 OS
<< ", " << *Minor
;
521 if (auto Subminor
= SDKVersion
.getSubminor()) {
522 OS
<< ", " << *Subminor
;
527 void MCAsmStreamer::EmitVersionMin(MCVersionMinType Type
, unsigned Major
,
528 unsigned Minor
, unsigned Update
,
529 VersionTuple SDKVersion
) {
530 OS
<< '\t' << getVersionMinDirective(Type
) << ' ' << Major
<< ", " << Minor
;
532 OS
<< ", " << Update
;
533 EmitSDKVersionSuffix(OS
, SDKVersion
);
537 static const char *getPlatformName(MachO::PlatformType Type
) {
539 case MachO::PLATFORM_MACOS
: return "macos";
540 case MachO::PLATFORM_IOS
: return "ios";
541 case MachO::PLATFORM_TVOS
: return "tvos";
542 case MachO::PLATFORM_WATCHOS
: return "watchos";
543 case MachO::PLATFORM_BRIDGEOS
: return "bridgeos";
544 case MachO::PLATFORM_IOSSIMULATOR
: return "iossimulator";
545 case MachO::PLATFORM_TVOSSIMULATOR
: return "tvossimulator";
546 case MachO::PLATFORM_WATCHOSSIMULATOR
: return "watchossimulator";
548 llvm_unreachable("Invalid Mach-O platform type");
551 void MCAsmStreamer::EmitBuildVersion(unsigned Platform
, unsigned Major
,
552 unsigned Minor
, unsigned Update
,
553 VersionTuple SDKVersion
) {
554 const char *PlatformName
= getPlatformName((MachO::PlatformType
)Platform
);
555 OS
<< "\t.build_version " << PlatformName
<< ", " << Major
<< ", " << Minor
;
557 OS
<< ", " << Update
;
558 EmitSDKVersionSuffix(OS
, SDKVersion
);
562 void MCAsmStreamer::EmitThumbFunc(MCSymbol
*Func
) {
563 // This needs to emit to a temporary string to get properly quoted
564 // MCSymbols when they have spaces in them.
565 OS
<< "\t.thumb_func";
566 // Only Mach-O hasSubsectionsViaSymbols()
567 if (MAI
->hasSubsectionsViaSymbols()) {
569 Func
->print(OS
, MAI
);
574 void MCAsmStreamer::EmitAssignment(MCSymbol
*Symbol
, const MCExpr
*Value
) {
575 // Do not emit a .set on inlined target assignments.
577 if (auto *E
= dyn_cast
<MCTargetExpr
>(Value
))
578 if (E
->inlineAssignedExpr())
582 Symbol
->print(OS
, MAI
);
584 Value
->print(OS
, MAI
);
589 MCStreamer::EmitAssignment(Symbol
, Value
);
592 void MCAsmStreamer::EmitWeakReference(MCSymbol
*Alias
, const MCSymbol
*Symbol
) {
594 Alias
->print(OS
, MAI
);
596 Symbol
->print(OS
, MAI
);
600 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol
*Symbol
,
601 MCSymbolAttr Attribute
) {
603 case MCSA_Invalid
: llvm_unreachable("Invalid symbol attribute");
604 case MCSA_ELF_TypeFunction
: /// .type _foo, STT_FUNC # aka @function
605 case MCSA_ELF_TypeIndFunction
: /// .type _foo, STT_GNU_IFUNC
606 case MCSA_ELF_TypeObject
: /// .type _foo, STT_OBJECT # aka @object
607 case MCSA_ELF_TypeTLS
: /// .type _foo, STT_TLS # aka @tls_object
608 case MCSA_ELF_TypeCommon
: /// .type _foo, STT_COMMON # aka @common
609 case MCSA_ELF_TypeNoType
: /// .type _foo, STT_NOTYPE # aka @notype
610 case MCSA_ELF_TypeGnuUniqueObject
: /// .type _foo, @gnu_unique_object
611 if (!MAI
->hasDotTypeDotSizeDirective())
612 return false; // Symbol attribute not supported
614 Symbol
->print(OS
, MAI
);
615 OS
<< ',' << ((MAI
->getCommentString()[0] != '@') ? '@' : '%');
617 default: return false;
618 case MCSA_ELF_TypeFunction
: OS
<< "function"; break;
619 case MCSA_ELF_TypeIndFunction
: OS
<< "gnu_indirect_function"; break;
620 case MCSA_ELF_TypeObject
: OS
<< "object"; break;
621 case MCSA_ELF_TypeTLS
: OS
<< "tls_object"; break;
622 case MCSA_ELF_TypeCommon
: OS
<< "common"; break;
623 case MCSA_ELF_TypeNoType
: OS
<< "notype"; break;
624 case MCSA_ELF_TypeGnuUniqueObject
: OS
<< "gnu_unique_object"; break;
628 case MCSA_Global
: // .globl/.global
629 OS
<< MAI
->getGlobalDirective();
631 case MCSA_Hidden
: OS
<< "\t.hidden\t"; break;
632 case MCSA_IndirectSymbol
: OS
<< "\t.indirect_symbol\t"; break;
633 case MCSA_Internal
: OS
<< "\t.internal\t"; break;
634 case MCSA_LazyReference
: OS
<< "\t.lazy_reference\t"; break;
635 case MCSA_Local
: OS
<< "\t.local\t"; break;
636 case MCSA_NoDeadStrip
:
637 if (!MAI
->hasNoDeadStrip())
639 OS
<< "\t.no_dead_strip\t";
641 case MCSA_SymbolResolver
: OS
<< "\t.symbol_resolver\t"; break;
642 case MCSA_AltEntry
: OS
<< "\t.alt_entry\t"; break;
643 case MCSA_PrivateExtern
:
644 OS
<< "\t.private_extern\t";
646 case MCSA_Protected
: OS
<< "\t.protected\t"; break;
647 case MCSA_Reference
: OS
<< "\t.reference\t"; break;
648 case MCSA_Weak
: OS
<< MAI
->getWeakDirective(); break;
649 case MCSA_WeakDefinition
:
650 OS
<< "\t.weak_definition\t";
653 case MCSA_WeakReference
: OS
<< MAI
->getWeakRefDirective(); break;
654 case MCSA_WeakDefAutoPrivate
: OS
<< "\t.weak_def_can_be_hidden\t"; break;
656 // Assemblers currently do not support a .cold directive.
660 Symbol
->print(OS
, MAI
);
666 void MCAsmStreamer::EmitSymbolDesc(MCSymbol
*Symbol
, unsigned DescValue
) {
667 OS
<< ".desc" << ' ';
668 Symbol
->print(OS
, MAI
);
669 OS
<< ',' << DescValue
;
673 void MCAsmStreamer::EmitSyntaxDirective() {
674 if (MAI
->getAssemblerDialect() == 1) {
675 OS
<< "\t.intel_syntax noprefix";
678 // FIXME: Currently emit unprefix'ed registers.
679 // The intel_syntax directive has one optional argument
680 // with may have a value of prefix or noprefix.
683 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol
*Symbol
) {
685 Symbol
->print(OS
, MAI
);
690 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass
) {
691 OS
<< "\t.scl\t" << StorageClass
<< ';';
695 void MCAsmStreamer::EmitCOFFSymbolType (int Type
) {
696 OS
<< "\t.type\t" << Type
<< ';';
700 void MCAsmStreamer::EndCOFFSymbolDef() {
705 void MCAsmStreamer::EmitCOFFSafeSEH(MCSymbol
const *Symbol
) {
706 OS
<< "\t.safeseh\t";
707 Symbol
->print(OS
, MAI
);
711 void MCAsmStreamer::EmitCOFFSymbolIndex(MCSymbol
const *Symbol
) {
713 Symbol
->print(OS
, MAI
);
717 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol
const *Symbol
) {
719 Symbol
->print(OS
, MAI
);
723 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol
const *Symbol
, uint64_t Offset
) {
724 OS
<< "\t.secrel32\t";
725 Symbol
->print(OS
, MAI
);
731 void MCAsmStreamer::EmitCOFFImgRel32(MCSymbol
const *Symbol
, int64_t Offset
) {
733 Symbol
->print(OS
, MAI
);
737 OS
<< '-' << -Offset
;
741 void MCAsmStreamer::emitELFSize(MCSymbol
*Symbol
, const MCExpr
*Value
) {
742 assert(MAI
->hasDotTypeDotSizeDirective());
744 Symbol
->print(OS
, MAI
);
746 Value
->print(OS
, MAI
);
750 void MCAsmStreamer::EmitCommonSymbol(MCSymbol
*Symbol
, uint64_t Size
,
751 unsigned ByteAlignment
) {
753 Symbol
->print(OS
, MAI
);
756 if (ByteAlignment
!= 0) {
757 if (MAI
->getCOMMDirectiveAlignmentIsInBytes())
758 OS
<< ',' << ByteAlignment
;
760 OS
<< ',' << Log2_32(ByteAlignment
);
765 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol
*Symbol
, uint64_t Size
,
766 unsigned ByteAlign
) {
768 Symbol
->print(OS
, MAI
);
772 switch (MAI
->getLCOMMDirectiveAlignmentType()) {
773 case LCOMM::NoAlignment
:
774 llvm_unreachable("alignment not supported on .lcomm!");
775 case LCOMM::ByteAlignment
:
776 OS
<< ',' << ByteAlign
;
778 case LCOMM::Log2Alignment
:
779 assert(isPowerOf2_32(ByteAlign
) && "alignment must be a power of 2");
780 OS
<< ',' << Log2_32(ByteAlign
);
787 void MCAsmStreamer::EmitZerofill(MCSection
*Section
, MCSymbol
*Symbol
,
788 uint64_t Size
, unsigned ByteAlignment
,
791 AssignFragment(Symbol
, &Section
->getDummyFragment());
793 // Note: a .zerofill directive does not switch sections.
796 assert(Section
->getVariant() == MCSection::SV_MachO
&&
797 ".zerofill is a Mach-O specific directive");
798 // This is a mach-o specific directive.
800 const MCSectionMachO
*MOSection
= ((const MCSectionMachO
*)Section
);
801 OS
<< MOSection
->getSegmentName() << "," << MOSection
->getSectionName();
805 Symbol
->print(OS
, MAI
);
807 if (ByteAlignment
!= 0)
808 OS
<< ',' << Log2_32(ByteAlignment
);
813 // .tbss sym, size, align
814 // This depends that the symbol has already been mangled from the original,
816 void MCAsmStreamer::EmitTBSSSymbol(MCSection
*Section
, MCSymbol
*Symbol
,
817 uint64_t Size
, unsigned ByteAlignment
) {
818 AssignFragment(Symbol
, &Section
->getDummyFragment());
820 assert(Symbol
&& "Symbol shouldn't be NULL!");
821 // Instead of using the Section we'll just use the shortcut.
823 assert(Section
->getVariant() == MCSection::SV_MachO
&&
824 ".zerofill is a Mach-O specific directive");
825 // This is a mach-o specific directive and section.
828 Symbol
->print(OS
, MAI
);
831 // Output align if we have it. We default to 1 so don't bother printing
833 if (ByteAlignment
> 1) OS
<< ", " << Log2_32(ByteAlignment
);
838 static inline char toOctal(int X
) { return (X
&7)+'0'; }
840 static void PrintQuotedString(StringRef Data
, raw_ostream
&OS
) {
843 for (unsigned i
= 0, e
= Data
.size(); i
!= e
; ++i
) {
844 unsigned char C
= Data
[i
];
845 if (C
== '"' || C
== '\\') {
846 OS
<< '\\' << (char)C
;
850 if (isPrint((unsigned char)C
)) {
856 case '\b': OS
<< "\\b"; break;
857 case '\f': OS
<< "\\f"; break;
858 case '\n': OS
<< "\\n"; break;
859 case '\r': OS
<< "\\r"; break;
860 case '\t': OS
<< "\\t"; break;
863 OS
<< toOctal(C
>> 6);
864 OS
<< toOctal(C
>> 3);
865 OS
<< toOctal(C
>> 0);
873 void MCAsmStreamer::EmitBytes(StringRef Data
) {
874 assert(getCurrentSectionOnly() &&
875 "Cannot emit contents before setting section!");
876 if (Data
.empty()) return;
878 // If only single byte is provided or no ascii or asciz directives is
879 // supported, emit as vector of 8bits data.
880 if (Data
.size() == 1 ||
881 !(MAI
->getAscizDirective() || MAI
->getAsciiDirective())) {
882 if (MCTargetStreamer
*TS
= getTargetStreamer()) {
883 TS
->emitRawBytes(Data
);
885 const char *Directive
= MAI
->getData8bitsDirective();
886 for (const unsigned char C
: Data
.bytes()) {
887 OS
<< Directive
<< (unsigned)C
;
894 // If the data ends with 0 and the target supports .asciz, use it, otherwise
896 if (MAI
->getAscizDirective() && Data
.back() == 0) {
897 OS
<< MAI
->getAscizDirective();
898 Data
= Data
.substr(0, Data
.size()-1);
900 OS
<< MAI
->getAsciiDirective();
903 PrintQuotedString(Data
, OS
);
907 void MCAsmStreamer::EmitBinaryData(StringRef Data
) {
908 // This is binary data. Print it in a grid of hex bytes for readability.
909 const size_t Cols
= 4;
910 for (size_t I
= 0, EI
= alignTo(Data
.size(), Cols
); I
< EI
; I
+= Cols
) {
911 size_t J
= I
, EJ
= std::min(I
+ Cols
, Data
.size());
913 OS
<< MAI
->getData8bitsDirective();
914 for (; J
< EJ
- 1; ++J
)
915 OS
<< format("0x%02x", uint8_t(Data
[J
])) << ", ";
916 OS
<< format("0x%02x", uint8_t(Data
[J
]));
921 void MCAsmStreamer::EmitIntValue(uint64_t Value
, unsigned Size
) {
922 EmitValue(MCConstantExpr::create(Value
, getContext()), Size
);
925 void MCAsmStreamer::EmitValueImpl(const MCExpr
*Value
, unsigned Size
,
927 assert(Size
<= 8 && "Invalid size");
928 assert(getCurrentSectionOnly() &&
929 "Cannot emit contents before setting section!");
930 const char *Directive
= nullptr;
933 case 1: Directive
= MAI
->getData8bitsDirective(); break;
934 case 2: Directive
= MAI
->getData16bitsDirective(); break;
935 case 4: Directive
= MAI
->getData32bitsDirective(); break;
936 case 8: Directive
= MAI
->getData64bitsDirective(); break;
941 if (!Value
->evaluateAsAbsolute(IntValue
))
942 report_fatal_error("Don't know how to emit this value.");
944 // We couldn't handle the requested integer size so we fallback by breaking
945 // the request down into several, smaller, integers.
946 // Since sizes greater or equal to "Size" are invalid, we use the greatest
947 // power of 2 that is less than "Size" as our largest piece of granularity.
948 bool IsLittleEndian
= MAI
->isLittleEndian();
949 for (unsigned Emitted
= 0; Emitted
!= Size
;) {
950 unsigned Remaining
= Size
- Emitted
;
951 // The size of our partial emission must be a power of two less than
953 unsigned EmissionSize
= PowerOf2Floor(std::min(Remaining
, Size
- 1));
954 // Calculate the byte offset of our partial emission taking into account
955 // the endianness of the target.
956 unsigned ByteOffset
=
957 IsLittleEndian
? Emitted
: (Remaining
- EmissionSize
);
958 uint64_t ValueToEmit
= IntValue
>> (ByteOffset
* 8);
959 // We truncate our partial emission to fit within the bounds of the
960 // emission domain. This produces nicer output and silences potential
961 // truncation warnings when round tripping through another assembler.
962 uint64_t Shift
= 64 - EmissionSize
* 8;
963 assert(Shift
< static_cast<uint64_t>(
964 std::numeric_limits
<unsigned long long>::digits
) &&
965 "undefined behavior");
966 ValueToEmit
&= ~0ULL >> Shift
;
967 EmitIntValue(ValueToEmit
, EmissionSize
);
968 Emitted
+= EmissionSize
;
973 assert(Directive
&& "Invalid size for machine code value!");
975 if (MCTargetStreamer
*TS
= getTargetStreamer()) {
976 TS
->emitValue(Value
);
978 Value
->print(OS
, MAI
);
983 void MCAsmStreamer::EmitULEB128Value(const MCExpr
*Value
) {
985 if (Value
->evaluateAsAbsolute(IntValue
)) {
986 EmitULEB128IntValue(IntValue
);
990 Value
->print(OS
, MAI
);
994 void MCAsmStreamer::EmitSLEB128Value(const MCExpr
*Value
) {
996 if (Value
->evaluateAsAbsolute(IntValue
)) {
997 EmitSLEB128IntValue(IntValue
);
1000 OS
<< "\t.sleb128 ";
1001 Value
->print(OS
, MAI
);
1005 void MCAsmStreamer::EmitDTPRel64Value(const MCExpr
*Value
) {
1006 assert(MAI
->getDTPRel64Directive() != nullptr);
1007 OS
<< MAI
->getDTPRel64Directive();
1008 Value
->print(OS
, MAI
);
1012 void MCAsmStreamer::EmitDTPRel32Value(const MCExpr
*Value
) {
1013 assert(MAI
->getDTPRel32Directive() != nullptr);
1014 OS
<< MAI
->getDTPRel32Directive();
1015 Value
->print(OS
, MAI
);
1019 void MCAsmStreamer::EmitTPRel64Value(const MCExpr
*Value
) {
1020 assert(MAI
->getTPRel64Directive() != nullptr);
1021 OS
<< MAI
->getTPRel64Directive();
1022 Value
->print(OS
, MAI
);
1026 void MCAsmStreamer::EmitTPRel32Value(const MCExpr
*Value
) {
1027 assert(MAI
->getTPRel32Directive() != nullptr);
1028 OS
<< MAI
->getTPRel32Directive();
1029 Value
->print(OS
, MAI
);
1033 void MCAsmStreamer::EmitGPRel64Value(const MCExpr
*Value
) {
1034 assert(MAI
->getGPRel64Directive() != nullptr);
1035 OS
<< MAI
->getGPRel64Directive();
1036 Value
->print(OS
, MAI
);
1040 void MCAsmStreamer::EmitGPRel32Value(const MCExpr
*Value
) {
1041 assert(MAI
->getGPRel32Directive() != nullptr);
1042 OS
<< MAI
->getGPRel32Directive();
1043 Value
->print(OS
, MAI
);
1047 void MCAsmStreamer::emitFill(const MCExpr
&NumBytes
, uint64_t FillValue
,
1049 int64_t IntNumBytes
;
1050 if (NumBytes
.evaluateAsAbsolute(IntNumBytes
) && IntNumBytes
== 0)
1053 if (const char *ZeroDirective
= MAI
->getZeroDirective()) {
1054 // FIXME: Emit location directives
1055 OS
<< ZeroDirective
;
1056 NumBytes
.print(OS
, MAI
);
1058 OS
<< ',' << (int)FillValue
;
1063 MCStreamer::emitFill(NumBytes
, FillValue
);
1066 void MCAsmStreamer::emitFill(const MCExpr
&NumValues
, int64_t Size
,
1067 int64_t Expr
, SMLoc Loc
) {
1068 // FIXME: Emit location directives
1070 NumValues
.print(OS
, MAI
);
1071 OS
<< ", " << Size
<< ", 0x";
1072 OS
.write_hex(truncateToSize(Expr
, 4));
1076 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment
, int64_t Value
,
1078 unsigned MaxBytesToEmit
) {
1079 // Some assemblers don't support non-power of two alignments, so we always
1080 // emit alignments as a power of two if possible.
1081 if (isPowerOf2_32(ByteAlignment
)) {
1082 switch (ValueSize
) {
1084 llvm_unreachable("Invalid size for machine code value!");
1086 OS
<< "\t.p2align\t";
1095 llvm_unreachable("Unsupported alignment size!");
1098 OS
<< Log2_32(ByteAlignment
);
1100 if (Value
|| MaxBytesToEmit
) {
1102 OS
.write_hex(truncateToSize(Value
, ValueSize
));
1105 OS
<< ", " << MaxBytesToEmit
;
1111 // Non-power of two alignment. This is not widely supported by assemblers.
1112 // FIXME: Parameterize this based on MAI.
1113 switch (ValueSize
) {
1114 default: llvm_unreachable("Invalid size for machine code value!");
1115 case 1: OS
<< ".balign"; break;
1116 case 2: OS
<< ".balignw"; break;
1117 case 4: OS
<< ".balignl"; break;
1118 case 8: llvm_unreachable("Unsupported alignment size!");
1121 OS
<< ' ' << ByteAlignment
;
1122 OS
<< ", " << truncateToSize(Value
, ValueSize
);
1124 OS
<< ", " << MaxBytesToEmit
;
1128 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment
,
1129 unsigned MaxBytesToEmit
) {
1130 // Emit with a text fill value.
1131 EmitValueToAlignment(ByteAlignment
, MAI
->getTextAlignFillValue(),
1135 void MCAsmStreamer::emitValueToOffset(const MCExpr
*Offset
,
1136 unsigned char Value
,
1138 // FIXME: Verify that Offset is associated with the current section.
1140 Offset
->print(OS
, MAI
);
1141 OS
<< ", " << (unsigned)Value
;
1145 void MCAsmStreamer::EmitFileDirective(StringRef Filename
) {
1146 assert(MAI
->hasSingleParameterDotFile());
1148 PrintQuotedString(Filename
, OS
);
1152 static void printDwarfFileDirective(unsigned FileNo
, StringRef Directory
,
1154 MD5::MD5Result
*Checksum
,
1155 Optional
<StringRef
> Source
,
1156 bool UseDwarfDirectory
,
1157 raw_svector_ostream
&OS
) {
1158 SmallString
<128> FullPathName
;
1160 if (!UseDwarfDirectory
&& !Directory
.empty()) {
1161 if (sys::path::is_absolute(Filename
))
1164 FullPathName
= Directory
;
1165 sys::path::append(FullPathName
, Filename
);
1167 Filename
= FullPathName
;
1171 OS
<< "\t.file\t" << FileNo
<< ' ';
1172 if (!Directory
.empty()) {
1173 PrintQuotedString(Directory
, OS
);
1176 PrintQuotedString(Filename
, OS
);
1178 OS
<< " md5 0x" << Checksum
->digest();
1181 PrintQuotedString(*Source
, OS
);
1185 Expected
<unsigned> MCAsmStreamer::tryEmitDwarfFileDirective(
1186 unsigned FileNo
, StringRef Directory
, StringRef Filename
,
1187 MD5::MD5Result
*Checksum
, Optional
<StringRef
> Source
, unsigned CUID
) {
1188 assert(CUID
== 0 && "multiple CUs not supported by MCAsmStreamer");
1190 MCDwarfLineTable
&Table
= getContext().getMCDwarfLineTable(CUID
);
1191 unsigned NumFiles
= Table
.getMCDwarfFiles().size();
1192 Expected
<unsigned> FileNoOrErr
=
1193 Table
.tryGetFile(Directory
, Filename
, Checksum
, Source
, FileNo
);
1195 return FileNoOrErr
.takeError();
1196 FileNo
= FileNoOrErr
.get();
1197 if (NumFiles
== Table
.getMCDwarfFiles().size())
1200 SmallString
<128> Str
;
1201 raw_svector_ostream
OS1(Str
);
1202 printDwarfFileDirective(FileNo
, Directory
, Filename
, Checksum
, Source
,
1203 UseDwarfDirectory
, OS1
);
1205 if (MCTargetStreamer
*TS
= getTargetStreamer())
1206 TS
->emitDwarfFileDirective(OS1
.str());
1208 EmitRawText(OS1
.str());
1213 void MCAsmStreamer::emitDwarfFile0Directive(StringRef Directory
,
1215 MD5::MD5Result
*Checksum
,
1216 Optional
<StringRef
> Source
,
1219 // .file 0 is new for DWARF v5.
1220 if (getContext().getDwarfVersion() < 5)
1222 // Inform MCDwarf about the root file.
1223 getContext().setMCLineTableRootFile(CUID
, Directory
, Filename
, Checksum
,
1226 SmallString
<128> Str
;
1227 raw_svector_ostream
OS1(Str
);
1228 printDwarfFileDirective(0, Directory
, Filename
, Checksum
, Source
,
1229 UseDwarfDirectory
, OS1
);
1231 if (MCTargetStreamer
*TS
= getTargetStreamer())
1232 TS
->emitDwarfFileDirective(OS1
.str());
1234 EmitRawText(OS1
.str());
1237 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo
, unsigned Line
,
1238 unsigned Column
, unsigned Flags
,
1240 unsigned Discriminator
,
1241 StringRef FileName
) {
1242 OS
<< "\t.loc\t" << FileNo
<< " " << Line
<< " " << Column
;
1243 if (MAI
->supportsExtendedDwarfLocDirective()) {
1244 if (Flags
& DWARF2_FLAG_BASIC_BLOCK
)
1245 OS
<< " basic_block";
1246 if (Flags
& DWARF2_FLAG_PROLOGUE_END
)
1247 OS
<< " prologue_end";
1248 if (Flags
& DWARF2_FLAG_EPILOGUE_BEGIN
)
1249 OS
<< " epilogue_begin";
1251 unsigned OldFlags
= getContext().getCurrentDwarfLoc().getFlags();
1252 if ((Flags
& DWARF2_FLAG_IS_STMT
) != (OldFlags
& DWARF2_FLAG_IS_STMT
)) {
1255 if (Flags
& DWARF2_FLAG_IS_STMT
)
1262 OS
<< " isa " << Isa
;
1264 OS
<< " discriminator " << Discriminator
;
1268 OS
.PadToColumn(MAI
->getCommentColumn());
1269 OS
<< MAI
->getCommentString() << ' ' << FileName
<< ':'
1270 << Line
<< ':' << Column
;
1273 this->MCStreamer::EmitDwarfLocDirective(FileNo
, Line
, Column
, Flags
,
1274 Isa
, Discriminator
, FileName
);
1277 MCSymbol
*MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID
) {
1278 // Always use the zeroth line table, since asm syntax only supports one line
1280 return MCStreamer::getDwarfLineTableSymbol(0);
1283 bool MCAsmStreamer::EmitCVFileDirective(unsigned FileNo
, StringRef Filename
,
1284 ArrayRef
<uint8_t> Checksum
,
1285 unsigned ChecksumKind
) {
1286 if (!getContext().getCVContext().addFile(*this, FileNo
, Filename
, Checksum
,
1290 OS
<< "\t.cv_file\t" << FileNo
<< ' ';
1291 PrintQuotedString(Filename
, OS
);
1293 if (!ChecksumKind
) {
1299 PrintQuotedString(toHex(Checksum
), OS
);
1300 OS
<< ' ' << ChecksumKind
;
1306 bool MCAsmStreamer::EmitCVFuncIdDirective(unsigned FuncId
) {
1307 OS
<< "\t.cv_func_id " << FuncId
<< '\n';
1308 return MCStreamer::EmitCVFuncIdDirective(FuncId
);
1311 bool MCAsmStreamer::EmitCVInlineSiteIdDirective(unsigned FunctionId
,
1314 unsigned IALine
, unsigned IACol
,
1316 OS
<< "\t.cv_inline_site_id " << FunctionId
<< " within " << IAFunc
1317 << " inlined_at " << IAFile
<< ' ' << IALine
<< ' ' << IACol
<< '\n';
1318 return MCStreamer::EmitCVInlineSiteIdDirective(FunctionId
, IAFunc
, IAFile
,
1319 IALine
, IACol
, Loc
);
1322 void MCAsmStreamer::EmitCVLocDirective(unsigned FunctionId
, unsigned FileNo
,
1323 unsigned Line
, unsigned Column
,
1324 bool PrologueEnd
, bool IsStmt
,
1325 StringRef FileName
, SMLoc Loc
) {
1326 // Validate the directive.
1327 if (!checkCVLocSection(FunctionId
, FileNo
, Loc
))
1330 OS
<< "\t.cv_loc\t" << FunctionId
<< " " << FileNo
<< " " << Line
<< " "
1333 OS
<< " prologue_end";
1339 OS
.PadToColumn(MAI
->getCommentColumn());
1340 OS
<< MAI
->getCommentString() << ' ' << FileName
<< ':' << Line
<< ':'
1346 void MCAsmStreamer::EmitCVLinetableDirective(unsigned FunctionId
,
1347 const MCSymbol
*FnStart
,
1348 const MCSymbol
*FnEnd
) {
1349 OS
<< "\t.cv_linetable\t" << FunctionId
<< ", ";
1350 FnStart
->print(OS
, MAI
);
1352 FnEnd
->print(OS
, MAI
);
1354 this->MCStreamer::EmitCVLinetableDirective(FunctionId
, FnStart
, FnEnd
);
1357 void MCAsmStreamer::EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId
,
1358 unsigned SourceFileId
,
1359 unsigned SourceLineNum
,
1360 const MCSymbol
*FnStartSym
,
1361 const MCSymbol
*FnEndSym
) {
1362 OS
<< "\t.cv_inline_linetable\t" << PrimaryFunctionId
<< ' ' << SourceFileId
1363 << ' ' << SourceLineNum
<< ' ';
1364 FnStartSym
->print(OS
, MAI
);
1366 FnEndSym
->print(OS
, MAI
);
1368 this->MCStreamer::EmitCVInlineLinetableDirective(
1369 PrimaryFunctionId
, SourceFileId
, SourceLineNum
, FnStartSym
, FnEndSym
);
1372 void MCAsmStreamer::EmitCVDefRangeDirective(
1373 ArrayRef
<std::pair
<const MCSymbol
*, const MCSymbol
*>> Ranges
,
1374 StringRef FixedSizePortion
) {
1375 OS
<< "\t.cv_def_range\t";
1376 for (std::pair
<const MCSymbol
*, const MCSymbol
*> Range
: Ranges
) {
1378 Range
.first
->print(OS
, MAI
);
1380 Range
.second
->print(OS
, MAI
);
1383 PrintQuotedString(FixedSizePortion
, OS
);
1385 this->MCStreamer::EmitCVDefRangeDirective(Ranges
, FixedSizePortion
);
1388 void MCAsmStreamer::EmitCVStringTableDirective() {
1389 OS
<< "\t.cv_stringtable";
1393 void MCAsmStreamer::EmitCVFileChecksumsDirective() {
1394 OS
<< "\t.cv_filechecksums";
1398 void MCAsmStreamer::EmitCVFileChecksumOffsetDirective(unsigned FileNo
) {
1399 OS
<< "\t.cv_filechecksumoffset\t" << FileNo
;
1403 void MCAsmStreamer::EmitCVFPOData(const MCSymbol
*ProcSym
, SMLoc L
) {
1404 OS
<< "\t.cv_fpo_data\t";
1405 ProcSym
->print(OS
, MAI
);
1409 void MCAsmStreamer::EmitIdent(StringRef IdentString
) {
1410 assert(MAI
->hasIdentDirective() && ".ident directive not supported");
1412 PrintQuotedString(IdentString
, OS
);
1416 void MCAsmStreamer::EmitCFISections(bool EH
, bool Debug
) {
1417 MCStreamer::EmitCFISections(EH
, Debug
);
1418 OS
<< "\t.cfi_sections ";
1422 OS
<< ", .debug_frame";
1424 OS
<< ".debug_frame";
1430 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo
&Frame
) {
1431 OS
<< "\t.cfi_startproc";
1437 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo
&Frame
) {
1438 MCStreamer::EmitCFIEndProcImpl(Frame
);
1439 OS
<< "\t.cfi_endproc";
1443 void MCAsmStreamer::EmitRegisterName(int64_t Register
) {
1444 if (!MAI
->useDwarfRegNumForCFI()) {
1445 // User .cfi_* directives can use arbitrary DWARF register numbers, not
1446 // just ones that map to LLVM register numbers and have known names.
1447 // Fall back to using the original number directly if no name is known.
1448 const MCRegisterInfo
*MRI
= getContext().getRegisterInfo();
1449 int LLVMRegister
= MRI
->getLLVMRegNumFromEH(Register
);
1450 if (LLVMRegister
!= -1) {
1451 InstPrinter
->printRegName(OS
, LLVMRegister
);
1458 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register
, int64_t Offset
) {
1459 MCStreamer::EmitCFIDefCfa(Register
, Offset
);
1460 OS
<< "\t.cfi_def_cfa ";
1461 EmitRegisterName(Register
);
1462 OS
<< ", " << Offset
;
1466 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset
) {
1467 MCStreamer::EmitCFIDefCfaOffset(Offset
);
1468 OS
<< "\t.cfi_def_cfa_offset " << Offset
;
1472 static void PrintCFIEscape(llvm::formatted_raw_ostream
&OS
, StringRef Values
) {
1473 OS
<< "\t.cfi_escape ";
1474 if (!Values
.empty()) {
1475 size_t e
= Values
.size() - 1;
1476 for (size_t i
= 0; i
< e
; ++i
)
1477 OS
<< format("0x%02x", uint8_t(Values
[i
])) << ", ";
1478 OS
<< format("0x%02x", uint8_t(Values
[e
]));
1482 void MCAsmStreamer::EmitCFIEscape(StringRef Values
) {
1483 MCStreamer::EmitCFIEscape(Values
);
1484 PrintCFIEscape(OS
, Values
);
1488 void MCAsmStreamer::EmitCFIGnuArgsSize(int64_t Size
) {
1489 MCStreamer::EmitCFIGnuArgsSize(Size
);
1491 uint8_t Buffer
[16] = { dwarf::DW_CFA_GNU_args_size
};
1492 unsigned Len
= encodeULEB128(Size
, Buffer
+ 1) + 1;
1494 PrintCFIEscape(OS
, StringRef((const char *)&Buffer
[0], Len
));
1498 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register
) {
1499 MCStreamer::EmitCFIDefCfaRegister(Register
);
1500 OS
<< "\t.cfi_def_cfa_register ";
1501 EmitRegisterName(Register
);
1505 void MCAsmStreamer::EmitCFIOffset(int64_t Register
, int64_t Offset
) {
1506 this->MCStreamer::EmitCFIOffset(Register
, Offset
);
1507 OS
<< "\t.cfi_offset ";
1508 EmitRegisterName(Register
);
1509 OS
<< ", " << Offset
;
1513 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol
*Sym
,
1514 unsigned Encoding
) {
1515 MCStreamer::EmitCFIPersonality(Sym
, Encoding
);
1516 OS
<< "\t.cfi_personality " << Encoding
<< ", ";
1517 Sym
->print(OS
, MAI
);
1521 void MCAsmStreamer::EmitCFILsda(const MCSymbol
*Sym
, unsigned Encoding
) {
1522 MCStreamer::EmitCFILsda(Sym
, Encoding
);
1523 OS
<< "\t.cfi_lsda " << Encoding
<< ", ";
1524 Sym
->print(OS
, MAI
);
1528 void MCAsmStreamer::EmitCFIRememberState() {
1529 MCStreamer::EmitCFIRememberState();
1530 OS
<< "\t.cfi_remember_state";
1534 void MCAsmStreamer::EmitCFIRestoreState() {
1535 MCStreamer::EmitCFIRestoreState();
1536 OS
<< "\t.cfi_restore_state";
1540 void MCAsmStreamer::EmitCFIRestore(int64_t Register
) {
1541 MCStreamer::EmitCFIRestore(Register
);
1542 OS
<< "\t.cfi_restore ";
1543 EmitRegisterName(Register
);
1547 void MCAsmStreamer::EmitCFISameValue(int64_t Register
) {
1548 MCStreamer::EmitCFISameValue(Register
);
1549 OS
<< "\t.cfi_same_value ";
1550 EmitRegisterName(Register
);
1554 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register
, int64_t Offset
) {
1555 MCStreamer::EmitCFIRelOffset(Register
, Offset
);
1556 OS
<< "\t.cfi_rel_offset ";
1557 EmitRegisterName(Register
);
1558 OS
<< ", " << Offset
;
1562 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment
) {
1563 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment
);
1564 OS
<< "\t.cfi_adjust_cfa_offset " << Adjustment
;
1568 void MCAsmStreamer::EmitCFISignalFrame() {
1569 MCStreamer::EmitCFISignalFrame();
1570 OS
<< "\t.cfi_signal_frame";
1574 void MCAsmStreamer::EmitCFIUndefined(int64_t Register
) {
1575 MCStreamer::EmitCFIUndefined(Register
);
1576 OS
<< "\t.cfi_undefined " << Register
;
1580 void MCAsmStreamer::EmitCFIRegister(int64_t Register1
, int64_t Register2
) {
1581 MCStreamer::EmitCFIRegister(Register1
, Register2
);
1582 OS
<< "\t.cfi_register " << Register1
<< ", " << Register2
;
1586 void MCAsmStreamer::EmitCFIWindowSave() {
1587 MCStreamer::EmitCFIWindowSave();
1588 OS
<< "\t.cfi_window_save";
1592 void MCAsmStreamer::EmitCFINegateRAState() {
1593 MCStreamer::EmitCFINegateRAState();
1594 OS
<< "\t.cfi_negate_ra_state";
1598 void MCAsmStreamer::EmitCFIReturnColumn(int64_t Register
) {
1599 MCStreamer::EmitCFIReturnColumn(Register
);
1600 OS
<< "\t.cfi_return_column " << Register
;
1604 void MCAsmStreamer::EmitCFIBKeyFrame() {
1605 MCStreamer::EmitCFIBKeyFrame();
1606 OS
<< "\t.cfi_b_key_frame";
1610 void MCAsmStreamer::EmitWinCFIStartProc(const MCSymbol
*Symbol
, SMLoc Loc
) {
1611 MCStreamer::EmitWinCFIStartProc(Symbol
, Loc
);
1614 Symbol
->print(OS
, MAI
);
1618 void MCAsmStreamer::EmitWinCFIEndProc(SMLoc Loc
) {
1619 MCStreamer::EmitWinCFIEndProc(Loc
);
1621 OS
<< "\t.seh_endproc";
1626 void MCAsmStreamer::EmitWinCFIFuncletOrFuncEnd(SMLoc Loc
) {
1629 void MCAsmStreamer::EmitWinCFIStartChained(SMLoc Loc
) {
1630 MCStreamer::EmitWinCFIStartChained(Loc
);
1632 OS
<< "\t.seh_startchained";
1636 void MCAsmStreamer::EmitWinCFIEndChained(SMLoc Loc
) {
1637 MCStreamer::EmitWinCFIEndChained(Loc
);
1639 OS
<< "\t.seh_endchained";
1643 void MCAsmStreamer::EmitWinEHHandler(const MCSymbol
*Sym
, bool Unwind
,
1644 bool Except
, SMLoc Loc
) {
1645 MCStreamer::EmitWinEHHandler(Sym
, Unwind
, Except
, Loc
);
1647 OS
<< "\t.seh_handler ";
1648 Sym
->print(OS
, MAI
);
1656 void MCAsmStreamer::EmitWinEHHandlerData(SMLoc Loc
) {
1657 MCStreamer::EmitWinEHHandlerData(Loc
);
1659 // Switch sections. Don't call SwitchSection directly, because that will
1660 // cause the section switch to be visible in the emitted assembly.
1661 // We only do this so the section switch that terminates the handler
1662 // data block is visible.
1663 WinEH::FrameInfo
*CurFrame
= getCurrentWinFrameInfo();
1664 MCSection
*TextSec
= &CurFrame
->Function
->getSection();
1665 MCSection
*XData
= getAssociatedXDataSection(TextSec
);
1666 SwitchSectionNoChange(XData
);
1668 OS
<< "\t.seh_handlerdata";
1672 void MCAsmStreamer::EmitWinCFIPushReg(unsigned Register
, SMLoc Loc
) {
1673 MCStreamer::EmitWinCFIPushReg(Register
, Loc
);
1675 OS
<< "\t.seh_pushreg " << Register
;
1679 void MCAsmStreamer::EmitWinCFISetFrame(unsigned Register
, unsigned Offset
,
1681 MCStreamer::EmitWinCFISetFrame(Register
, Offset
, Loc
);
1683 OS
<< "\t.seh_setframe " << Register
<< ", " << Offset
;
1687 void MCAsmStreamer::EmitWinCFIAllocStack(unsigned Size
, SMLoc Loc
) {
1688 MCStreamer::EmitWinCFIAllocStack(Size
, Loc
);
1690 OS
<< "\t.seh_stackalloc " << Size
;
1694 void MCAsmStreamer::EmitWinCFISaveReg(unsigned Register
, unsigned Offset
,
1696 MCStreamer::EmitWinCFISaveReg(Register
, Offset
, Loc
);
1698 OS
<< "\t.seh_savereg " << Register
<< ", " << Offset
;
1702 void MCAsmStreamer::EmitWinCFISaveXMM(unsigned Register
, unsigned Offset
,
1704 MCStreamer::EmitWinCFISaveXMM(Register
, Offset
, Loc
);
1706 OS
<< "\t.seh_savexmm " << Register
<< ", " << Offset
;
1710 void MCAsmStreamer::EmitWinCFIPushFrame(bool Code
, SMLoc Loc
) {
1711 MCStreamer::EmitWinCFIPushFrame(Code
, Loc
);
1713 OS
<< "\t.seh_pushframe";
1719 void MCAsmStreamer::EmitWinCFIEndProlog(SMLoc Loc
) {
1720 MCStreamer::EmitWinCFIEndProlog(Loc
);
1722 OS
<< "\t.seh_endprologue";
1726 void MCAsmStreamer::emitCGProfileEntry(const MCSymbolRefExpr
*From
,
1727 const MCSymbolRefExpr
*To
,
1729 OS
<< "\t.cg_profile ";
1730 From
->getSymbol().print(OS
, MAI
);
1732 To
->getSymbol().print(OS
, MAI
);
1733 OS
<< ", " << Count
;
1737 void MCAsmStreamer::AddEncodingComment(const MCInst
&Inst
,
1738 const MCSubtargetInfo
&STI
) {
1739 raw_ostream
&OS
= GetCommentOS();
1740 SmallString
<256> Code
;
1741 SmallVector
<MCFixup
, 4> Fixups
;
1742 raw_svector_ostream
VecOS(Code
);
1744 // If we have no code emitter, don't emit code.
1745 if (!getAssembler().getEmitterPtr())
1748 getAssembler().getEmitter().encodeInstruction(Inst
, VecOS
, Fixups
, STI
);
1750 // If we are showing fixups, create symbolic markers in the encoded
1751 // representation. We do this by making a per-bit map to the fixup item index,
1752 // then trying to display it as nicely as possible.
1753 SmallVector
<uint8_t, 64> FixupMap
;
1754 FixupMap
.resize(Code
.size() * 8);
1755 for (unsigned i
= 0, e
= Code
.size() * 8; i
!= e
; ++i
)
1758 for (unsigned i
= 0, e
= Fixups
.size(); i
!= e
; ++i
) {
1759 MCFixup
&F
= Fixups
[i
];
1760 const MCFixupKindInfo
&Info
=
1761 getAssembler().getBackend().getFixupKindInfo(F
.getKind());
1762 for (unsigned j
= 0; j
!= Info
.TargetSize
; ++j
) {
1763 unsigned Index
= F
.getOffset() * 8 + Info
.TargetOffset
+ j
;
1764 assert(Index
< Code
.size() * 8 && "Invalid offset in fixup!");
1765 FixupMap
[Index
] = 1 + i
;
1769 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1770 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1771 OS
<< "encoding: [";
1772 for (unsigned i
= 0, e
= Code
.size(); i
!= e
; ++i
) {
1776 // See if all bits are the same map entry.
1777 uint8_t MapEntry
= FixupMap
[i
* 8 + 0];
1778 for (unsigned j
= 1; j
!= 8; ++j
) {
1779 if (FixupMap
[i
* 8 + j
] == MapEntry
)
1782 MapEntry
= uint8_t(~0U);
1786 if (MapEntry
!= uint8_t(~0U)) {
1787 if (MapEntry
== 0) {
1788 OS
<< format("0x%02x", uint8_t(Code
[i
]));
1791 // FIXME: Some of the 8 bits require fix up.
1792 OS
<< format("0x%02x", uint8_t(Code
[i
])) << '\''
1793 << char('A' + MapEntry
- 1) << '\'';
1795 OS
<< char('A' + MapEntry
- 1);
1798 // Otherwise, write out in binary.
1800 for (unsigned j
= 8; j
--;) {
1801 unsigned Bit
= (Code
[i
] >> j
) & 1;
1804 if (MAI
->isLittleEndian())
1805 FixupBit
= i
* 8 + j
;
1807 FixupBit
= i
* 8 + (7-j
);
1809 if (uint8_t MapEntry
= FixupMap
[FixupBit
]) {
1810 assert(Bit
== 0 && "Encoder wrote into fixed up bit!");
1811 OS
<< char('A' + MapEntry
- 1);
1819 for (unsigned i
= 0, e
= Fixups
.size(); i
!= e
; ++i
) {
1820 MCFixup
&F
= Fixups
[i
];
1821 const MCFixupKindInfo
&Info
=
1822 getAssembler().getBackend().getFixupKindInfo(F
.getKind());
1823 OS
<< " fixup " << char('A' + i
) << " - " << "offset: " << F
.getOffset()
1824 << ", value: " << *F
.getValue() << ", kind: " << Info
.Name
<< "\n";
1828 void MCAsmStreamer::EmitInstruction(const MCInst
&Inst
,
1829 const MCSubtargetInfo
&STI
) {
1830 assert(getCurrentSectionOnly() &&
1831 "Cannot emit contents before setting section!");
1833 // Show the encoding in a comment if we have a code emitter.
1834 AddEncodingComment(Inst
, STI
);
1836 // Show the MCInst if enabled.
1838 Inst
.dump_pretty(GetCommentOS(), InstPrinter
.get(), "\n ");
1839 GetCommentOS() << "\n";
1842 if(getTargetStreamer())
1843 getTargetStreamer()->prettyPrintAsm(*InstPrinter
, OS
, Inst
, STI
);
1845 InstPrinter
->printInst(&Inst
, OS
, "", STI
);
1847 StringRef Comments
= CommentToEmit
;
1848 if (Comments
.size() && Comments
.back() != '\n')
1849 GetCommentOS() << "\n";
1854 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2
) {
1855 OS
<< "\t.bundle_align_mode " << AlignPow2
;
1859 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd
) {
1860 OS
<< "\t.bundle_lock";
1862 OS
<< " align_to_end";
1866 void MCAsmStreamer::EmitBundleUnlock() {
1867 OS
<< "\t.bundle_unlock";
1871 bool MCAsmStreamer::EmitRelocDirective(const MCExpr
&Offset
, StringRef Name
,
1872 const MCExpr
*Expr
, SMLoc
,
1873 const MCSubtargetInfo
&STI
) {
1875 Offset
.print(OS
, MAI
);
1879 Expr
->print(OS
, MAI
);
1885 void MCAsmStreamer::EmitAddrsig() {
1890 void MCAsmStreamer::EmitAddrsigSym(const MCSymbol
*Sym
) {
1891 OS
<< "\t.addrsig_sym ";
1892 Sym
->print(OS
, MAI
);
1896 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1897 /// the specified string in the output .s file. This capability is
1898 /// indicated by the hasRawTextSupport() predicate.
1899 void MCAsmStreamer::EmitRawTextImpl(StringRef String
) {
1900 if (!String
.empty() && String
.back() == '\n')
1901 String
= String
.substr(0, String
.size()-1);
1906 void MCAsmStreamer::FinishImpl() {
1907 // If we are generating dwarf for assembly source files dump out the sections.
1908 if (getContext().getGenDwarfForAssembly())
1909 MCGenDwarfInfo::Emit(this);
1911 // Emit the label for the line table, if requested - since the rest of the
1912 // line table will be defined by .loc/.file directives, and not emitted
1913 // directly, the label is the only work required here.
1914 auto &Tables
= getContext().getMCDwarfLineTables();
1915 if (!Tables
.empty()) {
1916 assert(Tables
.size() == 1 && "asm output only supports one line table");
1917 if (auto *Label
= Tables
.begin()->second
.getLabel()) {
1918 SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
1924 MCStreamer
*llvm::createAsmStreamer(MCContext
&Context
,
1925 std::unique_ptr
<formatted_raw_ostream
> OS
,
1926 bool isVerboseAsm
, bool useDwarfDirectory
,
1928 std::unique_ptr
<MCCodeEmitter
> &&CE
,
1929 std::unique_ptr
<MCAsmBackend
> &&MAB
,
1931 return new MCAsmStreamer(Context
, std::move(OS
), isVerboseAsm
,
1932 useDwarfDirectory
, IP
, std::move(CE
), std::move(MAB
),