Recommit r310809 with a fix for the spill problem
[llvm-core.git] / lib / MC / MCAsmStreamer.cpp
blobb1c928950cbf8c0836789cbdfe39c62bb7b8bd22
1 //===- lib/MC/MCAsmStreamer.cpp - Text Assembly Output ----------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
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/MCCodeEmitter.h"
17 #include "llvm/MC/MCCodeView.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCFixupKindInfo.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/MC/MCObjectFileInfo.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCSectionCOFF.h"
26 #include "llvm/MC/MCSectionMachO.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSymbolELF.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/SourceMgr.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<MCCodeEmitter> Emitter;
48 std::unique_ptr<MCAsmBackend> AsmBackend;
50 SmallString<128> ExplicitCommentToEmit;
51 SmallString<128> CommentToEmit;
52 raw_svector_ostream CommentStream;
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, MCCodeEmitter *emitter,
66 MCAsmBackend *asmbackend, bool showInst)
67 : MCStreamer(Context), OSOwner(std::move(os)), OS(*OSOwner),
68 MAI(Context.getAsmInfo()), InstPrinter(printer), Emitter(emitter),
69 AsmBackend(asmbackend), CommentStream(CommentToEmit),
70 IsVerboseAsm(isVerboseAsm), ShowInst(showInst),
71 UseDwarfDirectory(useDwarfDirectory) {
72 assert(InstPrinter);
73 if (IsVerboseAsm)
74 InstPrinter->setCommentStream(CommentStream);
77 inline void EmitEOL() {
78 // Dump Explicit Comments here.
79 emitExplicitComments();
80 // If we don't have any comments, just emit a \n.
81 if (!IsVerboseAsm) {
82 OS << '\n';
83 return;
85 EmitCommentsAndEOL();
88 void EmitSyntaxDirective() override;
90 void EmitCommentsAndEOL();
92 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
93 /// all.
94 bool isVerboseAsm() const override { return IsVerboseAsm; }
96 /// hasRawTextSupport - We support EmitRawText.
97 bool hasRawTextSupport() const override { return true; }
99 /// AddComment - Add a comment that can be emitted to the generated .s
100 /// file if applicable as a QoI issue to make the output of the compiler
101 /// more readable. This only affects the MCAsmStreamer, and only when
102 /// verbose assembly output is enabled.
103 void AddComment(const Twine &T, bool EOL = true) override;
105 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
106 /// If PrintSchedInfo - is true then the comment sched:[x:y] should
107 // be added to output if it's being supported by target
108 void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &,
109 bool PrintSchedInfo);
111 /// GetCommentOS - Return a raw_ostream that comments can be written to.
112 /// Unlike AddComment, you are required to terminate comments with \n if you
113 /// use this method.
114 raw_ostream &GetCommentOS() override {
115 if (!IsVerboseAsm)
116 return nulls(); // Discard comments unless in verbose asm mode.
117 return CommentStream;
120 void emitRawComment(const Twine &T, bool TabPrefix = true) override;
122 void addExplicitComment(const Twine &T) override;
123 void emitExplicitComments() override;
125 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
126 void AddBlankLine() override {
127 EmitEOL();
130 /// @name MCStreamer Interface
131 /// @{
133 void ChangeSection(MCSection *Section, const MCExpr *Subsection) override;
135 void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override;
136 void EmitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc()) override;
138 void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
139 void EmitLinkerOptions(ArrayRef<std::string> Options) override;
140 void EmitDataRegion(MCDataRegionType Kind) override;
141 void EmitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
142 unsigned Update) override;
143 void EmitThumbFunc(MCSymbol *Func) override;
145 void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
146 void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
147 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
149 void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
150 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override;
151 void EmitCOFFSymbolStorageClass(int StorageClass) override;
152 void EmitCOFFSymbolType(int Type) override;
153 void EndCOFFSymbolDef() override;
154 void EmitCOFFSafeSEH(MCSymbol const *Symbol) override;
155 void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
156 void EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) override;
157 void emitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
158 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
159 unsigned ByteAlignment) override;
161 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
163 /// @param Symbol - The common symbol to emit.
164 /// @param Size - The size of the common symbol.
165 /// @param ByteAlignment - The alignment of the common symbol in bytes.
166 void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
167 unsigned ByteAlignment) override;
169 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
170 uint64_t Size = 0, unsigned ByteAlignment = 0) override;
172 void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
173 unsigned ByteAlignment = 0) override;
175 void EmitBinaryData(StringRef Data) override;
177 void EmitBytes(StringRef Data) override;
179 void EmitValueImpl(const MCExpr *Value, unsigned Size,
180 SMLoc Loc = SMLoc()) override;
181 void EmitIntValue(uint64_t Value, unsigned Size) override;
183 void EmitULEB128Value(const MCExpr *Value) override;
185 void EmitSLEB128Value(const MCExpr *Value) override;
187 void EmitDTPRel32Value(const MCExpr *Value) override;
188 void EmitDTPRel64Value(const MCExpr *Value) override;
189 void EmitTPRel32Value(const MCExpr *Value) override;
190 void EmitTPRel64Value(const MCExpr *Value) override;
192 void EmitGPRel64Value(const MCExpr *Value) override;
194 void EmitGPRel32Value(const MCExpr *Value) override;
197 void emitFill(uint64_t NumBytes, uint8_t FillValue) override;
199 void emitFill(const MCExpr &NumBytes, uint64_t FillValue,
200 SMLoc Loc = SMLoc()) override;
202 void emitFill(uint64_t NumValues, int64_t Size, int64_t Expr) override;
204 void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
205 SMLoc Loc = SMLoc()) override;
207 void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
208 unsigned ValueSize = 1,
209 unsigned MaxBytesToEmit = 0) override;
211 void EmitCodeAlignment(unsigned ByteAlignment,
212 unsigned MaxBytesToEmit = 0) override;
214 void emitValueToOffset(const MCExpr *Offset,
215 unsigned char Value,
216 SMLoc Loc) override;
218 void EmitFileDirective(StringRef Filename) override;
219 unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
220 StringRef Filename,
221 unsigned CUID = 0) override;
222 void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
223 unsigned Column, unsigned Flags,
224 unsigned Isa, unsigned Discriminator,
225 StringRef FileName) override;
226 MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
228 bool EmitCVFileDirective(unsigned FileNo, StringRef Filename,
229 ArrayRef<uint8_t> Checksum,
230 unsigned ChecksumKind) override;
231 bool EmitCVFuncIdDirective(unsigned FuncId) override;
232 bool EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc,
233 unsigned IAFile, unsigned IALine,
234 unsigned IACol, SMLoc Loc) override;
235 void EmitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line,
236 unsigned Column, bool PrologueEnd, bool IsStmt,
237 StringRef FileName, SMLoc Loc) override;
238 void EmitCVLinetableDirective(unsigned FunctionId, const MCSymbol *FnStart,
239 const MCSymbol *FnEnd) override;
240 void EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
241 unsigned SourceFileId,
242 unsigned SourceLineNum,
243 const MCSymbol *FnStartSym,
244 const MCSymbol *FnEndSym) override;
245 void EmitCVDefRangeDirective(
246 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
247 StringRef FixedSizePortion) override;
248 void EmitCVStringTableDirective() override;
249 void EmitCVFileChecksumsDirective() override;
250 void EmitCVFileChecksumOffsetDirective(unsigned FileNo) override;
252 void EmitIdent(StringRef IdentString) override;
253 void EmitCFISections(bool EH, bool Debug) override;
254 void EmitCFIDefCfa(int64_t Register, int64_t Offset) override;
255 void EmitCFIDefCfaOffset(int64_t Offset) override;
256 void EmitCFIDefCfaRegister(int64_t Register) override;
257 void EmitCFIOffset(int64_t Register, int64_t Offset) override;
258 void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
259 void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
260 void EmitCFIRememberState() override;
261 void EmitCFIRestoreState() override;
262 void EmitCFISameValue(int64_t Register) override;
263 void EmitCFIRelOffset(int64_t Register, int64_t Offset) override;
264 void EmitCFIAdjustCfaOffset(int64_t Adjustment) override;
265 void EmitCFIEscape(StringRef Values) override;
266 void EmitCFIGnuArgsSize(int64_t Size) override;
267 void EmitCFISignalFrame() override;
268 void EmitCFIUndefined(int64_t Register) override;
269 void EmitCFIRegister(int64_t Register1, int64_t Register2) override;
270 void EmitCFIWindowSave() override;
271 void EmitCFIReturnColumn(int64_t Register) override;
273 void EmitWinCFIStartProc(const MCSymbol *Symbol) override;
274 void EmitWinCFIEndProc() override;
275 void EmitWinCFIStartChained() override;
276 void EmitWinCFIEndChained() override;
277 void EmitWinCFIPushReg(unsigned Register) override;
278 void EmitWinCFISetFrame(unsigned Register, unsigned Offset) override;
279 void EmitWinCFIAllocStack(unsigned Size) override;
280 void EmitWinCFISaveReg(unsigned Register, unsigned Offset) override;
281 void EmitWinCFISaveXMM(unsigned Register, unsigned Offset) override;
282 void EmitWinCFIPushFrame(bool Code) override;
283 void EmitWinCFIEndProlog() override;
285 void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except) override;
286 void EmitWinEHHandlerData() override;
288 void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
289 bool PrintSchedInfo) override;
291 void EmitBundleAlignMode(unsigned AlignPow2) override;
292 void EmitBundleLock(bool AlignToEnd) override;
293 void EmitBundleUnlock() override;
295 bool EmitRelocDirective(const MCExpr &Offset, StringRef Name,
296 const MCExpr *Expr, SMLoc Loc) override;
298 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
299 /// the specified string in the output .s file. This capability is
300 /// indicated by the hasRawTextSupport() predicate.
301 void EmitRawTextImpl(StringRef String) override;
303 void FinishImpl() override;
306 } // end anonymous namespace.
308 /// AddComment - Add a comment that can be emitted to the generated .s
309 /// file if applicable as a QoI issue to make the output of the compiler
310 /// more readable. This only affects the MCAsmStreamer, and only when
311 /// verbose assembly output is enabled.
312 /// By deafult EOL is set to true so that each comment goes on its own line.
313 void MCAsmStreamer::AddComment(const Twine &T, bool EOL) {
314 if (!IsVerboseAsm) return;
316 T.toVector(CommentToEmit);
318 if (EOL)
319 CommentToEmit.push_back('\n'); // Place comment in a new line.
322 void MCAsmStreamer::EmitCommentsAndEOL() {
323 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
324 OS << '\n';
325 return;
328 StringRef Comments = CommentToEmit;
330 assert(Comments.back() == '\n' &&
331 "Comment array not newline terminated");
332 do {
333 // Emit a line of comments.
334 OS.PadToColumn(MAI->getCommentColumn());
335 size_t Position = Comments.find('\n');
336 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
338 Comments = Comments.substr(Position+1);
339 } while (!Comments.empty());
341 CommentToEmit.clear();
344 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
345 assert(Bytes > 0 && Bytes <= 8 && "Invalid size!");
346 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
349 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
350 if (TabPrefix)
351 OS << '\t';
352 OS << MAI->getCommentString() << T;
353 EmitEOL();
356 void MCAsmStreamer::addExplicitComment(const Twine &T) {
357 StringRef c = T.getSingleStringRef();
358 if (c.equals(StringRef(MAI->getSeparatorString())))
359 return;
360 if (c.startswith(StringRef("//"))) {
361 ExplicitCommentToEmit.append("\t");
362 ExplicitCommentToEmit.append(MAI->getCommentString());
363 // drop //
364 ExplicitCommentToEmit.append(c.slice(2, c.size()).str());
365 } else if (c.startswith(StringRef("/*"))) {
366 size_t p = 2, len = c.size() - 2;
367 // emit each line in comment as separate newline.
368 do {
369 size_t newp = std::min(len, c.find_first_of("\r\n", p));
370 ExplicitCommentToEmit.append("\t");
371 ExplicitCommentToEmit.append(MAI->getCommentString());
372 ExplicitCommentToEmit.append(c.slice(p, newp).str());
373 // If we have another line in this comment add line
374 if (newp < len)
375 ExplicitCommentToEmit.append("\n");
376 p = newp + 1;
377 } while (p < len);
378 } else if (c.startswith(StringRef(MAI->getCommentString()))) {
379 ExplicitCommentToEmit.append("\t");
380 ExplicitCommentToEmit.append(c.str());
381 } else if (c.front() == '#') {
383 ExplicitCommentToEmit.append("\t");
384 ExplicitCommentToEmit.append(MAI->getCommentString());
385 ExplicitCommentToEmit.append(c.slice(1, c.size()).str());
386 } else
387 assert(false && "Unexpected Assembly Comment");
388 // full line comments immediately output
389 if (c.back() == '\n')
390 emitExplicitComments();
393 void MCAsmStreamer::emitExplicitComments() {
394 StringRef Comments = ExplicitCommentToEmit;
395 if (!Comments.empty())
396 OS << Comments;
397 ExplicitCommentToEmit.clear();
400 void MCAsmStreamer::ChangeSection(MCSection *Section,
401 const MCExpr *Subsection) {
402 assert(Section && "Cannot switch to a null section!");
403 Section->PrintSwitchToSection(
404 *MAI, getContext().getObjectFileInfo()->getTargetTriple(), OS,
405 Subsection);
408 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol, SMLoc Loc) {
409 MCStreamer::EmitLabel(Symbol, Loc);
411 Symbol->print(OS, MAI);
412 OS << MAI->getLabelSuffix();
414 EmitEOL();
417 void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
418 StringRef str = MCLOHIdToName(Kind);
420 #ifndef NDEBUG
421 int NbArgs = MCLOHIdToNbArgs(Kind);
422 assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
423 assert(str != "" && "Invalid LOH name");
424 #endif
426 OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
427 bool IsFirst = true;
428 for (const MCSymbol *Arg : Args) {
429 if (!IsFirst)
430 OS << ", ";
431 IsFirst = false;
432 Arg->print(OS, MAI);
434 EmitEOL();
437 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
438 switch (Flag) {
439 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
440 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
441 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
442 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
443 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
445 EmitEOL();
448 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
449 assert(!Options.empty() && "At least one option is required!");
450 OS << "\t.linker_option \"" << Options[0] << '"';
451 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
452 ie = Options.end(); it != ie; ++it) {
453 OS << ", " << '"' << *it << '"';
455 EmitEOL();
458 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
459 if (!MAI->doesSupportDataRegionDirectives())
460 return;
461 switch (Kind) {
462 case MCDR_DataRegion: OS << "\t.data_region"; break;
463 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
464 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
465 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
466 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
468 EmitEOL();
471 void MCAsmStreamer::EmitVersionMin(MCVersionMinType Kind, unsigned Major,
472 unsigned Minor, unsigned Update) {
473 switch (Kind) {
474 case MCVM_WatchOSVersionMin: OS << "\t.watchos_version_min"; break;
475 case MCVM_TvOSVersionMin: OS << "\t.tvos_version_min"; break;
476 case MCVM_IOSVersionMin: OS << "\t.ios_version_min"; break;
477 case MCVM_OSXVersionMin: OS << "\t.macosx_version_min"; break;
479 OS << " " << Major << ", " << Minor;
480 if (Update)
481 OS << ", " << Update;
482 EmitEOL();
485 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
486 // This needs to emit to a temporary string to get properly quoted
487 // MCSymbols when they have spaces in them.
488 OS << "\t.thumb_func";
489 // Only Mach-O hasSubsectionsViaSymbols()
490 if (MAI->hasSubsectionsViaSymbols()) {
491 OS << '\t';
492 Func->print(OS, MAI);
494 EmitEOL();
497 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
498 Symbol->print(OS, MAI);
499 OS << " = ";
500 Value->print(OS, MAI);
502 EmitEOL();
504 MCStreamer::EmitAssignment(Symbol, Value);
507 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
508 OS << ".weakref ";
509 Alias->print(OS, MAI);
510 OS << ", ";
511 Symbol->print(OS, MAI);
512 EmitEOL();
515 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
516 MCSymbolAttr Attribute) {
517 switch (Attribute) {
518 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
519 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
520 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
521 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
522 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
523 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
524 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
525 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
526 if (!MAI->hasDotTypeDotSizeDirective())
527 return false; // Symbol attribute not supported
528 OS << "\t.type\t";
529 Symbol->print(OS, MAI);
530 OS << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
531 switch (Attribute) {
532 default: return false;
533 case MCSA_ELF_TypeFunction: OS << "function"; break;
534 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
535 case MCSA_ELF_TypeObject: OS << "object"; break;
536 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
537 case MCSA_ELF_TypeCommon: OS << "common"; break;
538 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
539 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
541 EmitEOL();
542 return true;
543 case MCSA_Global: // .globl/.global
544 OS << MAI->getGlobalDirective();
545 break;
546 case MCSA_Hidden: OS << "\t.hidden\t"; break;
547 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
548 case MCSA_Internal: OS << "\t.internal\t"; break;
549 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
550 case MCSA_Local: OS << "\t.local\t"; break;
551 case MCSA_NoDeadStrip:
552 if (!MAI->hasNoDeadStrip())
553 return false;
554 OS << "\t.no_dead_strip\t";
555 break;
556 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
557 case MCSA_AltEntry: OS << "\t.alt_entry\t"; break;
558 case MCSA_PrivateExtern:
559 OS << "\t.private_extern\t";
560 break;
561 case MCSA_Protected: OS << "\t.protected\t"; break;
562 case MCSA_Reference: OS << "\t.reference\t"; break;
563 case MCSA_Weak: OS << MAI->getWeakDirective(); break;
564 case MCSA_WeakDefinition:
565 OS << "\t.weak_definition\t";
566 break;
567 // .weak_reference
568 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
569 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
572 Symbol->print(OS, MAI);
573 EmitEOL();
575 return true;
578 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
579 OS << ".desc" << ' ';
580 Symbol->print(OS, MAI);
581 OS << ',' << DescValue;
582 EmitEOL();
585 void MCAsmStreamer::EmitSyntaxDirective() {
586 if (MAI->getAssemblerDialect() == 1) {
587 OS << "\t.intel_syntax noprefix";
588 EmitEOL();
590 // FIXME: Currently emit unprefix'ed registers.
591 // The intel_syntax directive has one optional argument
592 // with may have a value of prefix or noprefix.
595 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
596 OS << "\t.def\t ";
597 Symbol->print(OS, MAI);
598 OS << ';';
599 EmitEOL();
602 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
603 OS << "\t.scl\t" << StorageClass << ';';
604 EmitEOL();
607 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
608 OS << "\t.type\t" << Type << ';';
609 EmitEOL();
612 void MCAsmStreamer::EndCOFFSymbolDef() {
613 OS << "\t.endef";
614 EmitEOL();
617 void MCAsmStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
618 OS << "\t.safeseh\t";
619 Symbol->print(OS, MAI);
620 EmitEOL();
623 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
624 OS << "\t.secidx\t";
625 Symbol->print(OS, MAI);
626 EmitEOL();
629 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {
630 OS << "\t.secrel32\t";
631 Symbol->print(OS, MAI);
632 if (Offset != 0)
633 OS << '+' << Offset;
634 EmitEOL();
637 void MCAsmStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
638 assert(MAI->hasDotTypeDotSizeDirective());
639 OS << "\t.size\t";
640 Symbol->print(OS, MAI);
641 OS << ", ";
642 Value->print(OS, MAI);
643 EmitEOL();
646 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
647 unsigned ByteAlignment) {
648 OS << "\t.comm\t";
649 Symbol->print(OS, MAI);
650 OS << ',' << Size;
652 if (ByteAlignment != 0) {
653 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
654 OS << ',' << ByteAlignment;
655 else
656 OS << ',' << Log2_32(ByteAlignment);
658 EmitEOL();
661 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
663 /// @param Symbol - The common symbol to emit.
664 /// @param Size - The size of the common symbol.
665 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
666 unsigned ByteAlign) {
667 OS << "\t.lcomm\t";
668 Symbol->print(OS, MAI);
669 OS << ',' << Size;
671 if (ByteAlign > 1) {
672 switch (MAI->getLCOMMDirectiveAlignmentType()) {
673 case LCOMM::NoAlignment:
674 llvm_unreachable("alignment not supported on .lcomm!");
675 case LCOMM::ByteAlignment:
676 OS << ',' << ByteAlign;
677 break;
678 case LCOMM::Log2Alignment:
679 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
680 OS << ',' << Log2_32(ByteAlign);
681 break;
684 EmitEOL();
687 void MCAsmStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
688 uint64_t Size, unsigned ByteAlignment) {
689 if (Symbol)
690 AssignFragment(Symbol, &Section->getDummyFragment());
692 // Note: a .zerofill directive does not switch sections.
693 OS << ".zerofill ";
695 // This is a mach-o specific directive.
696 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
697 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
699 if (Symbol) {
700 OS << ',';
701 Symbol->print(OS, MAI);
702 OS << ',' << Size;
703 if (ByteAlignment != 0)
704 OS << ',' << Log2_32(ByteAlignment);
706 EmitEOL();
709 // .tbss sym, size, align
710 // This depends that the symbol has already been mangled from the original,
711 // e.g. _a.
712 void MCAsmStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
713 uint64_t Size, unsigned ByteAlignment) {
714 AssignFragment(Symbol, &Section->getDummyFragment());
716 assert(Symbol && "Symbol shouldn't be NULL!");
717 // Instead of using the Section we'll just use the shortcut.
718 // This is a mach-o specific directive and section.
719 OS << ".tbss ";
720 Symbol->print(OS, MAI);
721 OS << ", " << Size;
723 // Output align if we have it. We default to 1 so don't bother printing
724 // that.
725 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
727 EmitEOL();
730 static inline char toOctal(int X) { return (X&7)+'0'; }
732 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
733 OS << '"';
735 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
736 unsigned char C = Data[i];
737 if (C == '"' || C == '\\') {
738 OS << '\\' << (char)C;
739 continue;
742 if (isprint((unsigned char)C)) {
743 OS << (char)C;
744 continue;
747 switch (C) {
748 case '\b': OS << "\\b"; break;
749 case '\f': OS << "\\f"; break;
750 case '\n': OS << "\\n"; break;
751 case '\r': OS << "\\r"; break;
752 case '\t': OS << "\\t"; break;
753 default:
754 OS << '\\';
755 OS << toOctal(C >> 6);
756 OS << toOctal(C >> 3);
757 OS << toOctal(C >> 0);
758 break;
762 OS << '"';
765 void MCAsmStreamer::EmitBytes(StringRef Data) {
766 assert(getCurrentSectionOnly() &&
767 "Cannot emit contents before setting section!");
768 if (Data.empty()) return;
770 if (Data.size() == 1) {
771 OS << MAI->getData8bitsDirective();
772 OS << (unsigned)(unsigned char)Data[0];
773 EmitEOL();
774 return;
777 // If the data ends with 0 and the target supports .asciz, use it, otherwise
778 // use .ascii
779 if (MAI->getAscizDirective() && Data.back() == 0) {
780 OS << MAI->getAscizDirective();
781 Data = Data.substr(0, Data.size()-1);
782 } else {
783 OS << MAI->getAsciiDirective();
786 PrintQuotedString(Data, OS);
787 EmitEOL();
790 void MCAsmStreamer::EmitBinaryData(StringRef Data) {
791 // This is binary data. Print it in a grid of hex bytes for readability.
792 const size_t Cols = 4;
793 for (size_t I = 0, EI = alignTo(Data.size(), Cols); I < EI; I += Cols) {
794 size_t J = I, EJ = std::min(I + Cols, Data.size());
795 assert(EJ > 0);
796 OS << MAI->getData8bitsDirective();
797 for (; J < EJ - 1; ++J)
798 OS << format("0x%02x", uint8_t(Data[J])) << ", ";
799 OS << format("0x%02x", uint8_t(Data[J]));
800 EmitEOL();
804 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
805 EmitValue(MCConstantExpr::create(Value, getContext()), Size);
808 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
809 SMLoc Loc) {
810 assert(Size <= 8 && "Invalid size");
811 assert(getCurrentSectionOnly() &&
812 "Cannot emit contents before setting section!");
813 const char *Directive = nullptr;
814 switch (Size) {
815 default: break;
816 case 1: Directive = MAI->getData8bitsDirective(); break;
817 case 2: Directive = MAI->getData16bitsDirective(); break;
818 case 4: Directive = MAI->getData32bitsDirective(); break;
819 case 8: Directive = MAI->getData64bitsDirective(); break;
822 if (!Directive) {
823 int64_t IntValue;
824 if (!Value->evaluateAsAbsolute(IntValue))
825 report_fatal_error("Don't know how to emit this value.");
827 // We couldn't handle the requested integer size so we fallback by breaking
828 // the request down into several, smaller, integers.
829 // Since sizes greater or equal to "Size" are invalid, we use the greatest
830 // power of 2 that is less than "Size" as our largest piece of granularity.
831 bool IsLittleEndian = MAI->isLittleEndian();
832 for (unsigned Emitted = 0; Emitted != Size;) {
833 unsigned Remaining = Size - Emitted;
834 // The size of our partial emission must be a power of two less than
835 // Size.
836 unsigned EmissionSize = PowerOf2Floor(std::min(Remaining, Size - 1));
837 // Calculate the byte offset of our partial emission taking into account
838 // the endianness of the target.
839 unsigned ByteOffset =
840 IsLittleEndian ? Emitted : (Remaining - EmissionSize);
841 uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
842 // We truncate our partial emission to fit within the bounds of the
843 // emission domain. This produces nicer output and silences potential
844 // truncation warnings when round tripping through another assembler.
845 uint64_t Shift = 64 - EmissionSize * 8;
846 assert(Shift < static_cast<uint64_t>(
847 std::numeric_limits<unsigned long long>::digits) &&
848 "undefined behavior");
849 ValueToEmit &= ~0ULL >> Shift;
850 EmitIntValue(ValueToEmit, EmissionSize);
851 Emitted += EmissionSize;
853 return;
856 assert(Directive && "Invalid size for machine code value!");
857 OS << Directive;
858 Value->print(OS, MAI);
859 EmitEOL();
862 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
863 int64_t IntValue;
864 if (Value->evaluateAsAbsolute(IntValue)) {
865 EmitULEB128IntValue(IntValue);
866 return;
868 OS << ".uleb128 ";
869 Value->print(OS, MAI);
870 EmitEOL();
873 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
874 int64_t IntValue;
875 if (Value->evaluateAsAbsolute(IntValue)) {
876 EmitSLEB128IntValue(IntValue);
877 return;
879 OS << ".sleb128 ";
880 Value->print(OS, MAI);
881 EmitEOL();
884 void MCAsmStreamer::EmitDTPRel64Value(const MCExpr *Value) {
885 assert(MAI->getDTPRel64Directive() != nullptr);
886 OS << MAI->getDTPRel64Directive();
887 Value->print(OS, MAI);
888 EmitEOL();
891 void MCAsmStreamer::EmitDTPRel32Value(const MCExpr *Value) {
892 assert(MAI->getDTPRel32Directive() != nullptr);
893 OS << MAI->getDTPRel32Directive();
894 Value->print(OS, MAI);
895 EmitEOL();
898 void MCAsmStreamer::EmitTPRel64Value(const MCExpr *Value) {
899 assert(MAI->getTPRel64Directive() != nullptr);
900 OS << MAI->getTPRel64Directive();
901 Value->print(OS, MAI);
902 EmitEOL();
905 void MCAsmStreamer::EmitTPRel32Value(const MCExpr *Value) {
906 assert(MAI->getTPRel32Directive() != nullptr);
907 OS << MAI->getTPRel32Directive();
908 Value->print(OS, MAI);
909 EmitEOL();
912 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
913 assert(MAI->getGPRel64Directive() != nullptr);
914 OS << MAI->getGPRel64Directive();
915 Value->print(OS, MAI);
916 EmitEOL();
919 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
920 assert(MAI->getGPRel32Directive() != nullptr);
921 OS << MAI->getGPRel32Directive();
922 Value->print(OS, MAI);
923 EmitEOL();
926 /// emitFill - Emit NumBytes bytes worth of the value specified by
927 /// FillValue. This implements directives such as '.space'.
928 void MCAsmStreamer::emitFill(uint64_t NumBytes, uint8_t FillValue) {
929 if (NumBytes == 0) return;
931 const MCExpr *E = MCConstantExpr::create(NumBytes, getContext());
932 emitFill(*E, FillValue);
935 void MCAsmStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
936 SMLoc Loc) {
937 if (const char *ZeroDirective = MAI->getZeroDirective()) {
938 // FIXME: Emit location directives
939 OS << ZeroDirective;
940 NumBytes.print(OS, MAI);
941 if (FillValue != 0)
942 OS << ',' << (int)FillValue;
943 EmitEOL();
944 return;
947 MCStreamer::emitFill(NumBytes, FillValue);
950 void MCAsmStreamer::emitFill(uint64_t NumValues, int64_t Size, int64_t Expr) {
951 if (NumValues == 0)
952 return;
954 const MCExpr *E = MCConstantExpr::create(NumValues, getContext());
955 emitFill(*E, Size, Expr);
958 void MCAsmStreamer::emitFill(const MCExpr &NumValues, int64_t Size,
959 int64_t Expr, SMLoc Loc) {
960 // FIXME: Emit location directives
961 OS << "\t.fill\t";
962 NumValues.print(OS, MAI);
963 OS << ", " << Size << ", 0x";
964 OS.write_hex(truncateToSize(Expr, 4));
965 EmitEOL();
968 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
969 unsigned ValueSize,
970 unsigned MaxBytesToEmit) {
971 // Some assemblers don't support non-power of two alignments, so we always
972 // emit alignments as a power of two if possible.
973 if (isPowerOf2_32(ByteAlignment)) {
974 switch (ValueSize) {
975 default:
976 llvm_unreachable("Invalid size for machine code value!");
977 case 1:
978 OS << "\t.p2align\t";
979 break;
980 case 2:
981 OS << ".p2alignw ";
982 break;
983 case 4:
984 OS << ".p2alignl ";
985 break;
986 case 8:
987 llvm_unreachable("Unsupported alignment size!");
990 OS << Log2_32(ByteAlignment);
992 if (Value || MaxBytesToEmit) {
993 OS << ", 0x";
994 OS.write_hex(truncateToSize(Value, ValueSize));
996 if (MaxBytesToEmit)
997 OS << ", " << MaxBytesToEmit;
999 EmitEOL();
1000 return;
1003 // Non-power of two alignment. This is not widely supported by assemblers.
1004 // FIXME: Parameterize this based on MAI.
1005 switch (ValueSize) {
1006 default: llvm_unreachable("Invalid size for machine code value!");
1007 case 1: OS << ".balign"; break;
1008 case 2: OS << ".balignw"; break;
1009 case 4: OS << ".balignl"; break;
1010 case 8: llvm_unreachable("Unsupported alignment size!");
1013 OS << ' ' << ByteAlignment;
1014 OS << ", " << truncateToSize(Value, ValueSize);
1015 if (MaxBytesToEmit)
1016 OS << ", " << MaxBytesToEmit;
1017 EmitEOL();
1020 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
1021 unsigned MaxBytesToEmit) {
1022 // Emit with a text fill value.
1023 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
1024 1, MaxBytesToEmit);
1027 void MCAsmStreamer::emitValueToOffset(const MCExpr *Offset,
1028 unsigned char Value,
1029 SMLoc Loc) {
1030 // FIXME: Verify that Offset is associated with the current section.
1031 OS << ".org ";
1032 Offset->print(OS, MAI);
1033 OS << ", " << (unsigned)Value;
1034 EmitEOL();
1037 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
1038 assert(MAI->hasSingleParameterDotFile());
1039 OS << "\t.file\t";
1040 PrintQuotedString(Filename, OS);
1041 EmitEOL();
1044 unsigned MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
1045 StringRef Directory,
1046 StringRef Filename,
1047 unsigned CUID) {
1048 assert(CUID == 0);
1050 MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
1051 unsigned NumFiles = Table.getMCDwarfFiles().size();
1052 FileNo = Table.getFile(Directory, Filename, FileNo);
1053 if (FileNo == 0)
1054 return 0;
1055 if (NumFiles == Table.getMCDwarfFiles().size())
1056 return FileNo;
1058 SmallString<128> FullPathName;
1060 if (!UseDwarfDirectory && !Directory.empty()) {
1061 if (sys::path::is_absolute(Filename))
1062 Directory = "";
1063 else {
1064 FullPathName = Directory;
1065 sys::path::append(FullPathName, Filename);
1066 Directory = "";
1067 Filename = FullPathName;
1071 OS << "\t.file\t" << FileNo << ' ';
1072 if (!Directory.empty()) {
1073 PrintQuotedString(Directory, OS);
1074 OS << ' ';
1076 PrintQuotedString(Filename, OS);
1077 EmitEOL();
1079 return FileNo;
1082 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
1083 unsigned Column, unsigned Flags,
1084 unsigned Isa,
1085 unsigned Discriminator,
1086 StringRef FileName) {
1087 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
1088 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
1089 OS << " basic_block";
1090 if (Flags & DWARF2_FLAG_PROLOGUE_END)
1091 OS << " prologue_end";
1092 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
1093 OS << " epilogue_begin";
1095 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
1096 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
1097 OS << " is_stmt ";
1099 if (Flags & DWARF2_FLAG_IS_STMT)
1100 OS << "1";
1101 else
1102 OS << "0";
1105 if (Isa)
1106 OS << " isa " << Isa;
1107 if (Discriminator)
1108 OS << " discriminator " << Discriminator;
1110 if (IsVerboseAsm) {
1111 OS.PadToColumn(MAI->getCommentColumn());
1112 OS << MAI->getCommentString() << ' ' << FileName << ':'
1113 << Line << ':' << Column;
1115 EmitEOL();
1116 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
1117 Isa, Discriminator, FileName);
1120 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
1121 // Always use the zeroth line table, since asm syntax only supports one line
1122 // table for now.
1123 return MCStreamer::getDwarfLineTableSymbol(0);
1126 bool MCAsmStreamer::EmitCVFileDirective(unsigned FileNo, StringRef Filename,
1127 ArrayRef<uint8_t> Checksum,
1128 unsigned ChecksumKind) {
1129 if (!getContext().getCVContext().addFile(*this, FileNo, Filename, Checksum,
1130 ChecksumKind))
1131 return false;
1133 OS << "\t.cv_file\t" << FileNo << ' ';
1134 PrintQuotedString(Filename, OS);
1136 if (!ChecksumKind) {
1137 EmitEOL();
1138 return true;
1141 OS << ' ';
1142 PrintQuotedString(toHex(Checksum), OS);
1143 OS << ' ' << ChecksumKind;
1145 EmitEOL();
1146 return true;
1149 bool MCAsmStreamer::EmitCVFuncIdDirective(unsigned FuncId) {
1150 OS << "\t.cv_func_id " << FuncId << '\n';
1151 return MCStreamer::EmitCVFuncIdDirective(FuncId);
1154 bool MCAsmStreamer::EmitCVInlineSiteIdDirective(unsigned FunctionId,
1155 unsigned IAFunc,
1156 unsigned IAFile,
1157 unsigned IALine, unsigned IACol,
1158 SMLoc Loc) {
1159 OS << "\t.cv_inline_site_id " << FunctionId << " within " << IAFunc
1160 << " inlined_at " << IAFile << ' ' << IALine << ' ' << IACol << '\n';
1161 return MCStreamer::EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
1162 IALine, IACol, Loc);
1165 void MCAsmStreamer::EmitCVLocDirective(unsigned FunctionId, unsigned FileNo,
1166 unsigned Line, unsigned Column,
1167 bool PrologueEnd, bool IsStmt,
1168 StringRef FileName, SMLoc Loc) {
1169 OS << "\t.cv_loc\t" << FunctionId << " " << FileNo << " " << Line << " "
1170 << Column;
1171 if (PrologueEnd)
1172 OS << " prologue_end";
1174 unsigned OldIsStmt = getContext().getCVContext().getCurrentCVLoc().isStmt();
1175 if (IsStmt != OldIsStmt) {
1176 OS << " is_stmt ";
1178 if (IsStmt)
1179 OS << "1";
1180 else
1181 OS << "0";
1184 if (IsVerboseAsm) {
1185 OS.PadToColumn(MAI->getCommentColumn());
1186 OS << MAI->getCommentString() << ' ' << FileName << ':' << Line << ':'
1187 << Column;
1189 EmitEOL();
1190 this->MCStreamer::EmitCVLocDirective(FunctionId, FileNo, Line, Column,
1191 PrologueEnd, IsStmt, FileName, Loc);
1194 void MCAsmStreamer::EmitCVLinetableDirective(unsigned FunctionId,
1195 const MCSymbol *FnStart,
1196 const MCSymbol *FnEnd) {
1197 OS << "\t.cv_linetable\t" << FunctionId << ", ";
1198 FnStart->print(OS, MAI);
1199 OS << ", ";
1200 FnEnd->print(OS, MAI);
1201 EmitEOL();
1202 this->MCStreamer::EmitCVLinetableDirective(FunctionId, FnStart, FnEnd);
1205 void MCAsmStreamer::EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
1206 unsigned SourceFileId,
1207 unsigned SourceLineNum,
1208 const MCSymbol *FnStartSym,
1209 const MCSymbol *FnEndSym) {
1210 OS << "\t.cv_inline_linetable\t" << PrimaryFunctionId << ' ' << SourceFileId
1211 << ' ' << SourceLineNum << ' ';
1212 FnStartSym->print(OS, MAI);
1213 OS << ' ';
1214 FnEndSym->print(OS, MAI);
1215 EmitEOL();
1216 this->MCStreamer::EmitCVInlineLinetableDirective(
1217 PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
1220 void MCAsmStreamer::EmitCVDefRangeDirective(
1221 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1222 StringRef FixedSizePortion) {
1223 OS << "\t.cv_def_range\t";
1224 for (std::pair<const MCSymbol *, const MCSymbol *> Range : Ranges) {
1225 OS << ' ';
1226 Range.first->print(OS, MAI);
1227 OS << ' ';
1228 Range.second->print(OS, MAI);
1230 OS << ", ";
1231 PrintQuotedString(FixedSizePortion, OS);
1232 EmitEOL();
1233 this->MCStreamer::EmitCVDefRangeDirective(Ranges, FixedSizePortion);
1236 void MCAsmStreamer::EmitCVStringTableDirective() {
1237 OS << "\t.cv_stringtable";
1238 EmitEOL();
1241 void MCAsmStreamer::EmitCVFileChecksumsDirective() {
1242 OS << "\t.cv_filechecksums";
1243 EmitEOL();
1246 void MCAsmStreamer::EmitCVFileChecksumOffsetDirective(unsigned FileNo) {
1247 OS << "\t.cv_filechecksumoffset\t" << FileNo;
1248 EmitEOL();
1251 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
1252 assert(MAI->hasIdentDirective() && ".ident directive not supported");
1253 OS << "\t.ident\t";
1254 PrintQuotedString(IdentString, OS);
1255 EmitEOL();
1258 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
1259 MCStreamer::EmitCFISections(EH, Debug);
1260 OS << "\t.cfi_sections ";
1261 if (EH) {
1262 OS << ".eh_frame";
1263 if (Debug)
1264 OS << ", .debug_frame";
1265 } else if (Debug) {
1266 OS << ".debug_frame";
1269 EmitEOL();
1272 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
1273 OS << "\t.cfi_startproc";
1274 if (Frame.IsSimple)
1275 OS << " simple";
1276 EmitEOL();
1279 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
1280 MCStreamer::EmitCFIEndProcImpl(Frame);
1281 OS << "\t.cfi_endproc";
1282 EmitEOL();
1285 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
1286 if (!MAI->useDwarfRegNumForCFI()) {
1287 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1288 unsigned LLVMRegister = MRI->getLLVMRegNum(Register, true);
1289 InstPrinter->printRegName(OS, LLVMRegister);
1290 } else {
1291 OS << Register;
1295 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
1296 MCStreamer::EmitCFIDefCfa(Register, Offset);
1297 OS << "\t.cfi_def_cfa ";
1298 EmitRegisterName(Register);
1299 OS << ", " << Offset;
1300 EmitEOL();
1303 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
1304 MCStreamer::EmitCFIDefCfaOffset(Offset);
1305 OS << "\t.cfi_def_cfa_offset " << Offset;
1306 EmitEOL();
1309 static void PrintCFIEscape(llvm::formatted_raw_ostream &OS, StringRef Values) {
1310 OS << "\t.cfi_escape ";
1311 if (!Values.empty()) {
1312 size_t e = Values.size() - 1;
1313 for (size_t i = 0; i < e; ++i)
1314 OS << format("0x%02x", uint8_t(Values[i])) << ", ";
1315 OS << format("0x%02x", uint8_t(Values[e]));
1319 void MCAsmStreamer::EmitCFIEscape(StringRef Values) {
1320 MCStreamer::EmitCFIEscape(Values);
1321 PrintCFIEscape(OS, Values);
1322 EmitEOL();
1325 void MCAsmStreamer::EmitCFIGnuArgsSize(int64_t Size) {
1326 MCStreamer::EmitCFIGnuArgsSize(Size);
1328 uint8_t Buffer[16] = { dwarf::DW_CFA_GNU_args_size };
1329 unsigned Len = encodeULEB128(Size, Buffer + 1) + 1;
1331 PrintCFIEscape(OS, StringRef((const char *)&Buffer[0], Len));
1332 EmitEOL();
1335 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
1336 MCStreamer::EmitCFIDefCfaRegister(Register);
1337 OS << "\t.cfi_def_cfa_register ";
1338 EmitRegisterName(Register);
1339 EmitEOL();
1342 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
1343 this->MCStreamer::EmitCFIOffset(Register, Offset);
1344 OS << "\t.cfi_offset ";
1345 EmitRegisterName(Register);
1346 OS << ", " << Offset;
1347 EmitEOL();
1350 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1351 unsigned Encoding) {
1352 MCStreamer::EmitCFIPersonality(Sym, Encoding);
1353 OS << "\t.cfi_personality " << Encoding << ", ";
1354 Sym->print(OS, MAI);
1355 EmitEOL();
1358 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1359 MCStreamer::EmitCFILsda(Sym, Encoding);
1360 OS << "\t.cfi_lsda " << Encoding << ", ";
1361 Sym->print(OS, MAI);
1362 EmitEOL();
1365 void MCAsmStreamer::EmitCFIRememberState() {
1366 MCStreamer::EmitCFIRememberState();
1367 OS << "\t.cfi_remember_state";
1368 EmitEOL();
1371 void MCAsmStreamer::EmitCFIRestoreState() {
1372 MCStreamer::EmitCFIRestoreState();
1373 OS << "\t.cfi_restore_state";
1374 EmitEOL();
1377 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1378 MCStreamer::EmitCFISameValue(Register);
1379 OS << "\t.cfi_same_value ";
1380 EmitRegisterName(Register);
1381 EmitEOL();
1384 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1385 MCStreamer::EmitCFIRelOffset(Register, Offset);
1386 OS << "\t.cfi_rel_offset ";
1387 EmitRegisterName(Register);
1388 OS << ", " << Offset;
1389 EmitEOL();
1392 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1393 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1394 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1395 EmitEOL();
1398 void MCAsmStreamer::EmitCFISignalFrame() {
1399 MCStreamer::EmitCFISignalFrame();
1400 OS << "\t.cfi_signal_frame";
1401 EmitEOL();
1404 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1405 MCStreamer::EmitCFIUndefined(Register);
1406 OS << "\t.cfi_undefined " << Register;
1407 EmitEOL();
1410 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1411 MCStreamer::EmitCFIRegister(Register1, Register2);
1412 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1413 EmitEOL();
1416 void MCAsmStreamer::EmitCFIWindowSave() {
1417 MCStreamer::EmitCFIWindowSave();
1418 OS << "\t.cfi_window_save";
1419 EmitEOL();
1422 void MCAsmStreamer::EmitCFIReturnColumn(int64_t Register) {
1423 MCStreamer::EmitCFIReturnColumn(Register);
1424 OS << "\t.cfi_return_column " << Register;
1425 EmitEOL();
1428 void MCAsmStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol) {
1429 MCStreamer::EmitWinCFIStartProc(Symbol);
1431 OS << ".seh_proc ";
1432 Symbol->print(OS, MAI);
1433 EmitEOL();
1436 void MCAsmStreamer::EmitWinCFIEndProc() {
1437 MCStreamer::EmitWinCFIEndProc();
1439 OS << "\t.seh_endproc";
1440 EmitEOL();
1443 void MCAsmStreamer::EmitWinCFIStartChained() {
1444 MCStreamer::EmitWinCFIStartChained();
1446 OS << "\t.seh_startchained";
1447 EmitEOL();
1450 void MCAsmStreamer::EmitWinCFIEndChained() {
1451 MCStreamer::EmitWinCFIEndChained();
1453 OS << "\t.seh_endchained";
1454 EmitEOL();
1457 void MCAsmStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind,
1458 bool Except) {
1459 MCStreamer::EmitWinEHHandler(Sym, Unwind, Except);
1461 OS << "\t.seh_handler ";
1462 Sym->print(OS, MAI);
1463 if (Unwind)
1464 OS << ", @unwind";
1465 if (Except)
1466 OS << ", @except";
1467 EmitEOL();
1470 void MCAsmStreamer::EmitWinEHHandlerData() {
1471 MCStreamer::EmitWinEHHandlerData();
1473 // Switch sections. Don't call SwitchSection directly, because that will
1474 // cause the section switch to be visible in the emitted assembly.
1475 // We only do this so the section switch that terminates the handler
1476 // data block is visible.
1477 WinEH::FrameInfo *CurFrame = getCurrentWinFrameInfo();
1478 MCSection *TextSec = &CurFrame->Function->getSection();
1479 MCSection *XData = getAssociatedXDataSection(TextSec);
1480 SwitchSectionNoChange(XData);
1482 OS << "\t.seh_handlerdata";
1483 EmitEOL();
1486 void MCAsmStreamer::EmitWinCFIPushReg(unsigned Register) {
1487 MCStreamer::EmitWinCFIPushReg(Register);
1489 OS << "\t.seh_pushreg " << Register;
1490 EmitEOL();
1493 void MCAsmStreamer::EmitWinCFISetFrame(unsigned Register, unsigned Offset) {
1494 MCStreamer::EmitWinCFISetFrame(Register, Offset);
1496 OS << "\t.seh_setframe " << Register << ", " << Offset;
1497 EmitEOL();
1500 void MCAsmStreamer::EmitWinCFIAllocStack(unsigned Size) {
1501 MCStreamer::EmitWinCFIAllocStack(Size);
1503 OS << "\t.seh_stackalloc " << Size;
1504 EmitEOL();
1507 void MCAsmStreamer::EmitWinCFISaveReg(unsigned Register, unsigned Offset) {
1508 MCStreamer::EmitWinCFISaveReg(Register, Offset);
1510 OS << "\t.seh_savereg " << Register << ", " << Offset;
1511 EmitEOL();
1514 void MCAsmStreamer::EmitWinCFISaveXMM(unsigned Register, unsigned Offset) {
1515 MCStreamer::EmitWinCFISaveXMM(Register, Offset);
1517 OS << "\t.seh_savexmm " << Register << ", " << Offset;
1518 EmitEOL();
1521 void MCAsmStreamer::EmitWinCFIPushFrame(bool Code) {
1522 MCStreamer::EmitWinCFIPushFrame(Code);
1524 OS << "\t.seh_pushframe";
1525 if (Code)
1526 OS << " @code";
1527 EmitEOL();
1530 void MCAsmStreamer::EmitWinCFIEndProlog() {
1531 MCStreamer::EmitWinCFIEndProlog();
1533 OS << "\t.seh_endprologue";
1534 EmitEOL();
1537 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1538 const MCSubtargetInfo &STI,
1539 bool PrintSchedInfo) {
1540 raw_ostream &OS = GetCommentOS();
1541 SmallString<256> Code;
1542 SmallVector<MCFixup, 4> Fixups;
1543 raw_svector_ostream VecOS(Code);
1544 Emitter->encodeInstruction(Inst, VecOS, Fixups, STI);
1546 // If we are showing fixups, create symbolic markers in the encoded
1547 // representation. We do this by making a per-bit map to the fixup item index,
1548 // then trying to display it as nicely as possible.
1549 SmallVector<uint8_t, 64> FixupMap;
1550 FixupMap.resize(Code.size() * 8);
1551 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1552 FixupMap[i] = 0;
1554 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1555 MCFixup &F = Fixups[i];
1556 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1557 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1558 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1559 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1560 FixupMap[Index] = 1 + i;
1564 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1565 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1566 OS << "encoding: [";
1567 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1568 if (i)
1569 OS << ',';
1571 // See if all bits are the same map entry.
1572 uint8_t MapEntry = FixupMap[i * 8 + 0];
1573 for (unsigned j = 1; j != 8; ++j) {
1574 if (FixupMap[i * 8 + j] == MapEntry)
1575 continue;
1577 MapEntry = uint8_t(~0U);
1578 break;
1581 if (MapEntry != uint8_t(~0U)) {
1582 if (MapEntry == 0) {
1583 OS << format("0x%02x", uint8_t(Code[i]));
1584 } else {
1585 if (Code[i]) {
1586 // FIXME: Some of the 8 bits require fix up.
1587 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1588 << char('A' + MapEntry - 1) << '\'';
1589 } else
1590 OS << char('A' + MapEntry - 1);
1592 } else {
1593 // Otherwise, write out in binary.
1594 OS << "0b";
1595 for (unsigned j = 8; j--;) {
1596 unsigned Bit = (Code[i] >> j) & 1;
1598 unsigned FixupBit;
1599 if (MAI->isLittleEndian())
1600 FixupBit = i * 8 + j;
1601 else
1602 FixupBit = i * 8 + (7-j);
1604 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1605 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1606 OS << char('A' + MapEntry - 1);
1607 } else
1608 OS << Bit;
1612 OS << "]";
1613 // If we are not going to add fixup or schedule comments after this point
1614 // then we have to end the current comment line with "\n".
1615 if (Fixups.size() || !PrintSchedInfo)
1616 OS << "\n";
1618 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1619 MCFixup &F = Fixups[i];
1620 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1621 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1622 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1626 void MCAsmStreamer::EmitInstruction(const MCInst &Inst,
1627 const MCSubtargetInfo &STI,
1628 bool PrintSchedInfo) {
1629 assert(getCurrentSectionOnly() &&
1630 "Cannot emit contents before setting section!");
1632 // Show the encoding in a comment if we have a code emitter.
1633 if (Emitter)
1634 AddEncodingComment(Inst, STI, PrintSchedInfo);
1636 // Show the MCInst if enabled.
1637 if (ShowInst) {
1638 if (PrintSchedInfo)
1639 GetCommentOS() << "\n";
1640 Inst.dump_pretty(GetCommentOS(), InstPrinter.get(), "\n ");
1641 GetCommentOS() << "\n";
1644 if(getTargetStreamer())
1645 getTargetStreamer()->prettyPrintAsm(*InstPrinter, OS, Inst, STI);
1646 else
1647 InstPrinter->printInst(&Inst, OS, "", STI);
1649 if (PrintSchedInfo) {
1650 std::string SI = STI.getSchedInfoStr(Inst);
1651 if (!SI.empty())
1652 GetCommentOS() << SI;
1655 StringRef Comments = CommentToEmit;
1656 if (Comments.size() && Comments.back() != '\n')
1657 GetCommentOS() << "\n";
1659 EmitEOL();
1662 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1663 OS << "\t.bundle_align_mode " << AlignPow2;
1664 EmitEOL();
1667 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1668 OS << "\t.bundle_lock";
1669 if (AlignToEnd)
1670 OS << " align_to_end";
1671 EmitEOL();
1674 void MCAsmStreamer::EmitBundleUnlock() {
1675 OS << "\t.bundle_unlock";
1676 EmitEOL();
1679 bool MCAsmStreamer::EmitRelocDirective(const MCExpr &Offset, StringRef Name,
1680 const MCExpr *Expr, SMLoc) {
1681 OS << "\t.reloc ";
1682 Offset.print(OS, MAI);
1683 OS << ", " << Name;
1684 if (Expr) {
1685 OS << ", ";
1686 Expr->print(OS, MAI);
1688 EmitEOL();
1689 return false;
1692 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1693 /// the specified string in the output .s file. This capability is
1694 /// indicated by the hasRawTextSupport() predicate.
1695 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1696 if (!String.empty() && String.back() == '\n')
1697 String = String.substr(0, String.size()-1);
1698 OS << String;
1699 EmitEOL();
1702 void MCAsmStreamer::FinishImpl() {
1703 // If we are generating dwarf for assembly source files dump out the sections.
1704 if (getContext().getGenDwarfForAssembly())
1705 MCGenDwarfInfo::Emit(this);
1707 // Emit the label for the line table, if requested - since the rest of the
1708 // line table will be defined by .loc/.file directives, and not emitted
1709 // directly, the label is the only work required here.
1710 auto &Tables = getContext().getMCDwarfLineTables();
1711 if (!Tables.empty()) {
1712 assert(Tables.size() == 1 && "asm output only supports one line table");
1713 if (auto *Label = Tables.begin()->second.getLabel()) {
1714 SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
1715 EmitLabel(Label);
1720 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1721 std::unique_ptr<formatted_raw_ostream> OS,
1722 bool isVerboseAsm, bool useDwarfDirectory,
1723 MCInstPrinter *IP, MCCodeEmitter *CE,
1724 MCAsmBackend *MAB, bool ShowInst) {
1725 return new MCAsmStreamer(Context, std::move(OS), isVerboseAsm,
1726 useDwarfDirectory, IP, CE, MAB, ShowInst);