[ARM] MVE sext costs
[llvm-complete.git] / lib / MC / MCAsmStreamer.cpp
blobe20ba2f96e3bcd6eb721bb534f3c7ca32851a9da
1 //===- lib/MC/MCAsmStreamer.cpp - Text Assembly Output ----------*- C++ -*-===//
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 //===----------------------------------------------------------------------===//
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"
36 #include <cctype>
38 using namespace llvm;
40 namespace {
42 class MCAsmStreamer final : public MCStreamer {
43 std::unique_ptr<formatted_raw_ostream> OSOwner;
44 formatted_raw_ostream &OS;
45 const MCAsmInfo *MAI;
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;
62 public:
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(std::make_unique<MCAssembler>(
70 Context, std::move(asmbackend), std::move(emitter),
71 (asmbackend) ? asmbackend->createObjectWriter(NullStream)
72 : nullptr)),
73 CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
74 ShowInst(showInst), UseDwarfDirectory(useDwarfDirectory) {
75 assert(InstPrinter);
76 if (IsVerboseAsm)
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.
87 if (!IsVerboseAsm) {
88 OS << '\n';
89 return;
91 EmitCommentsAndEOL();
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
114 /// use this method.
115 raw_ostream &GetCommentOS() override {
116 if (!IsVerboseAsm)
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 {
128 EmitEOL();
131 /// @name MCStreamer Interface
132 /// @{
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 EmitXCOFFLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
166 unsigned ByteAlign) override;
167 void emitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
168 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
169 unsigned ByteAlignment) override;
171 /// Emit a local common (.lcomm) symbol.
173 /// @param Symbol - The common symbol to emit.
174 /// @param Size - The size of the common symbol.
175 /// @param ByteAlignment - The alignment of the common symbol in bytes.
176 void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
177 unsigned ByteAlignment) override;
179 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
180 uint64_t Size = 0, unsigned ByteAlignment = 0,
181 SMLoc Loc = SMLoc()) override;
183 void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
184 unsigned ByteAlignment = 0) override;
186 void EmitBinaryData(StringRef Data) override;
188 void EmitBytes(StringRef Data) override;
190 void EmitValueImpl(const MCExpr *Value, unsigned Size,
191 SMLoc Loc = SMLoc()) override;
192 void EmitIntValue(uint64_t Value, unsigned Size) override;
193 void EmitIntValueInHex(uint64_t Value, unsigned Size) override;
195 void EmitULEB128Value(const MCExpr *Value) override;
197 void EmitSLEB128Value(const MCExpr *Value) override;
199 void EmitDTPRel32Value(const MCExpr *Value) override;
200 void EmitDTPRel64Value(const MCExpr *Value) override;
201 void EmitTPRel32Value(const MCExpr *Value) override;
202 void EmitTPRel64Value(const MCExpr *Value) override;
204 void EmitGPRel64Value(const MCExpr *Value) override;
206 void EmitGPRel32Value(const MCExpr *Value) override;
208 void emitFill(const MCExpr &NumBytes, uint64_t FillValue,
209 SMLoc Loc = SMLoc()) override;
211 void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
212 SMLoc Loc = SMLoc()) override;
214 void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
215 unsigned ValueSize = 1,
216 unsigned MaxBytesToEmit = 0) override;
218 void EmitCodeAlignment(unsigned ByteAlignment,
219 unsigned MaxBytesToEmit = 0) override;
221 void emitValueToOffset(const MCExpr *Offset,
222 unsigned char Value,
223 SMLoc Loc) override;
225 void EmitFileDirective(StringRef Filename) override;
226 Expected<unsigned> tryEmitDwarfFileDirective(unsigned FileNo,
227 StringRef Directory,
228 StringRef Filename,
229 Optional<MD5::MD5Result> Checksum = None,
230 Optional<StringRef> Source = None,
231 unsigned CUID = 0) override;
232 void emitDwarfFile0Directive(StringRef Directory, StringRef Filename,
233 Optional<MD5::MD5Result> Checksum,
234 Optional<StringRef> Source,
235 unsigned CUID = 0) override;
236 void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
237 unsigned Column, unsigned Flags,
238 unsigned Isa, unsigned Discriminator,
239 StringRef FileName) override;
240 MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
242 bool EmitCVFileDirective(unsigned FileNo, StringRef Filename,
243 ArrayRef<uint8_t> Checksum,
244 unsigned ChecksumKind) override;
245 bool EmitCVFuncIdDirective(unsigned FuncId) override;
246 bool EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc,
247 unsigned IAFile, unsigned IALine,
248 unsigned IACol, SMLoc Loc) override;
249 void EmitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line,
250 unsigned Column, bool PrologueEnd, bool IsStmt,
251 StringRef FileName, SMLoc Loc) override;
252 void EmitCVLinetableDirective(unsigned FunctionId, const MCSymbol *FnStart,
253 const MCSymbol *FnEnd) override;
254 void EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
255 unsigned SourceFileId,
256 unsigned SourceLineNum,
257 const MCSymbol *FnStartSym,
258 const MCSymbol *FnEndSym) override;
260 void PrintCVDefRangePrefix(
261 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges);
263 void EmitCVDefRangeDirective(
264 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
265 codeview::DefRangeRegisterRelSym::Header DRHdr) override;
267 void EmitCVDefRangeDirective(
268 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
269 codeview::DefRangeSubfieldRegisterSym::Header DRHdr) override;
271 void EmitCVDefRangeDirective(
272 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
273 codeview::DefRangeRegisterSym::Header DRHdr) override;
275 void EmitCVDefRangeDirective(
276 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
277 codeview::DefRangeFramePointerRelSym::Header DRHdr) override;
279 void EmitCVStringTableDirective() override;
280 void EmitCVFileChecksumsDirective() override;
281 void EmitCVFileChecksumOffsetDirective(unsigned FileNo) override;
282 void EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) override;
284 void EmitIdent(StringRef IdentString) override;
285 void EmitCFIBKeyFrame() override;
286 void EmitCFISections(bool EH, bool Debug) override;
287 void EmitCFIDefCfa(int64_t Register, int64_t Offset) override;
288 void EmitCFIDefCfaOffset(int64_t Offset) override;
289 void EmitCFIDefCfaRegister(int64_t Register) override;
290 void EmitCFIOffset(int64_t Register, int64_t Offset) override;
291 void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
292 void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
293 void EmitCFIRememberState() override;
294 void EmitCFIRestoreState() override;
295 void EmitCFIRestore(int64_t Register) override;
296 void EmitCFISameValue(int64_t Register) override;
297 void EmitCFIRelOffset(int64_t Register, int64_t Offset) override;
298 void EmitCFIAdjustCfaOffset(int64_t Adjustment) override;
299 void EmitCFIEscape(StringRef Values) override;
300 void EmitCFIGnuArgsSize(int64_t Size) override;
301 void EmitCFISignalFrame() override;
302 void EmitCFIUndefined(int64_t Register) override;
303 void EmitCFIRegister(int64_t Register1, int64_t Register2) override;
304 void EmitCFIWindowSave() override;
305 void EmitCFINegateRAState() override;
306 void EmitCFIReturnColumn(int64_t Register) override;
308 void EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) override;
309 void EmitWinCFIEndProc(SMLoc Loc) override;
310 void EmitWinCFIFuncletOrFuncEnd(SMLoc Loc) override;
311 void EmitWinCFIStartChained(SMLoc Loc) override;
312 void EmitWinCFIEndChained(SMLoc Loc) override;
313 void EmitWinCFIPushReg(unsigned Register, SMLoc Loc) override;
314 void EmitWinCFISetFrame(unsigned Register, unsigned Offset,
315 SMLoc Loc) override;
316 void EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) override;
317 void EmitWinCFISaveReg(unsigned Register, unsigned Offset,
318 SMLoc Loc) override;
319 void EmitWinCFISaveXMM(unsigned Register, unsigned Offset,
320 SMLoc Loc) override;
321 void EmitWinCFIPushFrame(bool Code, SMLoc Loc) override;
322 void EmitWinCFIEndProlog(SMLoc Loc) override;
324 void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
325 SMLoc Loc) override;
326 void EmitWinEHHandlerData(SMLoc Loc) override;
328 void emitCGProfileEntry(const MCSymbolRefExpr *From,
329 const MCSymbolRefExpr *To, uint64_t Count) override;
331 void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override;
333 void EmitBundleAlignMode(unsigned AlignPow2) override;
334 void EmitBundleLock(bool AlignToEnd) override;
335 void EmitBundleUnlock() override;
337 bool EmitRelocDirective(const MCExpr &Offset, StringRef Name,
338 const MCExpr *Expr, SMLoc Loc,
339 const MCSubtargetInfo &STI) override;
341 void EmitAddrsig() override;
342 void EmitAddrsigSym(const MCSymbol *Sym) override;
344 /// If this file is backed by an assembly streamer, this dumps the specified
345 /// string in the output .s file. This capability is indicated by the
346 /// hasRawTextSupport() predicate.
347 void EmitRawTextImpl(StringRef String) override;
349 void FinishImpl() override;
352 } // end anonymous namespace.
354 void MCAsmStreamer::AddComment(const Twine &T, bool EOL) {
355 if (!IsVerboseAsm) return;
357 T.toVector(CommentToEmit);
359 if (EOL)
360 CommentToEmit.push_back('\n'); // Place comment in a new line.
363 void MCAsmStreamer::EmitCommentsAndEOL() {
364 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
365 OS << '\n';
366 return;
369 StringRef Comments = CommentToEmit;
371 assert(Comments.back() == '\n' &&
372 "Comment array not newline terminated");
373 do {
374 // Emit a line of comments.
375 OS.PadToColumn(MAI->getCommentColumn());
376 size_t Position = Comments.find('\n');
377 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
379 Comments = Comments.substr(Position+1);
380 } while (!Comments.empty());
382 CommentToEmit.clear();
385 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
386 assert(Bytes > 0 && Bytes <= 8 && "Invalid size!");
387 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
390 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
391 if (TabPrefix)
392 OS << '\t';
393 OS << MAI->getCommentString() << T;
394 EmitEOL();
397 void MCAsmStreamer::addExplicitComment(const Twine &T) {
398 StringRef c = T.getSingleStringRef();
399 if (c.equals(StringRef(MAI->getSeparatorString())))
400 return;
401 if (c.startswith(StringRef("//"))) {
402 ExplicitCommentToEmit.append("\t");
403 ExplicitCommentToEmit.append(MAI->getCommentString());
404 // drop //
405 ExplicitCommentToEmit.append(c.slice(2, c.size()).str());
406 } else if (c.startswith(StringRef("/*"))) {
407 size_t p = 2, len = c.size() - 2;
408 // emit each line in comment as separate newline.
409 do {
410 size_t newp = std::min(len, c.find_first_of("\r\n", p));
411 ExplicitCommentToEmit.append("\t");
412 ExplicitCommentToEmit.append(MAI->getCommentString());
413 ExplicitCommentToEmit.append(c.slice(p, newp).str());
414 // If we have another line in this comment add line
415 if (newp < len)
416 ExplicitCommentToEmit.append("\n");
417 p = newp + 1;
418 } while (p < len);
419 } else if (c.startswith(StringRef(MAI->getCommentString()))) {
420 ExplicitCommentToEmit.append("\t");
421 ExplicitCommentToEmit.append(c.str());
422 } else if (c.front() == '#') {
424 ExplicitCommentToEmit.append("\t");
425 ExplicitCommentToEmit.append(MAI->getCommentString());
426 ExplicitCommentToEmit.append(c.slice(1, c.size()).str());
427 } else
428 assert(false && "Unexpected Assembly Comment");
429 // full line comments immediately output
430 if (c.back() == '\n')
431 emitExplicitComments();
434 void MCAsmStreamer::emitExplicitComments() {
435 StringRef Comments = ExplicitCommentToEmit;
436 if (!Comments.empty())
437 OS << Comments;
438 ExplicitCommentToEmit.clear();
441 void MCAsmStreamer::ChangeSection(MCSection *Section,
442 const MCExpr *Subsection) {
443 assert(Section && "Cannot switch to a null section!");
444 if (MCTargetStreamer *TS = getTargetStreamer()) {
445 TS->changeSection(getCurrentSectionOnly(), Section, Subsection, OS);
446 } else {
447 Section->PrintSwitchToSection(
448 *MAI, getContext().getObjectFileInfo()->getTargetTriple(), OS,
449 Subsection);
453 void MCAsmStreamer::emitELFSymverDirective(StringRef AliasName,
454 const MCSymbol *Aliasee) {
455 OS << ".symver ";
456 Aliasee->print(OS, MAI);
457 OS << ", " << AliasName;
458 EmitEOL();
461 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol, SMLoc Loc) {
462 MCStreamer::EmitLabel(Symbol, Loc);
464 Symbol->print(OS, MAI);
465 OS << MAI->getLabelSuffix();
467 EmitEOL();
470 void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
471 StringRef str = MCLOHIdToName(Kind);
473 #ifndef NDEBUG
474 int NbArgs = MCLOHIdToNbArgs(Kind);
475 assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
476 assert(str != "" && "Invalid LOH name");
477 #endif
479 OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
480 bool IsFirst = true;
481 for (const MCSymbol *Arg : Args) {
482 if (!IsFirst)
483 OS << ", ";
484 IsFirst = false;
485 Arg->print(OS, MAI);
487 EmitEOL();
490 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
491 switch (Flag) {
492 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
493 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
494 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
495 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
496 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
498 EmitEOL();
501 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
502 assert(!Options.empty() && "At least one option is required!");
503 OS << "\t.linker_option \"" << Options[0] << '"';
504 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
505 ie = Options.end(); it != ie; ++it) {
506 OS << ", " << '"' << *it << '"';
508 EmitEOL();
511 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
512 if (!MAI->doesSupportDataRegionDirectives())
513 return;
514 switch (Kind) {
515 case MCDR_DataRegion: OS << "\t.data_region"; break;
516 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
517 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
518 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
519 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
521 EmitEOL();
524 static const char *getVersionMinDirective(MCVersionMinType Type) {
525 switch (Type) {
526 case MCVM_WatchOSVersionMin: return ".watchos_version_min";
527 case MCVM_TvOSVersionMin: return ".tvos_version_min";
528 case MCVM_IOSVersionMin: return ".ios_version_min";
529 case MCVM_OSXVersionMin: return ".macosx_version_min";
531 llvm_unreachable("Invalid MC version min type");
534 static void EmitSDKVersionSuffix(raw_ostream &OS,
535 const VersionTuple &SDKVersion) {
536 if (SDKVersion.empty())
537 return;
538 OS << '\t' << "sdk_version " << SDKVersion.getMajor();
539 if (auto Minor = SDKVersion.getMinor()) {
540 OS << ", " << *Minor;
541 if (auto Subminor = SDKVersion.getSubminor()) {
542 OS << ", " << *Subminor;
547 void MCAsmStreamer::EmitVersionMin(MCVersionMinType Type, unsigned Major,
548 unsigned Minor, unsigned Update,
549 VersionTuple SDKVersion) {
550 OS << '\t' << getVersionMinDirective(Type) << ' ' << Major << ", " << Minor;
551 if (Update)
552 OS << ", " << Update;
553 EmitSDKVersionSuffix(OS, SDKVersion);
554 EmitEOL();
557 static const char *getPlatformName(MachO::PlatformType Type) {
558 switch (Type) {
559 case MachO::PLATFORM_MACOS: return "macos";
560 case MachO::PLATFORM_IOS: return "ios";
561 case MachO::PLATFORM_TVOS: return "tvos";
562 case MachO::PLATFORM_WATCHOS: return "watchos";
563 case MachO::PLATFORM_BRIDGEOS: return "bridgeos";
564 case MachO::PLATFORM_MACCATALYST: return "macCatalyst";
565 case MachO::PLATFORM_IOSSIMULATOR: return "iossimulator";
566 case MachO::PLATFORM_TVOSSIMULATOR: return "tvossimulator";
567 case MachO::PLATFORM_WATCHOSSIMULATOR: return "watchossimulator";
569 llvm_unreachable("Invalid Mach-O platform type");
572 void MCAsmStreamer::EmitBuildVersion(unsigned Platform, unsigned Major,
573 unsigned Minor, unsigned Update,
574 VersionTuple SDKVersion) {
575 const char *PlatformName = getPlatformName((MachO::PlatformType)Platform);
576 OS << "\t.build_version " << PlatformName << ", " << Major << ", " << Minor;
577 if (Update)
578 OS << ", " << Update;
579 EmitSDKVersionSuffix(OS, SDKVersion);
580 EmitEOL();
583 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
584 // This needs to emit to a temporary string to get properly quoted
585 // MCSymbols when they have spaces in them.
586 OS << "\t.thumb_func";
587 // Only Mach-O hasSubsectionsViaSymbols()
588 if (MAI->hasSubsectionsViaSymbols()) {
589 OS << '\t';
590 Func->print(OS, MAI);
592 EmitEOL();
595 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
596 // Do not emit a .set on inlined target assignments.
597 bool EmitSet = true;
598 if (auto *E = dyn_cast<MCTargetExpr>(Value))
599 if (E->inlineAssignedExpr())
600 EmitSet = false;
601 if (EmitSet) {
602 OS << ".set ";
603 Symbol->print(OS, MAI);
604 OS << ", ";
605 Value->print(OS, MAI);
607 EmitEOL();
610 MCStreamer::EmitAssignment(Symbol, Value);
613 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
614 OS << ".weakref ";
615 Alias->print(OS, MAI);
616 OS << ", ";
617 Symbol->print(OS, MAI);
618 EmitEOL();
621 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
622 MCSymbolAttr Attribute) {
623 switch (Attribute) {
624 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
625 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
626 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
627 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
628 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
629 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
630 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
631 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
632 if (!MAI->hasDotTypeDotSizeDirective())
633 return false; // Symbol attribute not supported
634 OS << "\t.type\t";
635 Symbol->print(OS, MAI);
636 OS << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
637 switch (Attribute) {
638 default: return false;
639 case MCSA_ELF_TypeFunction: OS << "function"; break;
640 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
641 case MCSA_ELF_TypeObject: OS << "object"; break;
642 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
643 case MCSA_ELF_TypeCommon: OS << "common"; break;
644 case MCSA_ELF_TypeNoType: OS << "notype"; break;
645 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
647 EmitEOL();
648 return true;
649 case MCSA_Global: // .globl/.global
650 OS << MAI->getGlobalDirective();
651 break;
652 case MCSA_Hidden: OS << "\t.hidden\t"; break;
653 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
654 case MCSA_Internal: OS << "\t.internal\t"; break;
655 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
656 case MCSA_Local: OS << "\t.local\t"; break;
657 case MCSA_NoDeadStrip:
658 if (!MAI->hasNoDeadStrip())
659 return false;
660 OS << "\t.no_dead_strip\t";
661 break;
662 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
663 case MCSA_AltEntry: OS << "\t.alt_entry\t"; break;
664 case MCSA_PrivateExtern:
665 OS << "\t.private_extern\t";
666 break;
667 case MCSA_Protected: OS << "\t.protected\t"; break;
668 case MCSA_Reference: OS << "\t.reference\t"; break;
669 case MCSA_Weak: OS << MAI->getWeakDirective(); break;
670 case MCSA_WeakDefinition:
671 OS << "\t.weak_definition\t";
672 break;
673 // .weak_reference
674 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
675 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
676 case MCSA_Cold:
677 // Assemblers currently do not support a .cold directive.
678 return false;
681 Symbol->print(OS, MAI);
682 EmitEOL();
684 return true;
687 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
688 OS << ".desc" << ' ';
689 Symbol->print(OS, MAI);
690 OS << ',' << DescValue;
691 EmitEOL();
694 void MCAsmStreamer::EmitSyntaxDirective() {
695 if (MAI->getAssemblerDialect() == 1) {
696 OS << "\t.intel_syntax noprefix";
697 EmitEOL();
699 // FIXME: Currently emit unprefix'ed registers.
700 // The intel_syntax directive has one optional argument
701 // with may have a value of prefix or noprefix.
704 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
705 OS << "\t.def\t ";
706 Symbol->print(OS, MAI);
707 OS << ';';
708 EmitEOL();
711 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
712 OS << "\t.scl\t" << StorageClass << ';';
713 EmitEOL();
716 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
717 OS << "\t.type\t" << Type << ';';
718 EmitEOL();
721 void MCAsmStreamer::EndCOFFSymbolDef() {
722 OS << "\t.endef";
723 EmitEOL();
726 void MCAsmStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
727 OS << "\t.safeseh\t";
728 Symbol->print(OS, MAI);
729 EmitEOL();
732 void MCAsmStreamer::EmitCOFFSymbolIndex(MCSymbol const *Symbol) {
733 OS << "\t.symidx\t";
734 Symbol->print(OS, MAI);
735 EmitEOL();
738 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
739 OS << "\t.secidx\t";
740 Symbol->print(OS, MAI);
741 EmitEOL();
744 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {
745 OS << "\t.secrel32\t";
746 Symbol->print(OS, MAI);
747 if (Offset != 0)
748 OS << '+' << Offset;
749 EmitEOL();
752 void MCAsmStreamer::EmitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) {
753 OS << "\t.rva\t";
754 Symbol->print(OS, MAI);
755 if (Offset > 0)
756 OS << '+' << Offset;
757 else if (Offset < 0)
758 OS << '-' << -Offset;
759 EmitEOL();
762 // We need an XCOFF-specific version of this directive as the AIX syntax
763 // requires a QualName argument identifying the csect name and storage mapping
764 // class to appear before the alignment if we are specifying it.
765 void MCAsmStreamer::EmitXCOFFLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
766 unsigned ByteAlignment) {
767 assert(MAI->getLCOMMDirectiveAlignmentType() == LCOMM::Log2Alignment &&
768 "We only support writing log base-2 alignment format with XCOFF.");
769 assert(isPowerOf2_32(ByteAlignment) && "Alignment must be a power of 2.");
771 OS << "\t.lcomm\t";
772 Symbol->print(OS, MAI);
773 OS << ',' << Size;
774 OS << ',' << Symbol->getName();
775 OS << ',' << Log2_32(ByteAlignment);
777 EmitEOL();
780 void MCAsmStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
781 assert(MAI->hasDotTypeDotSizeDirective());
782 OS << "\t.size\t";
783 Symbol->print(OS, MAI);
784 OS << ", ";
785 Value->print(OS, MAI);
786 EmitEOL();
789 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
790 unsigned ByteAlignment) {
791 OS << "\t.comm\t";
792 Symbol->print(OS, MAI);
793 OS << ',' << Size;
795 if (ByteAlignment != 0) {
796 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
797 OS << ',' << ByteAlignment;
798 else
799 OS << ',' << Log2_32(ByteAlignment);
801 EmitEOL();
804 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
805 unsigned ByteAlign) {
806 OS << "\t.lcomm\t";
807 Symbol->print(OS, MAI);
808 OS << ',' << Size;
810 if (ByteAlign > 1) {
811 switch (MAI->getLCOMMDirectiveAlignmentType()) {
812 case LCOMM::NoAlignment:
813 llvm_unreachable("alignment not supported on .lcomm!");
814 case LCOMM::ByteAlignment:
815 OS << ',' << ByteAlign;
816 break;
817 case LCOMM::Log2Alignment:
818 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
819 OS << ',' << Log2_32(ByteAlign);
820 break;
823 EmitEOL();
826 void MCAsmStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
827 uint64_t Size, unsigned ByteAlignment,
828 SMLoc Loc) {
829 if (Symbol)
830 AssignFragment(Symbol, &Section->getDummyFragment());
832 // Note: a .zerofill directive does not switch sections.
833 OS << ".zerofill ";
835 assert(Section->getVariant() == MCSection::SV_MachO &&
836 ".zerofill is a Mach-O specific directive");
837 // This is a mach-o specific directive.
839 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
840 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
842 if (Symbol) {
843 OS << ',';
844 Symbol->print(OS, MAI);
845 OS << ',' << Size;
846 if (ByteAlignment != 0)
847 OS << ',' << Log2_32(ByteAlignment);
849 EmitEOL();
852 // .tbss sym, size, align
853 // This depends that the symbol has already been mangled from the original,
854 // e.g. _a.
855 void MCAsmStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
856 uint64_t Size, unsigned ByteAlignment) {
857 AssignFragment(Symbol, &Section->getDummyFragment());
859 assert(Symbol && "Symbol shouldn't be NULL!");
860 // Instead of using the Section we'll just use the shortcut.
862 assert(Section->getVariant() == MCSection::SV_MachO &&
863 ".zerofill is a Mach-O specific directive");
864 // This is a mach-o specific directive and section.
866 OS << ".tbss ";
867 Symbol->print(OS, MAI);
868 OS << ", " << Size;
870 // Output align if we have it. We default to 1 so don't bother printing
871 // that.
872 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
874 EmitEOL();
877 static inline char toOctal(int X) { return (X&7)+'0'; }
879 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
880 OS << '"';
882 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
883 unsigned char C = Data[i];
884 if (C == '"' || C == '\\') {
885 OS << '\\' << (char)C;
886 continue;
889 if (isPrint((unsigned char)C)) {
890 OS << (char)C;
891 continue;
894 switch (C) {
895 case '\b': OS << "\\b"; break;
896 case '\f': OS << "\\f"; break;
897 case '\n': OS << "\\n"; break;
898 case '\r': OS << "\\r"; break;
899 case '\t': OS << "\\t"; break;
900 default:
901 OS << '\\';
902 OS << toOctal(C >> 6);
903 OS << toOctal(C >> 3);
904 OS << toOctal(C >> 0);
905 break;
909 OS << '"';
912 void MCAsmStreamer::EmitBytes(StringRef Data) {
913 assert(getCurrentSectionOnly() &&
914 "Cannot emit contents before setting section!");
915 if (Data.empty()) return;
917 // If only single byte is provided or no ascii or asciz directives is
918 // supported, emit as vector of 8bits data.
919 if (Data.size() == 1 ||
920 !(MAI->getAscizDirective() || MAI->getAsciiDirective())) {
921 if (MCTargetStreamer *TS = getTargetStreamer()) {
922 TS->emitRawBytes(Data);
923 } else {
924 const char *Directive = MAI->getData8bitsDirective();
925 for (const unsigned char C : Data.bytes()) {
926 OS << Directive << (unsigned)C;
927 EmitEOL();
930 return;
933 // If the data ends with 0 and the target supports .asciz, use it, otherwise
934 // use .ascii
935 if (MAI->getAscizDirective() && Data.back() == 0) {
936 OS << MAI->getAscizDirective();
937 Data = Data.substr(0, Data.size()-1);
938 } else {
939 OS << MAI->getAsciiDirective();
942 PrintQuotedString(Data, OS);
943 EmitEOL();
946 void MCAsmStreamer::EmitBinaryData(StringRef Data) {
947 // This is binary data. Print it in a grid of hex bytes for readability.
948 const size_t Cols = 4;
949 for (size_t I = 0, EI = alignTo(Data.size(), Cols); I < EI; I += Cols) {
950 size_t J = I, EJ = std::min(I + Cols, Data.size());
951 assert(EJ > 0);
952 OS << MAI->getData8bitsDirective();
953 for (; J < EJ - 1; ++J)
954 OS << format("0x%02x", uint8_t(Data[J])) << ", ";
955 OS << format("0x%02x", uint8_t(Data[J]));
956 EmitEOL();
960 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
961 EmitValue(MCConstantExpr::create(Value, getContext()), Size);
964 void MCAsmStreamer::EmitIntValueInHex(uint64_t Value, unsigned Size) {
965 EmitValue(MCConstantExpr::create(Value, getContext(), true), Size);
968 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
969 SMLoc Loc) {
970 assert(Size <= 8 && "Invalid size");
971 assert(getCurrentSectionOnly() &&
972 "Cannot emit contents before setting section!");
973 const char *Directive = nullptr;
974 switch (Size) {
975 default: break;
976 case 1: Directive = MAI->getData8bitsDirective(); break;
977 case 2: Directive = MAI->getData16bitsDirective(); break;
978 case 4: Directive = MAI->getData32bitsDirective(); break;
979 case 8: Directive = MAI->getData64bitsDirective(); break;
982 if (!Directive) {
983 int64_t IntValue;
984 if (!Value->evaluateAsAbsolute(IntValue))
985 report_fatal_error("Don't know how to emit this value.");
987 // We couldn't handle the requested integer size so we fallback by breaking
988 // the request down into several, smaller, integers.
989 // Since sizes greater or equal to "Size" are invalid, we use the greatest
990 // power of 2 that is less than "Size" as our largest piece of granularity.
991 bool IsLittleEndian = MAI->isLittleEndian();
992 for (unsigned Emitted = 0; Emitted != Size;) {
993 unsigned Remaining = Size - Emitted;
994 // The size of our partial emission must be a power of two less than
995 // Size.
996 unsigned EmissionSize = PowerOf2Floor(std::min(Remaining, Size - 1));
997 // Calculate the byte offset of our partial emission taking into account
998 // the endianness of the target.
999 unsigned ByteOffset =
1000 IsLittleEndian ? Emitted : (Remaining - EmissionSize);
1001 uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
1002 // We truncate our partial emission to fit within the bounds of the
1003 // emission domain. This produces nicer output and silences potential
1004 // truncation warnings when round tripping through another assembler.
1005 uint64_t Shift = 64 - EmissionSize * 8;
1006 assert(Shift < static_cast<uint64_t>(
1007 std::numeric_limits<unsigned long long>::digits) &&
1008 "undefined behavior");
1009 ValueToEmit &= ~0ULL >> Shift;
1010 EmitIntValue(ValueToEmit, EmissionSize);
1011 Emitted += EmissionSize;
1013 return;
1016 assert(Directive && "Invalid size for machine code value!");
1017 OS << Directive;
1018 if (MCTargetStreamer *TS = getTargetStreamer()) {
1019 TS->emitValue(Value);
1020 } else {
1021 Value->print(OS, MAI);
1022 EmitEOL();
1026 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
1027 int64_t IntValue;
1028 if (Value->evaluateAsAbsolute(IntValue)) {
1029 EmitULEB128IntValue(IntValue);
1030 return;
1032 OS << "\t.uleb128 ";
1033 Value->print(OS, MAI);
1034 EmitEOL();
1037 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
1038 int64_t IntValue;
1039 if (Value->evaluateAsAbsolute(IntValue)) {
1040 EmitSLEB128IntValue(IntValue);
1041 return;
1043 OS << "\t.sleb128 ";
1044 Value->print(OS, MAI);
1045 EmitEOL();
1048 void MCAsmStreamer::EmitDTPRel64Value(const MCExpr *Value) {
1049 assert(MAI->getDTPRel64Directive() != nullptr);
1050 OS << MAI->getDTPRel64Directive();
1051 Value->print(OS, MAI);
1052 EmitEOL();
1055 void MCAsmStreamer::EmitDTPRel32Value(const MCExpr *Value) {
1056 assert(MAI->getDTPRel32Directive() != nullptr);
1057 OS << MAI->getDTPRel32Directive();
1058 Value->print(OS, MAI);
1059 EmitEOL();
1062 void MCAsmStreamer::EmitTPRel64Value(const MCExpr *Value) {
1063 assert(MAI->getTPRel64Directive() != nullptr);
1064 OS << MAI->getTPRel64Directive();
1065 Value->print(OS, MAI);
1066 EmitEOL();
1069 void MCAsmStreamer::EmitTPRel32Value(const MCExpr *Value) {
1070 assert(MAI->getTPRel32Directive() != nullptr);
1071 OS << MAI->getTPRel32Directive();
1072 Value->print(OS, MAI);
1073 EmitEOL();
1076 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
1077 assert(MAI->getGPRel64Directive() != nullptr);
1078 OS << MAI->getGPRel64Directive();
1079 Value->print(OS, MAI);
1080 EmitEOL();
1083 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
1084 assert(MAI->getGPRel32Directive() != nullptr);
1085 OS << MAI->getGPRel32Directive();
1086 Value->print(OS, MAI);
1087 EmitEOL();
1090 void MCAsmStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
1091 SMLoc Loc) {
1092 int64_t IntNumBytes;
1093 if (NumBytes.evaluateAsAbsolute(IntNumBytes) && IntNumBytes == 0)
1094 return;
1096 if (const char *ZeroDirective = MAI->getZeroDirective()) {
1097 // FIXME: Emit location directives
1098 OS << ZeroDirective;
1099 NumBytes.print(OS, MAI);
1100 if (FillValue != 0)
1101 OS << ',' << (int)FillValue;
1102 EmitEOL();
1103 return;
1106 MCStreamer::emitFill(NumBytes, FillValue);
1109 void MCAsmStreamer::emitFill(const MCExpr &NumValues, int64_t Size,
1110 int64_t Expr, SMLoc Loc) {
1111 // FIXME: Emit location directives
1112 OS << "\t.fill\t";
1113 NumValues.print(OS, MAI);
1114 OS << ", " << Size << ", 0x";
1115 OS.write_hex(truncateToSize(Expr, 4));
1116 EmitEOL();
1119 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
1120 unsigned ValueSize,
1121 unsigned MaxBytesToEmit) {
1122 // Some assemblers don't support non-power of two alignments, so we always
1123 // emit alignments as a power of two if possible.
1124 if (isPowerOf2_32(ByteAlignment)) {
1125 switch (ValueSize) {
1126 default:
1127 llvm_unreachable("Invalid size for machine code value!");
1128 case 1:
1129 OS << "\t.p2align\t";
1130 break;
1131 case 2:
1132 OS << ".p2alignw ";
1133 break;
1134 case 4:
1135 OS << ".p2alignl ";
1136 break;
1137 case 8:
1138 llvm_unreachable("Unsupported alignment size!");
1141 OS << Log2_32(ByteAlignment);
1143 if (Value || MaxBytesToEmit) {
1144 OS << ", 0x";
1145 OS.write_hex(truncateToSize(Value, ValueSize));
1147 if (MaxBytesToEmit)
1148 OS << ", " << MaxBytesToEmit;
1150 EmitEOL();
1151 return;
1154 // Non-power of two alignment. This is not widely supported by assemblers.
1155 // FIXME: Parameterize this based on MAI.
1156 switch (ValueSize) {
1157 default: llvm_unreachable("Invalid size for machine code value!");
1158 case 1: OS << ".balign"; break;
1159 case 2: OS << ".balignw"; break;
1160 case 4: OS << ".balignl"; break;
1161 case 8: llvm_unreachable("Unsupported alignment size!");
1164 OS << ' ' << ByteAlignment;
1165 OS << ", " << truncateToSize(Value, ValueSize);
1166 if (MaxBytesToEmit)
1167 OS << ", " << MaxBytesToEmit;
1168 EmitEOL();
1171 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
1172 unsigned MaxBytesToEmit) {
1173 // Emit with a text fill value.
1174 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
1175 1, MaxBytesToEmit);
1178 void MCAsmStreamer::emitValueToOffset(const MCExpr *Offset,
1179 unsigned char Value,
1180 SMLoc Loc) {
1181 // FIXME: Verify that Offset is associated with the current section.
1182 OS << ".org ";
1183 Offset->print(OS, MAI);
1184 OS << ", " << (unsigned)Value;
1185 EmitEOL();
1188 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
1189 assert(MAI->hasSingleParameterDotFile());
1190 OS << "\t.file\t";
1191 PrintQuotedString(Filename, OS);
1192 EmitEOL();
1195 static void printDwarfFileDirective(unsigned FileNo, StringRef Directory,
1196 StringRef Filename,
1197 Optional<MD5::MD5Result> Checksum,
1198 Optional<StringRef> Source,
1199 bool UseDwarfDirectory,
1200 raw_svector_ostream &OS) {
1201 SmallString<128> FullPathName;
1203 if (!UseDwarfDirectory && !Directory.empty()) {
1204 if (sys::path::is_absolute(Filename))
1205 Directory = "";
1206 else {
1207 FullPathName = Directory;
1208 sys::path::append(FullPathName, Filename);
1209 Directory = "";
1210 Filename = FullPathName;
1214 OS << "\t.file\t" << FileNo << ' ';
1215 if (!Directory.empty()) {
1216 PrintQuotedString(Directory, OS);
1217 OS << ' ';
1219 PrintQuotedString(Filename, OS);
1220 if (Checksum)
1221 OS << " md5 0x" << Checksum->digest();
1222 if (Source) {
1223 OS << " source ";
1224 PrintQuotedString(*Source, OS);
1228 Expected<unsigned> MCAsmStreamer::tryEmitDwarfFileDirective(
1229 unsigned FileNo, StringRef Directory, StringRef Filename,
1230 Optional<MD5::MD5Result> Checksum, Optional<StringRef> Source, unsigned CUID) {
1231 assert(CUID == 0 && "multiple CUs not supported by MCAsmStreamer");
1233 MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
1234 unsigned NumFiles = Table.getMCDwarfFiles().size();
1235 Expected<unsigned> FileNoOrErr =
1236 Table.tryGetFile(Directory, Filename, Checksum, Source,
1237 getContext().getDwarfVersion(), FileNo);
1238 if (!FileNoOrErr)
1239 return FileNoOrErr.takeError();
1240 FileNo = FileNoOrErr.get();
1241 if (NumFiles == Table.getMCDwarfFiles().size())
1242 return FileNo;
1244 SmallString<128> Str;
1245 raw_svector_ostream OS1(Str);
1246 printDwarfFileDirective(FileNo, Directory, Filename, Checksum, Source,
1247 UseDwarfDirectory, OS1);
1249 if (MCTargetStreamer *TS = getTargetStreamer())
1250 TS->emitDwarfFileDirective(OS1.str());
1251 else
1252 EmitRawText(OS1.str());
1254 return FileNo;
1257 void MCAsmStreamer::emitDwarfFile0Directive(StringRef Directory,
1258 StringRef Filename,
1259 Optional<MD5::MD5Result> Checksum,
1260 Optional<StringRef> Source,
1261 unsigned CUID) {
1262 assert(CUID == 0);
1263 // .file 0 is new for DWARF v5.
1264 if (getContext().getDwarfVersion() < 5)
1265 return;
1266 // Inform MCDwarf about the root file.
1267 getContext().setMCLineTableRootFile(CUID, Directory, Filename, Checksum,
1268 Source);
1270 SmallString<128> Str;
1271 raw_svector_ostream OS1(Str);
1272 printDwarfFileDirective(0, Directory, Filename, Checksum, Source,
1273 UseDwarfDirectory, OS1);
1275 if (MCTargetStreamer *TS = getTargetStreamer())
1276 TS->emitDwarfFileDirective(OS1.str());
1277 else
1278 EmitRawText(OS1.str());
1281 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
1282 unsigned Column, unsigned Flags,
1283 unsigned Isa,
1284 unsigned Discriminator,
1285 StringRef FileName) {
1286 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
1287 if (MAI->supportsExtendedDwarfLocDirective()) {
1288 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
1289 OS << " basic_block";
1290 if (Flags & DWARF2_FLAG_PROLOGUE_END)
1291 OS << " prologue_end";
1292 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
1293 OS << " epilogue_begin";
1295 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
1296 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
1297 OS << " is_stmt ";
1299 if (Flags & DWARF2_FLAG_IS_STMT)
1300 OS << "1";
1301 else
1302 OS << "0";
1305 if (Isa)
1306 OS << " isa " << Isa;
1307 if (Discriminator)
1308 OS << " discriminator " << Discriminator;
1311 if (IsVerboseAsm) {
1312 OS.PadToColumn(MAI->getCommentColumn());
1313 OS << MAI->getCommentString() << ' ' << FileName << ':'
1314 << Line << ':' << Column;
1316 EmitEOL();
1317 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
1318 Isa, Discriminator, FileName);
1321 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
1322 // Always use the zeroth line table, since asm syntax only supports one line
1323 // table for now.
1324 return MCStreamer::getDwarfLineTableSymbol(0);
1327 bool MCAsmStreamer::EmitCVFileDirective(unsigned FileNo, StringRef Filename,
1328 ArrayRef<uint8_t> Checksum,
1329 unsigned ChecksumKind) {
1330 if (!getContext().getCVContext().addFile(*this, FileNo, Filename, Checksum,
1331 ChecksumKind))
1332 return false;
1334 OS << "\t.cv_file\t" << FileNo << ' ';
1335 PrintQuotedString(Filename, OS);
1337 if (!ChecksumKind) {
1338 EmitEOL();
1339 return true;
1342 OS << ' ';
1343 PrintQuotedString(toHex(Checksum), OS);
1344 OS << ' ' << ChecksumKind;
1346 EmitEOL();
1347 return true;
1350 bool MCAsmStreamer::EmitCVFuncIdDirective(unsigned FuncId) {
1351 OS << "\t.cv_func_id " << FuncId << '\n';
1352 return MCStreamer::EmitCVFuncIdDirective(FuncId);
1355 bool MCAsmStreamer::EmitCVInlineSiteIdDirective(unsigned FunctionId,
1356 unsigned IAFunc,
1357 unsigned IAFile,
1358 unsigned IALine, unsigned IACol,
1359 SMLoc Loc) {
1360 OS << "\t.cv_inline_site_id " << FunctionId << " within " << IAFunc
1361 << " inlined_at " << IAFile << ' ' << IALine << ' ' << IACol << '\n';
1362 return MCStreamer::EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
1363 IALine, IACol, Loc);
1366 void MCAsmStreamer::EmitCVLocDirective(unsigned FunctionId, unsigned FileNo,
1367 unsigned Line, unsigned Column,
1368 bool PrologueEnd, bool IsStmt,
1369 StringRef FileName, SMLoc Loc) {
1370 // Validate the directive.
1371 if (!checkCVLocSection(FunctionId, FileNo, Loc))
1372 return;
1374 OS << "\t.cv_loc\t" << FunctionId << " " << FileNo << " " << Line << " "
1375 << Column;
1376 if (PrologueEnd)
1377 OS << " prologue_end";
1379 if (IsStmt)
1380 OS << " is_stmt 1";
1382 if (IsVerboseAsm) {
1383 OS.PadToColumn(MAI->getCommentColumn());
1384 OS << MAI->getCommentString() << ' ' << FileName << ':' << Line << ':'
1385 << Column;
1387 EmitEOL();
1390 void MCAsmStreamer::EmitCVLinetableDirective(unsigned FunctionId,
1391 const MCSymbol *FnStart,
1392 const MCSymbol *FnEnd) {
1393 OS << "\t.cv_linetable\t" << FunctionId << ", ";
1394 FnStart->print(OS, MAI);
1395 OS << ", ";
1396 FnEnd->print(OS, MAI);
1397 EmitEOL();
1398 this->MCStreamer::EmitCVLinetableDirective(FunctionId, FnStart, FnEnd);
1401 void MCAsmStreamer::EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
1402 unsigned SourceFileId,
1403 unsigned SourceLineNum,
1404 const MCSymbol *FnStartSym,
1405 const MCSymbol *FnEndSym) {
1406 OS << "\t.cv_inline_linetable\t" << PrimaryFunctionId << ' ' << SourceFileId
1407 << ' ' << SourceLineNum << ' ';
1408 FnStartSym->print(OS, MAI);
1409 OS << ' ';
1410 FnEndSym->print(OS, MAI);
1411 EmitEOL();
1412 this->MCStreamer::EmitCVInlineLinetableDirective(
1413 PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
1416 void MCAsmStreamer::PrintCVDefRangePrefix(
1417 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges) {
1418 OS << "\t.cv_def_range\t";
1419 for (std::pair<const MCSymbol *, const MCSymbol *> Range : Ranges) {
1420 OS << ' ';
1421 Range.first->print(OS, MAI);
1422 OS << ' ';
1423 Range.second->print(OS, MAI);
1427 void MCAsmStreamer::EmitCVDefRangeDirective(
1428 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1429 codeview::DefRangeRegisterRelSym::Header DRHdr) {
1430 PrintCVDefRangePrefix(Ranges);
1431 OS << ", reg_rel, ";
1432 OS << DRHdr.Register << ", " << DRHdr.Flags << ", "
1433 << DRHdr.BasePointerOffset;
1434 EmitEOL();
1437 void MCAsmStreamer::EmitCVDefRangeDirective(
1438 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1439 codeview::DefRangeSubfieldRegisterSym::Header DRHdr) {
1440 PrintCVDefRangePrefix(Ranges);
1441 OS << ", subfield_reg, ";
1442 OS << DRHdr.Register << ", " << DRHdr.OffsetInParent;
1443 EmitEOL();
1446 void MCAsmStreamer::EmitCVDefRangeDirective(
1447 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1448 codeview::DefRangeRegisterSym::Header DRHdr) {
1449 PrintCVDefRangePrefix(Ranges);
1450 OS << ", reg, ";
1451 OS << DRHdr.Register;
1452 EmitEOL();
1455 void MCAsmStreamer::EmitCVDefRangeDirective(
1456 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1457 codeview::DefRangeFramePointerRelSym::Header DRHdr) {
1458 PrintCVDefRangePrefix(Ranges);
1459 OS << ", frame_ptr_rel, ";
1460 OS << DRHdr.Offset;
1461 EmitEOL();
1464 void MCAsmStreamer::EmitCVStringTableDirective() {
1465 OS << "\t.cv_stringtable";
1466 EmitEOL();
1469 void MCAsmStreamer::EmitCVFileChecksumsDirective() {
1470 OS << "\t.cv_filechecksums";
1471 EmitEOL();
1474 void MCAsmStreamer::EmitCVFileChecksumOffsetDirective(unsigned FileNo) {
1475 OS << "\t.cv_filechecksumoffset\t" << FileNo;
1476 EmitEOL();
1479 void MCAsmStreamer::EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) {
1480 OS << "\t.cv_fpo_data\t";
1481 ProcSym->print(OS, MAI);
1482 EmitEOL();
1485 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
1486 assert(MAI->hasIdentDirective() && ".ident directive not supported");
1487 OS << "\t.ident\t";
1488 PrintQuotedString(IdentString, OS);
1489 EmitEOL();
1492 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
1493 MCStreamer::EmitCFISections(EH, Debug);
1494 OS << "\t.cfi_sections ";
1495 if (EH) {
1496 OS << ".eh_frame";
1497 if (Debug)
1498 OS << ", .debug_frame";
1499 } else if (Debug) {
1500 OS << ".debug_frame";
1503 EmitEOL();
1506 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
1507 OS << "\t.cfi_startproc";
1508 if (Frame.IsSimple)
1509 OS << " simple";
1510 EmitEOL();
1513 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
1514 MCStreamer::EmitCFIEndProcImpl(Frame);
1515 OS << "\t.cfi_endproc";
1516 EmitEOL();
1519 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
1520 if (!MAI->useDwarfRegNumForCFI()) {
1521 // User .cfi_* directives can use arbitrary DWARF register numbers, not
1522 // just ones that map to LLVM register numbers and have known names.
1523 // Fall back to using the original number directly if no name is known.
1524 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1525 int LLVMRegister = MRI->getLLVMRegNumFromEH(Register);
1526 if (LLVMRegister != -1) {
1527 InstPrinter->printRegName(OS, LLVMRegister);
1528 return;
1531 OS << Register;
1534 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
1535 MCStreamer::EmitCFIDefCfa(Register, Offset);
1536 OS << "\t.cfi_def_cfa ";
1537 EmitRegisterName(Register);
1538 OS << ", " << Offset;
1539 EmitEOL();
1542 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
1543 MCStreamer::EmitCFIDefCfaOffset(Offset);
1544 OS << "\t.cfi_def_cfa_offset " << Offset;
1545 EmitEOL();
1548 static void PrintCFIEscape(llvm::formatted_raw_ostream &OS, StringRef Values) {
1549 OS << "\t.cfi_escape ";
1550 if (!Values.empty()) {
1551 size_t e = Values.size() - 1;
1552 for (size_t i = 0; i < e; ++i)
1553 OS << format("0x%02x", uint8_t(Values[i])) << ", ";
1554 OS << format("0x%02x", uint8_t(Values[e]));
1558 void MCAsmStreamer::EmitCFIEscape(StringRef Values) {
1559 MCStreamer::EmitCFIEscape(Values);
1560 PrintCFIEscape(OS, Values);
1561 EmitEOL();
1564 void MCAsmStreamer::EmitCFIGnuArgsSize(int64_t Size) {
1565 MCStreamer::EmitCFIGnuArgsSize(Size);
1567 uint8_t Buffer[16] = { dwarf::DW_CFA_GNU_args_size };
1568 unsigned Len = encodeULEB128(Size, Buffer + 1) + 1;
1570 PrintCFIEscape(OS, StringRef((const char *)&Buffer[0], Len));
1571 EmitEOL();
1574 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
1575 MCStreamer::EmitCFIDefCfaRegister(Register);
1576 OS << "\t.cfi_def_cfa_register ";
1577 EmitRegisterName(Register);
1578 EmitEOL();
1581 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
1582 this->MCStreamer::EmitCFIOffset(Register, Offset);
1583 OS << "\t.cfi_offset ";
1584 EmitRegisterName(Register);
1585 OS << ", " << Offset;
1586 EmitEOL();
1589 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1590 unsigned Encoding) {
1591 MCStreamer::EmitCFIPersonality(Sym, Encoding);
1592 OS << "\t.cfi_personality " << Encoding << ", ";
1593 Sym->print(OS, MAI);
1594 EmitEOL();
1597 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1598 MCStreamer::EmitCFILsda(Sym, Encoding);
1599 OS << "\t.cfi_lsda " << Encoding << ", ";
1600 Sym->print(OS, MAI);
1601 EmitEOL();
1604 void MCAsmStreamer::EmitCFIRememberState() {
1605 MCStreamer::EmitCFIRememberState();
1606 OS << "\t.cfi_remember_state";
1607 EmitEOL();
1610 void MCAsmStreamer::EmitCFIRestoreState() {
1611 MCStreamer::EmitCFIRestoreState();
1612 OS << "\t.cfi_restore_state";
1613 EmitEOL();
1616 void MCAsmStreamer::EmitCFIRestore(int64_t Register) {
1617 MCStreamer::EmitCFIRestore(Register);
1618 OS << "\t.cfi_restore ";
1619 EmitRegisterName(Register);
1620 EmitEOL();
1623 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1624 MCStreamer::EmitCFISameValue(Register);
1625 OS << "\t.cfi_same_value ";
1626 EmitRegisterName(Register);
1627 EmitEOL();
1630 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1631 MCStreamer::EmitCFIRelOffset(Register, Offset);
1632 OS << "\t.cfi_rel_offset ";
1633 EmitRegisterName(Register);
1634 OS << ", " << Offset;
1635 EmitEOL();
1638 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1639 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1640 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1641 EmitEOL();
1644 void MCAsmStreamer::EmitCFISignalFrame() {
1645 MCStreamer::EmitCFISignalFrame();
1646 OS << "\t.cfi_signal_frame";
1647 EmitEOL();
1650 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1651 MCStreamer::EmitCFIUndefined(Register);
1652 OS << "\t.cfi_undefined " << Register;
1653 EmitEOL();
1656 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1657 MCStreamer::EmitCFIRegister(Register1, Register2);
1658 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1659 EmitEOL();
1662 void MCAsmStreamer::EmitCFIWindowSave() {
1663 MCStreamer::EmitCFIWindowSave();
1664 OS << "\t.cfi_window_save";
1665 EmitEOL();
1668 void MCAsmStreamer::EmitCFINegateRAState() {
1669 MCStreamer::EmitCFINegateRAState();
1670 OS << "\t.cfi_negate_ra_state";
1671 EmitEOL();
1674 void MCAsmStreamer::EmitCFIReturnColumn(int64_t Register) {
1675 MCStreamer::EmitCFIReturnColumn(Register);
1676 OS << "\t.cfi_return_column " << Register;
1677 EmitEOL();
1680 void MCAsmStreamer::EmitCFIBKeyFrame() {
1681 MCStreamer::EmitCFIBKeyFrame();
1682 OS << "\t.cfi_b_key_frame";
1683 EmitEOL();
1686 void MCAsmStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) {
1687 MCStreamer::EmitWinCFIStartProc(Symbol, Loc);
1689 OS << ".seh_proc ";
1690 Symbol->print(OS, MAI);
1691 EmitEOL();
1694 void MCAsmStreamer::EmitWinCFIEndProc(SMLoc Loc) {
1695 MCStreamer::EmitWinCFIEndProc(Loc);
1697 OS << "\t.seh_endproc";
1698 EmitEOL();
1701 // TODO: Implement
1702 void MCAsmStreamer::EmitWinCFIFuncletOrFuncEnd(SMLoc Loc) {
1705 void MCAsmStreamer::EmitWinCFIStartChained(SMLoc Loc) {
1706 MCStreamer::EmitWinCFIStartChained(Loc);
1708 OS << "\t.seh_startchained";
1709 EmitEOL();
1712 void MCAsmStreamer::EmitWinCFIEndChained(SMLoc Loc) {
1713 MCStreamer::EmitWinCFIEndChained(Loc);
1715 OS << "\t.seh_endchained";
1716 EmitEOL();
1719 void MCAsmStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind,
1720 bool Except, SMLoc Loc) {
1721 MCStreamer::EmitWinEHHandler(Sym, Unwind, Except, Loc);
1723 OS << "\t.seh_handler ";
1724 Sym->print(OS, MAI);
1725 if (Unwind)
1726 OS << ", @unwind";
1727 if (Except)
1728 OS << ", @except";
1729 EmitEOL();
1732 void MCAsmStreamer::EmitWinEHHandlerData(SMLoc Loc) {
1733 MCStreamer::EmitWinEHHandlerData(Loc);
1735 // Switch sections. Don't call SwitchSection directly, because that will
1736 // cause the section switch to be visible in the emitted assembly.
1737 // We only do this so the section switch that terminates the handler
1738 // data block is visible.
1739 WinEH::FrameInfo *CurFrame = getCurrentWinFrameInfo();
1740 MCSection *TextSec = &CurFrame->Function->getSection();
1741 MCSection *XData = getAssociatedXDataSection(TextSec);
1742 SwitchSectionNoChange(XData);
1744 OS << "\t.seh_handlerdata";
1745 EmitEOL();
1748 void MCAsmStreamer::EmitWinCFIPushReg(unsigned Register, SMLoc Loc) {
1749 MCStreamer::EmitWinCFIPushReg(Register, Loc);
1751 OS << "\t.seh_pushreg " << Register;
1752 EmitEOL();
1755 void MCAsmStreamer::EmitWinCFISetFrame(unsigned Register, unsigned Offset,
1756 SMLoc Loc) {
1757 MCStreamer::EmitWinCFISetFrame(Register, Offset, Loc);
1759 OS << "\t.seh_setframe " << Register << ", " << Offset;
1760 EmitEOL();
1763 void MCAsmStreamer::EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) {
1764 MCStreamer::EmitWinCFIAllocStack(Size, Loc);
1766 OS << "\t.seh_stackalloc " << Size;
1767 EmitEOL();
1770 void MCAsmStreamer::EmitWinCFISaveReg(unsigned Register, unsigned Offset,
1771 SMLoc Loc) {
1772 MCStreamer::EmitWinCFISaveReg(Register, Offset, Loc);
1774 OS << "\t.seh_savereg " << Register << ", " << Offset;
1775 EmitEOL();
1778 void MCAsmStreamer::EmitWinCFISaveXMM(unsigned Register, unsigned Offset,
1779 SMLoc Loc) {
1780 MCStreamer::EmitWinCFISaveXMM(Register, Offset, Loc);
1782 OS << "\t.seh_savexmm " << Register << ", " << Offset;
1783 EmitEOL();
1786 void MCAsmStreamer::EmitWinCFIPushFrame(bool Code, SMLoc Loc) {
1787 MCStreamer::EmitWinCFIPushFrame(Code, Loc);
1789 OS << "\t.seh_pushframe";
1790 if (Code)
1791 OS << " @code";
1792 EmitEOL();
1795 void MCAsmStreamer::EmitWinCFIEndProlog(SMLoc Loc) {
1796 MCStreamer::EmitWinCFIEndProlog(Loc);
1798 OS << "\t.seh_endprologue";
1799 EmitEOL();
1802 void MCAsmStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
1803 const MCSymbolRefExpr *To,
1804 uint64_t Count) {
1805 OS << "\t.cg_profile ";
1806 From->getSymbol().print(OS, MAI);
1807 OS << ", ";
1808 To->getSymbol().print(OS, MAI);
1809 OS << ", " << Count;
1810 EmitEOL();
1813 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1814 const MCSubtargetInfo &STI) {
1815 raw_ostream &OS = GetCommentOS();
1816 SmallString<256> Code;
1817 SmallVector<MCFixup, 4> Fixups;
1818 raw_svector_ostream VecOS(Code);
1820 // If we have no code emitter, don't emit code.
1821 if (!getAssembler().getEmitterPtr())
1822 return;
1824 getAssembler().getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
1826 // If we are showing fixups, create symbolic markers in the encoded
1827 // representation. We do this by making a per-bit map to the fixup item index,
1828 // then trying to display it as nicely as possible.
1829 SmallVector<uint8_t, 64> FixupMap;
1830 FixupMap.resize(Code.size() * 8);
1831 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1832 FixupMap[i] = 0;
1834 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1835 MCFixup &F = Fixups[i];
1836 const MCFixupKindInfo &Info =
1837 getAssembler().getBackend().getFixupKindInfo(F.getKind());
1838 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1839 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1840 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1841 FixupMap[Index] = 1 + i;
1845 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1846 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1847 OS << "encoding: [";
1848 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1849 if (i)
1850 OS << ',';
1852 // See if all bits are the same map entry.
1853 uint8_t MapEntry = FixupMap[i * 8 + 0];
1854 for (unsigned j = 1; j != 8; ++j) {
1855 if (FixupMap[i * 8 + j] == MapEntry)
1856 continue;
1858 MapEntry = uint8_t(~0U);
1859 break;
1862 if (MapEntry != uint8_t(~0U)) {
1863 if (MapEntry == 0) {
1864 OS << format("0x%02x", uint8_t(Code[i]));
1865 } else {
1866 if (Code[i]) {
1867 // FIXME: Some of the 8 bits require fix up.
1868 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1869 << char('A' + MapEntry - 1) << '\'';
1870 } else
1871 OS << char('A' + MapEntry - 1);
1873 } else {
1874 // Otherwise, write out in binary.
1875 OS << "0b";
1876 for (unsigned j = 8; j--;) {
1877 unsigned Bit = (Code[i] >> j) & 1;
1879 unsigned FixupBit;
1880 if (MAI->isLittleEndian())
1881 FixupBit = i * 8 + j;
1882 else
1883 FixupBit = i * 8 + (7-j);
1885 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1886 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1887 OS << char('A' + MapEntry - 1);
1888 } else
1889 OS << Bit;
1893 OS << "]\n";
1895 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1896 MCFixup &F = Fixups[i];
1897 const MCFixupKindInfo &Info =
1898 getAssembler().getBackend().getFixupKindInfo(F.getKind());
1899 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1900 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1904 void MCAsmStreamer::EmitInstruction(const MCInst &Inst,
1905 const MCSubtargetInfo &STI) {
1906 assert(getCurrentSectionOnly() &&
1907 "Cannot emit contents before setting section!");
1909 // Show the encoding in a comment if we have a code emitter.
1910 AddEncodingComment(Inst, STI);
1912 // Show the MCInst if enabled.
1913 if (ShowInst) {
1914 Inst.dump_pretty(GetCommentOS(), InstPrinter.get(), "\n ");
1915 GetCommentOS() << "\n";
1918 if(getTargetStreamer())
1919 getTargetStreamer()->prettyPrintAsm(*InstPrinter, OS, Inst, STI);
1920 else
1921 InstPrinter->printInst(&Inst, OS, "", STI);
1923 StringRef Comments = CommentToEmit;
1924 if (Comments.size() && Comments.back() != '\n')
1925 GetCommentOS() << "\n";
1927 EmitEOL();
1930 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1931 OS << "\t.bundle_align_mode " << AlignPow2;
1932 EmitEOL();
1935 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1936 OS << "\t.bundle_lock";
1937 if (AlignToEnd)
1938 OS << " align_to_end";
1939 EmitEOL();
1942 void MCAsmStreamer::EmitBundleUnlock() {
1943 OS << "\t.bundle_unlock";
1944 EmitEOL();
1947 bool MCAsmStreamer::EmitRelocDirective(const MCExpr &Offset, StringRef Name,
1948 const MCExpr *Expr, SMLoc,
1949 const MCSubtargetInfo &STI) {
1950 OS << "\t.reloc ";
1951 Offset.print(OS, MAI);
1952 OS << ", " << Name;
1953 if (Expr) {
1954 OS << ", ";
1955 Expr->print(OS, MAI);
1957 EmitEOL();
1958 return false;
1961 void MCAsmStreamer::EmitAddrsig() {
1962 OS << "\t.addrsig";
1963 EmitEOL();
1966 void MCAsmStreamer::EmitAddrsigSym(const MCSymbol *Sym) {
1967 OS << "\t.addrsig_sym ";
1968 Sym->print(OS, MAI);
1969 EmitEOL();
1972 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1973 /// the specified string in the output .s file. This capability is
1974 /// indicated by the hasRawTextSupport() predicate.
1975 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1976 if (!String.empty() && String.back() == '\n')
1977 String = String.substr(0, String.size()-1);
1978 OS << String;
1979 EmitEOL();
1982 void MCAsmStreamer::FinishImpl() {
1983 // If we are generating dwarf for assembly source files dump out the sections.
1984 if (getContext().getGenDwarfForAssembly())
1985 MCGenDwarfInfo::Emit(this);
1987 // Emit the label for the line table, if requested - since the rest of the
1988 // line table will be defined by .loc/.file directives, and not emitted
1989 // directly, the label is the only work required here.
1990 const auto &Tables = getContext().getMCDwarfLineTables();
1991 if (!Tables.empty()) {
1992 assert(Tables.size() == 1 && "asm output only supports one line table");
1993 if (auto *Label = Tables.begin()->second.getLabel()) {
1994 SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
1995 EmitLabel(Label);
2000 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
2001 std::unique_ptr<formatted_raw_ostream> OS,
2002 bool isVerboseAsm, bool useDwarfDirectory,
2003 MCInstPrinter *IP,
2004 std::unique_ptr<MCCodeEmitter> &&CE,
2005 std::unique_ptr<MCAsmBackend> &&MAB,
2006 bool ShowInst) {
2007 return new MCAsmStreamer(Context, std::move(OS), isVerboseAsm,
2008 useDwarfDirectory, IP, std::move(CE), std::move(MAB),
2009 ShowInst);