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 //===----------------------------------------------------------------------===//
8 
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/DebugInfo/CodeView/SymbolRecord.h"
15 #include "llvm/MC/MCAsmBackend.h"
16 #include "llvm/MC/MCAsmInfo.h"
17 #include "llvm/MC/MCAssembler.h"
18 #include "llvm/MC/MCCodeEmitter.h"
19 #include "llvm/MC/MCCodeView.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCFixupKindInfo.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstPrinter.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCObjectWriter.h"
27 #include "llvm/MC/MCRegister.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSectionMachO.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/Format.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/LEB128.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include <cctype>
39 
40 using namespace llvm;
41 
42 namespace {
43 
44 class MCAsmStreamer final : public MCStreamer {
45   std::unique_ptr<formatted_raw_ostream> OSOwner;
46   formatted_raw_ostream &OS;
47   const MCAsmInfo *MAI;
48   std::unique_ptr<MCInstPrinter> InstPrinter;
49   std::unique_ptr<MCAssembler> Assembler;
50 
51   SmallString<128> ExplicitCommentToEmit;
52   SmallString<128> CommentToEmit;
53   raw_svector_ostream CommentStream;
54   raw_null_ostream NullStream;
55 
56   unsigned IsVerboseAsm : 1;
57   unsigned ShowInst : 1;
58   unsigned UseDwarfDirectory : 1;
59 
60   void EmitRegisterName(int64_t Register);
61   void emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
62   void emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
63 
64 public:
65   MCAsmStreamer(MCContext &Context, std::unique_ptr<formatted_raw_ostream> os,
66                 bool isVerboseAsm, bool useDwarfDirectory,
67                 MCInstPrinter *printer, std::unique_ptr<MCCodeEmitter> emitter,
68                 std::unique_ptr<MCAsmBackend> asmbackend, bool showInst)
69       : MCStreamer(Context), OSOwner(std::move(os)), OS(*OSOwner),
70         MAI(Context.getAsmInfo()), InstPrinter(printer),
71         Assembler(std::make_unique<MCAssembler>(
72             Context, std::move(asmbackend), std::move(emitter),
73             (asmbackend) ? asmbackend->createObjectWriter(NullStream)
74                          : nullptr)),
75         CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
76         ShowInst(showInst), UseDwarfDirectory(useDwarfDirectory) {
77     assert(InstPrinter);
78     if (IsVerboseAsm)
79         InstPrinter->setCommentStream(CommentStream);
80     if (Assembler->getBackendPtr())
81       setAllowAutoPadding(Assembler->getBackend().allowAutoPadding());
82 
83     Context.setUseNamesOnTempLabels(true);
84   }
85 
86   MCAssembler &getAssembler() { return *Assembler; }
87   MCAssembler *getAssemblerPtr() override { return nullptr; }
88 
89   inline void EmitEOL() {
90     // Dump Explicit Comments here.
91     emitExplicitComments();
92     // If we don't have any comments, just emit a \n.
93     if (!IsVerboseAsm) {
94       OS << '\n';
95       return;
96     }
97     EmitCommentsAndEOL();
98   }
99 
100   void emitSyntaxDirective() override;
101 
102   void EmitCommentsAndEOL();
103 
104   /// Return true if this streamer supports verbose assembly at all.
105   bool isVerboseAsm() const override { return IsVerboseAsm; }
106 
107   /// Do we support EmitRawText?
108   bool hasRawTextSupport() const override { return true; }
109 
110   /// Add a comment that can be emitted to the generated .s file to make the
111   /// output of the compiler more readable. This only affects the MCAsmStreamer
112   /// and only when verbose assembly output is enabled.
113   void AddComment(const Twine &T, bool EOL = true) override;
114 
115   /// Add a comment showing the encoding of an instruction.
116   void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &);
117 
118   /// Return a raw_ostream that comments can be written to.
119   /// Unlike AddComment, you are required to terminate comments with \n if you
120   /// use this method.
121   raw_ostream &GetCommentOS() override {
122     if (!IsVerboseAsm)
123       return nulls();  // Discard comments unless in verbose asm mode.
124     return CommentStream;
125   }
126 
127   void emitRawComment(const Twine &T, bool TabPrefix = true) override;
128 
129   void addExplicitComment(const Twine &T) override;
130   void emitExplicitComments() override;
131 
132   /// Emit a blank line to a .s file to pretty it up.
133   void AddBlankLine() override {
134     EmitEOL();
135   }
136 
137   /// @name MCStreamer Interface
138   /// @{
139 
140   void changeSection(MCSection *Section, const MCExpr *Subsection) override;
141 
142   void emitELFSymverDirective(StringRef AliasName,
143                               const MCSymbol *Aliasee) override;
144 
145   void emitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override;
146   void emitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc()) override;
147 
148   void emitAssemblerFlag(MCAssemblerFlag Flag) override;
149   void emitLinkerOptions(ArrayRef<std::string> Options) override;
150   void emitDataRegion(MCDataRegionType Kind) override;
151   void emitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
152                       unsigned Update, VersionTuple SDKVersion) override;
153   void emitBuildVersion(unsigned Platform, unsigned Major, unsigned Minor,
154                         unsigned Update, VersionTuple SDKVersion) override;
155   void emitThumbFunc(MCSymbol *Func) override;
156 
157   void emitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
158   void emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
159   bool emitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
160 
161   void emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
162   void BeginCOFFSymbolDef(const MCSymbol *Symbol) override;
163   void EmitCOFFSymbolStorageClass(int StorageClass) override;
164   void EmitCOFFSymbolType(int Type) override;
165   void EndCOFFSymbolDef() override;
166   void EmitCOFFSafeSEH(MCSymbol const *Symbol) override;
167   void EmitCOFFSymbolIndex(MCSymbol const *Symbol) override;
168   void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
169   void EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) override;
170   void EmitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) override;
171   void emitXCOFFLocalCommonSymbol(MCSymbol *LabelSym, uint64_t Size,
172                                   MCSymbol *CsectSym,
173                                   unsigned ByteAlign) override;
174   void emitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
175   void emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
176                         unsigned ByteAlignment) override;
177 
178   /// Emit a local common (.lcomm) symbol.
179   ///
180   /// @param Symbol - The common symbol to emit.
181   /// @param Size - The size of the common symbol.
182   /// @param ByteAlignment - The alignment of the common symbol in bytes.
183   void emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
184                              unsigned ByteAlignment) override;
185 
186   void emitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
187                     uint64_t Size = 0, unsigned ByteAlignment = 0,
188                     SMLoc Loc = SMLoc()) override;
189 
190   void emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
191                       unsigned ByteAlignment = 0) override;
192 
193   void emitBinaryData(StringRef Data) override;
194 
195   void emitBytes(StringRef Data) override;
196 
197   void emitValueImpl(const MCExpr *Value, unsigned Size,
198                      SMLoc Loc = SMLoc()) override;
199   void emitIntValue(uint64_t Value, unsigned Size) override;
200   void emitIntValueInHex(uint64_t Value, unsigned Size) override;
201   void emitIntValueInHexWithPadding(uint64_t Value, unsigned Size) override;
202 
203   void emitULEB128Value(const MCExpr *Value) override;
204 
205   void emitSLEB128Value(const MCExpr *Value) override;
206 
207   void emitDTPRel32Value(const MCExpr *Value) override;
208   void emitDTPRel64Value(const MCExpr *Value) override;
209   void emitTPRel32Value(const MCExpr *Value) override;
210   void emitTPRel64Value(const MCExpr *Value) override;
211 
212   void emitGPRel64Value(const MCExpr *Value) override;
213 
214   void emitGPRel32Value(const MCExpr *Value) override;
215 
216   void emitFill(const MCExpr &NumBytes, uint64_t FillValue,
217                 SMLoc Loc = SMLoc()) override;
218 
219   void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
220                 SMLoc Loc = SMLoc()) override;
221 
222   void emitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
223                             unsigned ValueSize = 1,
224                             unsigned MaxBytesToEmit = 0) override;
225 
226   void emitCodeAlignment(unsigned ByteAlignment,
227                          unsigned MaxBytesToEmit = 0) override;
228 
229   void emitValueToOffset(const MCExpr *Offset,
230                          unsigned char Value,
231                          SMLoc Loc) override;
232 
233   void emitFileDirective(StringRef Filename) override;
234   Expected<unsigned> tryEmitDwarfFileDirective(unsigned FileNo,
235                                                StringRef Directory,
236                                                StringRef Filename,
237                                                Optional<MD5::MD5Result> Checksum = None,
238                                                Optional<StringRef> Source = None,
239                                                unsigned CUID = 0) override;
240   void emitDwarfFile0Directive(StringRef Directory, StringRef Filename,
241                                Optional<MD5::MD5Result> Checksum,
242                                Optional<StringRef> Source,
243                                unsigned CUID = 0) override;
244   void emitDwarfLocDirective(unsigned FileNo, unsigned Line, unsigned Column,
245                              unsigned Flags, unsigned Isa,
246                              unsigned Discriminator,
247                              StringRef FileName) override;
248   MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
249 
250   bool EmitCVFileDirective(unsigned FileNo, StringRef Filename,
251                            ArrayRef<uint8_t> Checksum,
252                            unsigned ChecksumKind) override;
253   bool EmitCVFuncIdDirective(unsigned FuncId) override;
254   bool EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc,
255                                    unsigned IAFile, unsigned IALine,
256                                    unsigned IACol, SMLoc Loc) override;
257   void emitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line,
258                           unsigned Column, bool PrologueEnd, bool IsStmt,
259                           StringRef FileName, SMLoc Loc) override;
260   void emitCVLinetableDirective(unsigned FunctionId, const MCSymbol *FnStart,
261                                 const MCSymbol *FnEnd) override;
262   void emitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
263                                       unsigned SourceFileId,
264                                       unsigned SourceLineNum,
265                                       const MCSymbol *FnStartSym,
266                                       const MCSymbol *FnEndSym) override;
267 
268   void PrintCVDefRangePrefix(
269       ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges);
270 
271   void emitCVDefRangeDirective(
272       ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
273       codeview::DefRangeRegisterRelHeader DRHdr) override;
274 
275   void emitCVDefRangeDirective(
276       ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
277       codeview::DefRangeSubfieldRegisterHeader DRHdr) override;
278 
279   void emitCVDefRangeDirective(
280       ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
281       codeview::DefRangeRegisterHeader DRHdr) override;
282 
283   void emitCVDefRangeDirective(
284       ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
285       codeview::DefRangeFramePointerRelHeader DRHdr) override;
286 
287   void emitCVStringTableDirective() override;
288   void emitCVFileChecksumsDirective() override;
289   void emitCVFileChecksumOffsetDirective(unsigned FileNo) override;
290   void EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) override;
291 
292   void emitIdent(StringRef IdentString) override;
293   void emitCFIBKeyFrame() override;
294   void emitCFISections(bool EH, bool Debug) override;
295   void emitCFIDefCfa(int64_t Register, int64_t Offset) override;
296   void emitCFIDefCfaOffset(int64_t Offset) override;
297   void emitCFIDefCfaRegister(int64_t Register) override;
298   void emitCFIOffset(int64_t Register, int64_t Offset) override;
299   void emitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
300   void emitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
301   void emitCFIRememberState() override;
302   void emitCFIRestoreState() override;
303   void emitCFIRestore(int64_t Register) override;
304   void emitCFISameValue(int64_t Register) override;
305   void emitCFIRelOffset(int64_t Register, int64_t Offset) override;
306   void emitCFIAdjustCfaOffset(int64_t Adjustment) override;
307   void emitCFIEscape(StringRef Values) override;
308   void emitCFIGnuArgsSize(int64_t Size) override;
309   void emitCFISignalFrame() override;
310   void emitCFIUndefined(int64_t Register) override;
311   void emitCFIRegister(int64_t Register1, int64_t Register2) override;
312   void emitCFIWindowSave() override;
313   void emitCFINegateRAState() override;
314   void emitCFIReturnColumn(int64_t Register) override;
315 
316   void EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) override;
317   void EmitWinCFIEndProc(SMLoc Loc) override;
318   void EmitWinCFIFuncletOrFuncEnd(SMLoc Loc) override;
319   void EmitWinCFIStartChained(SMLoc Loc) override;
320   void EmitWinCFIEndChained(SMLoc Loc) override;
321   void EmitWinCFIPushReg(MCRegister Register, SMLoc Loc) override;
322   void EmitWinCFISetFrame(MCRegister Register, unsigned Offset,
323                           SMLoc Loc) override;
324   void EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) override;
325   void EmitWinCFISaveReg(MCRegister Register, unsigned Offset,
326                          SMLoc Loc) override;
327   void EmitWinCFISaveXMM(MCRegister Register, unsigned Offset,
328                          SMLoc Loc) override;
329   void EmitWinCFIPushFrame(bool Code, SMLoc Loc) override;
330   void EmitWinCFIEndProlog(SMLoc Loc) override;
331 
332   void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
333                         SMLoc Loc) override;
334   void EmitWinEHHandlerData(SMLoc Loc) override;
335 
336   void emitCGProfileEntry(const MCSymbolRefExpr *From,
337                           const MCSymbolRefExpr *To, uint64_t Count) override;
338 
339   void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override;
340 
341   void emitBundleAlignMode(unsigned AlignPow2) override;
342   void emitBundleLock(bool AlignToEnd) override;
343   void emitBundleUnlock() override;
344 
345   bool emitRelocDirective(const MCExpr &Offset, StringRef Name,
346                           const MCExpr *Expr, SMLoc Loc,
347                           const MCSubtargetInfo &STI) override;
348 
349   void emitAddrsig() override;
350   void emitAddrsigSym(const MCSymbol *Sym) override;
351 
352   /// If this file is backed by an assembly streamer, this dumps the specified
353   /// string in the output .s file. This capability is indicated by the
354   /// hasRawTextSupport() predicate.
355   void emitRawTextImpl(StringRef String) override;
356 
357   void finishImpl() override;
358 };
359 
360 } // end anonymous namespace.
361 
362 void MCAsmStreamer::AddComment(const Twine &T, bool EOL) {
363   if (!IsVerboseAsm) return;
364 
365   T.toVector(CommentToEmit);
366 
367   if (EOL)
368     CommentToEmit.push_back('\n'); // Place comment in a new line.
369 }
370 
371 void MCAsmStreamer::EmitCommentsAndEOL() {
372   if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
373     OS << '\n';
374     return;
375   }
376 
377   StringRef Comments = CommentToEmit;
378 
379   assert(Comments.back() == '\n' &&
380          "Comment array not newline terminated");
381   do {
382     // Emit a line of comments.
383     OS.PadToColumn(MAI->getCommentColumn());
384     size_t Position = Comments.find('\n');
385     OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
386 
387     Comments = Comments.substr(Position+1);
388   } while (!Comments.empty());
389 
390   CommentToEmit.clear();
391 }
392 
393 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
394   assert(Bytes > 0 && Bytes <= 8 && "Invalid size!");
395   return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
396 }
397 
398 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
399   if (TabPrefix)
400     OS << '\t';
401   OS << MAI->getCommentString() << T;
402   EmitEOL();
403 }
404 
405 void MCAsmStreamer::addExplicitComment(const Twine &T) {
406   StringRef c = T.getSingleStringRef();
407   if (c.equals(StringRef(MAI->getSeparatorString())))
408     return;
409   if (c.startswith(StringRef("//"))) {
410     ExplicitCommentToEmit.append("\t");
411     ExplicitCommentToEmit.append(MAI->getCommentString());
412     // drop //
413     ExplicitCommentToEmit.append(c.slice(2, c.size()).str());
414   } else if (c.startswith(StringRef("/*"))) {
415     size_t p = 2, len = c.size() - 2;
416     // emit each line in comment as separate newline.
417     do {
418       size_t newp = std::min(len, c.find_first_of("\r\n", p));
419       ExplicitCommentToEmit.append("\t");
420       ExplicitCommentToEmit.append(MAI->getCommentString());
421       ExplicitCommentToEmit.append(c.slice(p, newp).str());
422       // If we have another line in this comment add line
423       if (newp < len)
424         ExplicitCommentToEmit.append("\n");
425       p = newp + 1;
426     } while (p < len);
427   } else if (c.startswith(StringRef(MAI->getCommentString()))) {
428     ExplicitCommentToEmit.append("\t");
429     ExplicitCommentToEmit.append(c.str());
430   } else if (c.front() == '#') {
431 
432     ExplicitCommentToEmit.append("\t");
433     ExplicitCommentToEmit.append(MAI->getCommentString());
434     ExplicitCommentToEmit.append(c.slice(1, c.size()).str());
435   } else
436     assert(false && "Unexpected Assembly Comment");
437   // full line comments immediately output
438   if (c.back() == '\n')
439     emitExplicitComments();
440 }
441 
442 void MCAsmStreamer::emitExplicitComments() {
443   StringRef Comments = ExplicitCommentToEmit;
444   if (!Comments.empty())
445     OS << Comments;
446   ExplicitCommentToEmit.clear();
447 }
448 
449 void MCAsmStreamer::changeSection(MCSection *Section,
450                                   const MCExpr *Subsection) {
451   assert(Section && "Cannot switch to a null section!");
452   if (MCTargetStreamer *TS = getTargetStreamer()) {
453     TS->changeSection(getCurrentSectionOnly(), Section, Subsection, OS);
454   } else {
455     Section->PrintSwitchToSection(
456         *MAI, getContext().getObjectFileInfo()->getTargetTriple(), OS,
457         Subsection);
458   }
459 }
460 
461 void MCAsmStreamer::emitELFSymverDirective(StringRef AliasName,
462                                            const MCSymbol *Aliasee) {
463   OS << ".symver ";
464   Aliasee->print(OS, MAI);
465   OS << ", " << AliasName;
466   EmitEOL();
467 }
468 
469 void MCAsmStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) {
470   MCStreamer::emitLabel(Symbol, Loc);
471 
472   Symbol->print(OS, MAI);
473   OS << MAI->getLabelSuffix();
474 
475   EmitEOL();
476 }
477 
478 void MCAsmStreamer::emitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
479   StringRef str = MCLOHIdToName(Kind);
480 
481 #ifndef NDEBUG
482   int NbArgs = MCLOHIdToNbArgs(Kind);
483   assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
484   assert(str != "" && "Invalid LOH name");
485 #endif
486 
487   OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
488   bool IsFirst = true;
489   for (const MCSymbol *Arg : Args) {
490     if (!IsFirst)
491       OS << ", ";
492     IsFirst = false;
493     Arg->print(OS, MAI);
494   }
495   EmitEOL();
496 }
497 
498 void MCAsmStreamer::emitAssemblerFlag(MCAssemblerFlag Flag) {
499   switch (Flag) {
500   case MCAF_SyntaxUnified:         OS << "\t.syntax unified"; break;
501   case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
502   case MCAF_Code16:                OS << '\t'<< MAI->getCode16Directive();break;
503   case MCAF_Code32:                OS << '\t'<< MAI->getCode32Directive();break;
504   case MCAF_Code64:                OS << '\t'<< MAI->getCode64Directive();break;
505   }
506   EmitEOL();
507 }
508 
509 void MCAsmStreamer::emitLinkerOptions(ArrayRef<std::string> Options) {
510   assert(!Options.empty() && "At least one option is required!");
511   OS << "\t.linker_option \"" << Options[0] << '"';
512   for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
513          ie = Options.end(); it != ie; ++it) {
514     OS << ", " << '"' << *it << '"';
515   }
516   EmitEOL();
517 }
518 
519 void MCAsmStreamer::emitDataRegion(MCDataRegionType Kind) {
520   if (!MAI->doesSupportDataRegionDirectives())
521     return;
522   switch (Kind) {
523   case MCDR_DataRegion:            OS << "\t.data_region"; break;
524   case MCDR_DataRegionJT8:         OS << "\t.data_region jt8"; break;
525   case MCDR_DataRegionJT16:        OS << "\t.data_region jt16"; break;
526   case MCDR_DataRegionJT32:        OS << "\t.data_region jt32"; break;
527   case MCDR_DataRegionEnd:         OS << "\t.end_data_region"; break;
528   }
529   EmitEOL();
530 }
531 
532 static const char *getVersionMinDirective(MCVersionMinType Type) {
533   switch (Type) {
534   case MCVM_WatchOSVersionMin: return ".watchos_version_min";
535   case MCVM_TvOSVersionMin:    return ".tvos_version_min";
536   case MCVM_IOSVersionMin:     return ".ios_version_min";
537   case MCVM_OSXVersionMin:     return ".macosx_version_min";
538   }
539   llvm_unreachable("Invalid MC version min type");
540 }
541 
542 static void EmitSDKVersionSuffix(raw_ostream &OS,
543                                  const VersionTuple &SDKVersion) {
544   if (SDKVersion.empty())
545     return;
546   OS << '\t' << "sdk_version " << SDKVersion.getMajor();
547   if (auto Minor = SDKVersion.getMinor()) {
548     OS << ", " << *Minor;
549     if (auto Subminor = SDKVersion.getSubminor()) {
550       OS << ", " << *Subminor;
551     }
552   }
553 }
554 
555 void MCAsmStreamer::emitVersionMin(MCVersionMinType Type, unsigned Major,
556                                    unsigned Minor, unsigned Update,
557                                    VersionTuple SDKVersion) {
558   OS << '\t' << getVersionMinDirective(Type) << ' ' << Major << ", " << Minor;
559   if (Update)
560     OS << ", " << Update;
561   EmitSDKVersionSuffix(OS, SDKVersion);
562   EmitEOL();
563 }
564 
565 static const char *getPlatformName(MachO::PlatformType Type) {
566   switch (Type) {
567   case MachO::PLATFORM_MACOS:            return "macos";
568   case MachO::PLATFORM_IOS:              return "ios";
569   case MachO::PLATFORM_TVOS:             return "tvos";
570   case MachO::PLATFORM_WATCHOS:          return "watchos";
571   case MachO::PLATFORM_BRIDGEOS:         return "bridgeos";
572   case MachO::PLATFORM_MACCATALYST:      return "macCatalyst";
573   case MachO::PLATFORM_IOSSIMULATOR:     return "iossimulator";
574   case MachO::PLATFORM_TVOSSIMULATOR:    return "tvossimulator";
575   case MachO::PLATFORM_WATCHOSSIMULATOR: return "watchossimulator";
576   }
577   llvm_unreachable("Invalid Mach-O platform type");
578 }
579 
580 void MCAsmStreamer::emitBuildVersion(unsigned Platform, unsigned Major,
581                                      unsigned Minor, unsigned Update,
582                                      VersionTuple SDKVersion) {
583   const char *PlatformName = getPlatformName((MachO::PlatformType)Platform);
584   OS << "\t.build_version " << PlatformName << ", " << Major << ", " << Minor;
585   if (Update)
586     OS << ", " << Update;
587   EmitSDKVersionSuffix(OS, SDKVersion);
588   EmitEOL();
589 }
590 
591 void MCAsmStreamer::emitThumbFunc(MCSymbol *Func) {
592   // This needs to emit to a temporary string to get properly quoted
593   // MCSymbols when they have spaces in them.
594   OS << "\t.thumb_func";
595   // Only Mach-O hasSubsectionsViaSymbols()
596   if (MAI->hasSubsectionsViaSymbols()) {
597     OS << '\t';
598     Func->print(OS, MAI);
599   }
600   EmitEOL();
601 }
602 
603 void MCAsmStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
604   // Do not emit a .set on inlined target assignments.
605   bool EmitSet = true;
606   if (auto *E = dyn_cast<MCTargetExpr>(Value))
607     if (E->inlineAssignedExpr())
608       EmitSet = false;
609   if (EmitSet) {
610     OS << ".set ";
611     Symbol->print(OS, MAI);
612     OS << ", ";
613     Value->print(OS, MAI);
614 
615     EmitEOL();
616   }
617 
618   MCStreamer::emitAssignment(Symbol, Value);
619 }
620 
621 void MCAsmStreamer::emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
622   OS << ".weakref ";
623   Alias->print(OS, MAI);
624   OS << ", ";
625   Symbol->print(OS, MAI);
626   EmitEOL();
627 }
628 
629 bool MCAsmStreamer::emitSymbolAttribute(MCSymbol *Symbol,
630                                         MCSymbolAttr Attribute) {
631   switch (Attribute) {
632   case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
633   case MCSA_ELF_TypeFunction:    /// .type _foo, STT_FUNC  # aka @function
634   case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
635   case MCSA_ELF_TypeObject:      /// .type _foo, STT_OBJECT  # aka @object
636   case MCSA_ELF_TypeTLS:         /// .type _foo, STT_TLS     # aka @tls_object
637   case MCSA_ELF_TypeCommon:      /// .type _foo, STT_COMMON  # aka @common
638   case MCSA_ELF_TypeNoType:      /// .type _foo, STT_NOTYPE  # aka @notype
639   case MCSA_ELF_TypeGnuUniqueObject:  /// .type _foo, @gnu_unique_object
640     if (!MAI->hasDotTypeDotSizeDirective())
641       return false; // Symbol attribute not supported
642     OS << "\t.type\t";
643     Symbol->print(OS, MAI);
644     OS << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
645     switch (Attribute) {
646     default: return false;
647     case MCSA_ELF_TypeFunction:    OS << "function"; break;
648     case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
649     case MCSA_ELF_TypeObject:      OS << "object"; break;
650     case MCSA_ELF_TypeTLS:         OS << "tls_object"; break;
651     case MCSA_ELF_TypeCommon:      OS << "common"; break;
652     case MCSA_ELF_TypeNoType:      OS << "notype"; break;
653     case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
654     }
655     EmitEOL();
656     return true;
657   case MCSA_Global: // .globl/.global
658     OS << MAI->getGlobalDirective();
659     break;
660   case MCSA_LGlobal:        OS << "\t.lglobl\t";          break;
661   case MCSA_Hidden:         OS << "\t.hidden\t";          break;
662   case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
663   case MCSA_Internal:       OS << "\t.internal\t";        break;
664   case MCSA_LazyReference:  OS << "\t.lazy_reference\t";  break;
665   case MCSA_Local:          OS << "\t.local\t";           break;
666   case MCSA_NoDeadStrip:
667     if (!MAI->hasNoDeadStrip())
668       return false;
669     OS << "\t.no_dead_strip\t";
670     break;
671   case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
672   case MCSA_AltEntry:       OS << "\t.alt_entry\t";       break;
673   case MCSA_PrivateExtern:
674     OS << "\t.private_extern\t";
675     break;
676   case MCSA_Protected:      OS << "\t.protected\t";       break;
677   case MCSA_Reference:      OS << "\t.reference\t";       break;
678   case MCSA_Weak:           OS << MAI->getWeakDirective(); break;
679   case MCSA_WeakDefinition:
680     OS << "\t.weak_definition\t";
681     break;
682       // .weak_reference
683   case MCSA_WeakReference:  OS << MAI->getWeakRefDirective(); break;
684   case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
685   case MCSA_Cold:
686     // Assemblers currently do not support a .cold directive.
687     return false;
688   }
689 
690   Symbol->print(OS, MAI);
691   EmitEOL();
692 
693   return true;
694 }
695 
696 void MCAsmStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
697   OS << ".desc" << ' ';
698   Symbol->print(OS, MAI);
699   OS << ',' << DescValue;
700   EmitEOL();
701 }
702 
703 void MCAsmStreamer::emitSyntaxDirective() {
704   if (MAI->getAssemblerDialect() == 1) {
705     OS << "\t.intel_syntax noprefix";
706     EmitEOL();
707   }
708   // FIXME: Currently emit unprefix'ed registers.
709   // The intel_syntax directive has one optional argument
710   // with may have a value of prefix or noprefix.
711 }
712 
713 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
714   OS << "\t.def\t ";
715   Symbol->print(OS, MAI);
716   OS << ';';
717   EmitEOL();
718 }
719 
720 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
721   OS << "\t.scl\t" << StorageClass << ';';
722   EmitEOL();
723 }
724 
725 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
726   OS << "\t.type\t" << Type << ';';
727   EmitEOL();
728 }
729 
730 void MCAsmStreamer::EndCOFFSymbolDef() {
731   OS << "\t.endef";
732   EmitEOL();
733 }
734 
735 void MCAsmStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
736   OS << "\t.safeseh\t";
737   Symbol->print(OS, MAI);
738   EmitEOL();
739 }
740 
741 void MCAsmStreamer::EmitCOFFSymbolIndex(MCSymbol const *Symbol) {
742   OS << "\t.symidx\t";
743   Symbol->print(OS, MAI);
744   EmitEOL();
745 }
746 
747 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
748   OS << "\t.secidx\t";
749   Symbol->print(OS, MAI);
750   EmitEOL();
751 }
752 
753 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {
754   OS << "\t.secrel32\t";
755   Symbol->print(OS, MAI);
756   if (Offset != 0)
757     OS << '+' << Offset;
758   EmitEOL();
759 }
760 
761 void MCAsmStreamer::EmitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) {
762   OS << "\t.rva\t";
763   Symbol->print(OS, MAI);
764   if (Offset > 0)
765     OS << '+' << Offset;
766   else if (Offset < 0)
767     OS << '-' << -Offset;
768   EmitEOL();
769 }
770 
771 // We need an XCOFF-specific version of this directive as the AIX syntax
772 // requires a QualName argument identifying the csect name and storage mapping
773 // class to appear before the alignment if we are specifying it.
774 void MCAsmStreamer::emitXCOFFLocalCommonSymbol(MCSymbol *LabelSym,
775                                                uint64_t Size,
776                                                MCSymbol *CsectSym,
777                                                unsigned ByteAlignment) {
778   assert(MAI->getLCOMMDirectiveAlignmentType() == LCOMM::Log2Alignment &&
779          "We only support writing log base-2 alignment format with XCOFF.");
780   assert(isPowerOf2_32(ByteAlignment) && "Alignment must be a power of 2.");
781 
782   OS << "\t.lcomm\t";
783   LabelSym->print(OS, MAI);
784   OS << ',' << Size << ',';
785   CsectSym->print(OS, MAI);
786   OS << ',' << Log2_32(ByteAlignment);
787 
788   EmitEOL();
789 }
790 
791 void MCAsmStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
792   assert(MAI->hasDotTypeDotSizeDirective());
793   OS << "\t.size\t";
794   Symbol->print(OS, MAI);
795   OS << ", ";
796   Value->print(OS, MAI);
797   EmitEOL();
798 }
799 
800 void MCAsmStreamer::emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
801                                      unsigned ByteAlignment) {
802   OS << "\t.comm\t";
803   Symbol->print(OS, MAI);
804   OS << ',' << Size;
805 
806   if (ByteAlignment != 0) {
807     if (MAI->getCOMMDirectiveAlignmentIsInBytes())
808       OS << ',' << ByteAlignment;
809     else
810       OS << ',' << Log2_32(ByteAlignment);
811   }
812   EmitEOL();
813 }
814 
815 void MCAsmStreamer::emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
816                                           unsigned ByteAlign) {
817   OS << "\t.lcomm\t";
818   Symbol->print(OS, MAI);
819   OS << ',' << Size;
820 
821   if (ByteAlign > 1) {
822     switch (MAI->getLCOMMDirectiveAlignmentType()) {
823     case LCOMM::NoAlignment:
824       llvm_unreachable("alignment not supported on .lcomm!");
825     case LCOMM::ByteAlignment:
826       OS << ',' << ByteAlign;
827       break;
828     case LCOMM::Log2Alignment:
829       assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
830       OS << ',' << Log2_32(ByteAlign);
831       break;
832     }
833   }
834   EmitEOL();
835 }
836 
837 void MCAsmStreamer::emitZerofill(MCSection *Section, MCSymbol *Symbol,
838                                  uint64_t Size, unsigned ByteAlignment,
839                                  SMLoc Loc) {
840   if (Symbol)
841     AssignFragment(Symbol, &Section->getDummyFragment());
842 
843   // Note: a .zerofill directive does not switch sections.
844   OS << ".zerofill ";
845 
846   assert(Section->getVariant() == MCSection::SV_MachO &&
847          ".zerofill is a Mach-O specific directive");
848   // This is a mach-o specific directive.
849 
850   const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
851   OS << MOSection->getSegmentName() << "," << MOSection->getName();
852 
853   if (Symbol) {
854     OS << ',';
855     Symbol->print(OS, MAI);
856     OS << ',' << Size;
857     if (ByteAlignment != 0)
858       OS << ',' << Log2_32(ByteAlignment);
859   }
860   EmitEOL();
861 }
862 
863 // .tbss sym, size, align
864 // This depends that the symbol has already been mangled from the original,
865 // e.g. _a.
866 void MCAsmStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
867                                    uint64_t Size, unsigned ByteAlignment) {
868   AssignFragment(Symbol, &Section->getDummyFragment());
869 
870   assert(Symbol && "Symbol shouldn't be NULL!");
871   // Instead of using the Section we'll just use the shortcut.
872 
873   assert(Section->getVariant() == MCSection::SV_MachO &&
874          ".zerofill is a Mach-O specific directive");
875   // This is a mach-o specific directive and section.
876 
877   OS << ".tbss ";
878   Symbol->print(OS, MAI);
879   OS << ", " << Size;
880 
881   // Output align if we have it.  We default to 1 so don't bother printing
882   // that.
883   if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
884 
885   EmitEOL();
886 }
887 
888 static inline char toOctal(int X) { return (X&7)+'0'; }
889 
890 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
891   OS << '"';
892 
893   for (unsigned i = 0, e = Data.size(); i != e; ++i) {
894     unsigned char C = Data[i];
895     if (C == '"' || C == '\\') {
896       OS << '\\' << (char)C;
897       continue;
898     }
899 
900     if (isPrint((unsigned char)C)) {
901       OS << (char)C;
902       continue;
903     }
904 
905     switch (C) {
906       case '\b': OS << "\\b"; break;
907       case '\f': OS << "\\f"; break;
908       case '\n': OS << "\\n"; break;
909       case '\r': OS << "\\r"; break;
910       case '\t': OS << "\\t"; break;
911       default:
912         OS << '\\';
913         OS << toOctal(C >> 6);
914         OS << toOctal(C >> 3);
915         OS << toOctal(C >> 0);
916         break;
917     }
918   }
919 
920   OS << '"';
921 }
922 
923 void MCAsmStreamer::emitBytes(StringRef Data) {
924   assert(getCurrentSectionOnly() &&
925          "Cannot emit contents before setting section!");
926   if (Data.empty()) return;
927 
928   // If only single byte is provided or no ascii or asciz directives is
929   // supported, emit as vector of 8bits data.
930   if (Data.size() == 1 ||
931       !(MAI->getAscizDirective() || MAI->getAsciiDirective())) {
932     if (MCTargetStreamer *TS = getTargetStreamer()) {
933       TS->emitRawBytes(Data);
934     } else {
935       const char *Directive = MAI->getData8bitsDirective();
936       for (const unsigned char C : Data.bytes()) {
937         OS << Directive << (unsigned)C;
938         EmitEOL();
939       }
940     }
941     return;
942   }
943 
944   // If the data ends with 0 and the target supports .asciz, use it, otherwise
945   // use .ascii
946   if (MAI->getAscizDirective() && Data.back() == 0) {
947     OS << MAI->getAscizDirective();
948     Data = Data.substr(0, Data.size()-1);
949   } else {
950     OS << MAI->getAsciiDirective();
951   }
952 
953   PrintQuotedString(Data, OS);
954   EmitEOL();
955 }
956 
957 void MCAsmStreamer::emitBinaryData(StringRef Data) {
958   // This is binary data. Print it in a grid of hex bytes for readability.
959   const size_t Cols = 4;
960   for (size_t I = 0, EI = alignTo(Data.size(), Cols); I < EI; I += Cols) {
961     size_t J = I, EJ = std::min(I + Cols, Data.size());
962     assert(EJ > 0);
963     OS << MAI->getData8bitsDirective();
964     for (; J < EJ - 1; ++J)
965       OS << format("0x%02x", uint8_t(Data[J])) << ", ";
966     OS << format("0x%02x", uint8_t(Data[J]));
967     EmitEOL();
968   }
969 }
970 
971 void MCAsmStreamer::emitIntValue(uint64_t Value, unsigned Size) {
972   emitValue(MCConstantExpr::create(Value, getContext()), Size);
973 }
974 
975 void MCAsmStreamer::emitIntValueInHex(uint64_t Value, unsigned Size) {
976   emitValue(MCConstantExpr::create(Value, getContext(), true), Size);
977 }
978 
979 void MCAsmStreamer::emitIntValueInHexWithPadding(uint64_t Value,
980                                                  unsigned Size) {
981   emitValue(MCConstantExpr::create(Value, getContext(), true, Size), Size);
982 }
983 
984 void MCAsmStreamer::emitValueImpl(const MCExpr *Value, unsigned Size,
985                                   SMLoc Loc) {
986   assert(Size <= 8 && "Invalid size");
987   assert(getCurrentSectionOnly() &&
988          "Cannot emit contents before setting section!");
989   const char *Directive = nullptr;
990   switch (Size) {
991   default: break;
992   case 1: Directive = MAI->getData8bitsDirective();  break;
993   case 2: Directive = MAI->getData16bitsDirective(); break;
994   case 4: Directive = MAI->getData32bitsDirective(); break;
995   case 8: Directive = MAI->getData64bitsDirective(); break;
996   }
997 
998   if (!Directive) {
999     int64_t IntValue;
1000     if (!Value->evaluateAsAbsolute(IntValue))
1001       report_fatal_error("Don't know how to emit this value.");
1002 
1003     // We couldn't handle the requested integer size so we fallback by breaking
1004     // the request down into several, smaller, integers.
1005     // Since sizes greater or equal to "Size" are invalid, we use the greatest
1006     // power of 2 that is less than "Size" as our largest piece of granularity.
1007     bool IsLittleEndian = MAI->isLittleEndian();
1008     for (unsigned Emitted = 0; Emitted != Size;) {
1009       unsigned Remaining = Size - Emitted;
1010       // The size of our partial emission must be a power of two less than
1011       // Size.
1012       unsigned EmissionSize = PowerOf2Floor(std::min(Remaining, Size - 1));
1013       // Calculate the byte offset of our partial emission taking into account
1014       // the endianness of the target.
1015       unsigned ByteOffset =
1016           IsLittleEndian ? Emitted : (Remaining - EmissionSize);
1017       uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
1018       // We truncate our partial emission to fit within the bounds of the
1019       // emission domain.  This produces nicer output and silences potential
1020       // truncation warnings when round tripping through another assembler.
1021       uint64_t Shift = 64 - EmissionSize * 8;
1022       assert(Shift < static_cast<uint64_t>(
1023                          std::numeric_limits<unsigned long long>::digits) &&
1024              "undefined behavior");
1025       ValueToEmit &= ~0ULL >> Shift;
1026       emitIntValue(ValueToEmit, EmissionSize);
1027       Emitted += EmissionSize;
1028     }
1029     return;
1030   }
1031 
1032   assert(Directive && "Invalid size for machine code value!");
1033   OS << Directive;
1034   if (MCTargetStreamer *TS = getTargetStreamer()) {
1035     TS->emitValue(Value);
1036   } else {
1037     Value->print(OS, MAI);
1038     EmitEOL();
1039   }
1040 }
1041 
1042 void MCAsmStreamer::emitULEB128Value(const MCExpr *Value) {
1043   int64_t IntValue;
1044   if (Value->evaluateAsAbsolute(IntValue)) {
1045     emitULEB128IntValue(IntValue);
1046     return;
1047   }
1048   OS << "\t.uleb128 ";
1049   Value->print(OS, MAI);
1050   EmitEOL();
1051 }
1052 
1053 void MCAsmStreamer::emitSLEB128Value(const MCExpr *Value) {
1054   int64_t IntValue;
1055   if (Value->evaluateAsAbsolute(IntValue)) {
1056     emitSLEB128IntValue(IntValue);
1057     return;
1058   }
1059   OS << "\t.sleb128 ";
1060   Value->print(OS, MAI);
1061   EmitEOL();
1062 }
1063 
1064 void MCAsmStreamer::emitDTPRel64Value(const MCExpr *Value) {
1065   assert(MAI->getDTPRel64Directive() != nullptr);
1066   OS << MAI->getDTPRel64Directive();
1067   Value->print(OS, MAI);
1068   EmitEOL();
1069 }
1070 
1071 void MCAsmStreamer::emitDTPRel32Value(const MCExpr *Value) {
1072   assert(MAI->getDTPRel32Directive() != nullptr);
1073   OS << MAI->getDTPRel32Directive();
1074   Value->print(OS, MAI);
1075   EmitEOL();
1076 }
1077 
1078 void MCAsmStreamer::emitTPRel64Value(const MCExpr *Value) {
1079   assert(MAI->getTPRel64Directive() != nullptr);
1080   OS << MAI->getTPRel64Directive();
1081   Value->print(OS, MAI);
1082   EmitEOL();
1083 }
1084 
1085 void MCAsmStreamer::emitTPRel32Value(const MCExpr *Value) {
1086   assert(MAI->getTPRel32Directive() != nullptr);
1087   OS << MAI->getTPRel32Directive();
1088   Value->print(OS, MAI);
1089   EmitEOL();
1090 }
1091 
1092 void MCAsmStreamer::emitGPRel64Value(const MCExpr *Value) {
1093   assert(MAI->getGPRel64Directive() != nullptr);
1094   OS << MAI->getGPRel64Directive();
1095   Value->print(OS, MAI);
1096   EmitEOL();
1097 }
1098 
1099 void MCAsmStreamer::emitGPRel32Value(const MCExpr *Value) {
1100   assert(MAI->getGPRel32Directive() != nullptr);
1101   OS << MAI->getGPRel32Directive();
1102   Value->print(OS, MAI);
1103   EmitEOL();
1104 }
1105 
1106 void MCAsmStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
1107                              SMLoc Loc) {
1108   int64_t IntNumBytes;
1109   const bool IsAbsolute = NumBytes.evaluateAsAbsolute(IntNumBytes);
1110   if (IsAbsolute && IntNumBytes == 0)
1111     return;
1112 
1113   if (const char *ZeroDirective = MAI->getZeroDirective()) {
1114     if (MAI->doesZeroDirectiveSupportNonZeroValue() || FillValue == 0) {
1115       // FIXME: Emit location directives
1116       OS << ZeroDirective;
1117       NumBytes.print(OS, MAI);
1118       if (FillValue != 0)
1119         OS << ',' << (int)FillValue;
1120       EmitEOL();
1121     } else {
1122       if (!IsAbsolute)
1123         report_fatal_error(
1124             "Cannot emit non-absolute expression lengths of fill.");
1125       for (int i = 0; i < IntNumBytes; ++i) {
1126         OS << MAI->getData8bitsDirective() << (int)FillValue;
1127         EmitEOL();
1128       }
1129     }
1130     return;
1131   }
1132 
1133   MCStreamer::emitFill(NumBytes, FillValue);
1134 }
1135 
1136 void MCAsmStreamer::emitFill(const MCExpr &NumValues, int64_t Size,
1137                              int64_t Expr, SMLoc Loc) {
1138   // FIXME: Emit location directives
1139   OS << "\t.fill\t";
1140   NumValues.print(OS, MAI);
1141   OS << ", " << Size << ", 0x";
1142   OS.write_hex(truncateToSize(Expr, 4));
1143   EmitEOL();
1144 }
1145 
1146 void MCAsmStreamer::emitValueToAlignment(unsigned ByteAlignment, int64_t Value,
1147                                          unsigned ValueSize,
1148                                          unsigned MaxBytesToEmit) {
1149   if (MAI->useDotAlignForAlignment()) {
1150     if (!isPowerOf2_32(ByteAlignment))
1151       report_fatal_error("Only power-of-two alignments are supported "
1152                          "with .align.");
1153     OS << "\t.align\t";
1154     OS << Log2_32(ByteAlignment);
1155     EmitEOL();
1156     return;
1157   }
1158 
1159   // Some assemblers don't support non-power of two alignments, so we always
1160   // emit alignments as a power of two if possible.
1161   if (isPowerOf2_32(ByteAlignment)) {
1162     switch (ValueSize) {
1163     default:
1164       llvm_unreachable("Invalid size for machine code value!");
1165     case 1:
1166       OS << "\t.p2align\t";
1167       break;
1168     case 2:
1169       OS << ".p2alignw ";
1170       break;
1171     case 4:
1172       OS << ".p2alignl ";
1173       break;
1174     case 8:
1175       llvm_unreachable("Unsupported alignment size!");
1176     }
1177 
1178     OS << Log2_32(ByteAlignment);
1179 
1180     if (Value || MaxBytesToEmit) {
1181       OS << ", 0x";
1182       OS.write_hex(truncateToSize(Value, ValueSize));
1183 
1184       if (MaxBytesToEmit)
1185         OS << ", " << MaxBytesToEmit;
1186     }
1187     EmitEOL();
1188     return;
1189   }
1190 
1191   // Non-power of two alignment.  This is not widely supported by assemblers.
1192   // FIXME: Parameterize this based on MAI.
1193   switch (ValueSize) {
1194   default: llvm_unreachable("Invalid size for machine code value!");
1195   case 1: OS << ".balign";  break;
1196   case 2: OS << ".balignw"; break;
1197   case 4: OS << ".balignl"; break;
1198   case 8: llvm_unreachable("Unsupported alignment size!");
1199   }
1200 
1201   OS << ' ' << ByteAlignment;
1202   OS << ", " << truncateToSize(Value, ValueSize);
1203   if (MaxBytesToEmit)
1204     OS << ", " << MaxBytesToEmit;
1205   EmitEOL();
1206 }
1207 
1208 void MCAsmStreamer::emitCodeAlignment(unsigned ByteAlignment,
1209                                       unsigned MaxBytesToEmit) {
1210   // Emit with a text fill value.
1211   emitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
1212                        1, MaxBytesToEmit);
1213 }
1214 
1215 void MCAsmStreamer::emitValueToOffset(const MCExpr *Offset,
1216                                       unsigned char Value,
1217                                       SMLoc Loc) {
1218   // FIXME: Verify that Offset is associated with the current section.
1219   OS << ".org ";
1220   Offset->print(OS, MAI);
1221   OS << ", " << (unsigned)Value;
1222   EmitEOL();
1223 }
1224 
1225 void MCAsmStreamer::emitFileDirective(StringRef Filename) {
1226   assert(MAI->hasSingleParameterDotFile());
1227   OS << "\t.file\t";
1228   PrintQuotedString(Filename, OS);
1229   EmitEOL();
1230 }
1231 
1232 static void printDwarfFileDirective(unsigned FileNo, StringRef Directory,
1233                                     StringRef Filename,
1234                                     Optional<MD5::MD5Result> Checksum,
1235                                     Optional<StringRef> Source,
1236                                     bool UseDwarfDirectory,
1237                                     raw_svector_ostream &OS) {
1238   SmallString<128> FullPathName;
1239 
1240   if (!UseDwarfDirectory && !Directory.empty()) {
1241     if (sys::path::is_absolute(Filename))
1242       Directory = "";
1243     else {
1244       FullPathName = Directory;
1245       sys::path::append(FullPathName, Filename);
1246       Directory = "";
1247       Filename = FullPathName;
1248     }
1249   }
1250 
1251   OS << "\t.file\t" << FileNo << ' ';
1252   if (!Directory.empty()) {
1253     PrintQuotedString(Directory, OS);
1254     OS << ' ';
1255   }
1256   PrintQuotedString(Filename, OS);
1257   if (Checksum)
1258     OS << " md5 0x" << Checksum->digest();
1259   if (Source) {
1260     OS << " source ";
1261     PrintQuotedString(*Source, OS);
1262   }
1263 }
1264 
1265 Expected<unsigned> MCAsmStreamer::tryEmitDwarfFileDirective(
1266     unsigned FileNo, StringRef Directory, StringRef Filename,
1267     Optional<MD5::MD5Result> Checksum, Optional<StringRef> Source, unsigned CUID) {
1268   assert(CUID == 0 && "multiple CUs not supported by MCAsmStreamer");
1269 
1270   MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
1271   unsigned NumFiles = Table.getMCDwarfFiles().size();
1272   Expected<unsigned> FileNoOrErr =
1273       Table.tryGetFile(Directory, Filename, Checksum, Source,
1274                        getContext().getDwarfVersion(), FileNo);
1275   if (!FileNoOrErr)
1276     return FileNoOrErr.takeError();
1277   FileNo = FileNoOrErr.get();
1278   if (NumFiles == Table.getMCDwarfFiles().size())
1279     return FileNo;
1280 
1281   SmallString<128> Str;
1282   raw_svector_ostream OS1(Str);
1283   printDwarfFileDirective(FileNo, Directory, Filename, Checksum, Source,
1284                           UseDwarfDirectory, OS1);
1285 
1286   if (MCTargetStreamer *TS = getTargetStreamer())
1287     TS->emitDwarfFileDirective(OS1.str());
1288   else
1289     emitRawText(OS1.str());
1290 
1291   return FileNo;
1292 }
1293 
1294 void MCAsmStreamer::emitDwarfFile0Directive(StringRef Directory,
1295                                             StringRef Filename,
1296                                             Optional<MD5::MD5Result> Checksum,
1297                                             Optional<StringRef> Source,
1298                                             unsigned CUID) {
1299   assert(CUID == 0);
1300   // .file 0 is new for DWARF v5.
1301   if (getContext().getDwarfVersion() < 5)
1302     return;
1303   // Inform MCDwarf about the root file.
1304   getContext().setMCLineTableRootFile(CUID, Directory, Filename, Checksum,
1305                                       Source);
1306 
1307   SmallString<128> Str;
1308   raw_svector_ostream OS1(Str);
1309   printDwarfFileDirective(0, Directory, Filename, Checksum, Source,
1310                           UseDwarfDirectory, OS1);
1311 
1312   if (MCTargetStreamer *TS = getTargetStreamer())
1313     TS->emitDwarfFileDirective(OS1.str());
1314   else
1315     emitRawText(OS1.str());
1316 }
1317 
1318 void MCAsmStreamer::emitDwarfLocDirective(unsigned FileNo, unsigned Line,
1319                                           unsigned Column, unsigned Flags,
1320                                           unsigned Isa, unsigned Discriminator,
1321                                           StringRef FileName) {
1322   OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
1323   if (MAI->supportsExtendedDwarfLocDirective()) {
1324     if (Flags & DWARF2_FLAG_BASIC_BLOCK)
1325       OS << " basic_block";
1326     if (Flags & DWARF2_FLAG_PROLOGUE_END)
1327       OS << " prologue_end";
1328     if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
1329       OS << " epilogue_begin";
1330 
1331     unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
1332     if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
1333       OS << " is_stmt ";
1334 
1335       if (Flags & DWARF2_FLAG_IS_STMT)
1336         OS << "1";
1337       else
1338         OS << "0";
1339     }
1340 
1341     if (Isa)
1342       OS << " isa " << Isa;
1343     if (Discriminator)
1344       OS << " discriminator " << Discriminator;
1345   }
1346 
1347   if (IsVerboseAsm) {
1348     OS.PadToColumn(MAI->getCommentColumn());
1349     OS << MAI->getCommentString() << ' ' << FileName << ':'
1350        << Line << ':' << Column;
1351   }
1352   EmitEOL();
1353   this->MCStreamer::emitDwarfLocDirective(FileNo, Line, Column, Flags, Isa,
1354                                           Discriminator, FileName);
1355 }
1356 
1357 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
1358   // Always use the zeroth line table, since asm syntax only supports one line
1359   // table for now.
1360   return MCStreamer::getDwarfLineTableSymbol(0);
1361 }
1362 
1363 bool MCAsmStreamer::EmitCVFileDirective(unsigned FileNo, StringRef Filename,
1364                                         ArrayRef<uint8_t> Checksum,
1365                                         unsigned ChecksumKind) {
1366   if (!getContext().getCVContext().addFile(*this, FileNo, Filename, Checksum,
1367                                            ChecksumKind))
1368     return false;
1369 
1370   OS << "\t.cv_file\t" << FileNo << ' ';
1371   PrintQuotedString(Filename, OS);
1372 
1373   if (!ChecksumKind) {
1374     EmitEOL();
1375     return true;
1376   }
1377 
1378   OS << ' ';
1379   PrintQuotedString(toHex(Checksum), OS);
1380   OS << ' ' << ChecksumKind;
1381 
1382   EmitEOL();
1383   return true;
1384 }
1385 
1386 bool MCAsmStreamer::EmitCVFuncIdDirective(unsigned FuncId) {
1387   OS << "\t.cv_func_id " << FuncId << '\n';
1388   return MCStreamer::EmitCVFuncIdDirective(FuncId);
1389 }
1390 
1391 bool MCAsmStreamer::EmitCVInlineSiteIdDirective(unsigned FunctionId,
1392                                                 unsigned IAFunc,
1393                                                 unsigned IAFile,
1394                                                 unsigned IALine, unsigned IACol,
1395                                                 SMLoc Loc) {
1396   OS << "\t.cv_inline_site_id " << FunctionId << " within " << IAFunc
1397      << " inlined_at " << IAFile << ' ' << IALine << ' ' << IACol << '\n';
1398   return MCStreamer::EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
1399                                                  IALine, IACol, Loc);
1400 }
1401 
1402 void MCAsmStreamer::emitCVLocDirective(unsigned FunctionId, unsigned FileNo,
1403                                        unsigned Line, unsigned Column,
1404                                        bool PrologueEnd, bool IsStmt,
1405                                        StringRef FileName, SMLoc Loc) {
1406   // Validate the directive.
1407   if (!checkCVLocSection(FunctionId, FileNo, Loc))
1408     return;
1409 
1410   OS << "\t.cv_loc\t" << FunctionId << " " << FileNo << " " << Line << " "
1411      << Column;
1412   if (PrologueEnd)
1413     OS << " prologue_end";
1414 
1415   if (IsStmt)
1416     OS << " is_stmt 1";
1417 
1418   if (IsVerboseAsm) {
1419     OS.PadToColumn(MAI->getCommentColumn());
1420     OS << MAI->getCommentString() << ' ' << FileName << ':' << Line << ':'
1421        << Column;
1422   }
1423   EmitEOL();
1424 }
1425 
1426 void MCAsmStreamer::emitCVLinetableDirective(unsigned FunctionId,
1427                                              const MCSymbol *FnStart,
1428                                              const MCSymbol *FnEnd) {
1429   OS << "\t.cv_linetable\t" << FunctionId << ", ";
1430   FnStart->print(OS, MAI);
1431   OS << ", ";
1432   FnEnd->print(OS, MAI);
1433   EmitEOL();
1434   this->MCStreamer::emitCVLinetableDirective(FunctionId, FnStart, FnEnd);
1435 }
1436 
1437 void MCAsmStreamer::emitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
1438                                                    unsigned SourceFileId,
1439                                                    unsigned SourceLineNum,
1440                                                    const MCSymbol *FnStartSym,
1441                                                    const MCSymbol *FnEndSym) {
1442   OS << "\t.cv_inline_linetable\t" << PrimaryFunctionId << ' ' << SourceFileId
1443      << ' ' << SourceLineNum << ' ';
1444   FnStartSym->print(OS, MAI);
1445   OS << ' ';
1446   FnEndSym->print(OS, MAI);
1447   EmitEOL();
1448   this->MCStreamer::emitCVInlineLinetableDirective(
1449       PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
1450 }
1451 
1452 void MCAsmStreamer::PrintCVDefRangePrefix(
1453     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges) {
1454   OS << "\t.cv_def_range\t";
1455   for (std::pair<const MCSymbol *, const MCSymbol *> Range : Ranges) {
1456     OS << ' ';
1457     Range.first->print(OS, MAI);
1458     OS << ' ';
1459     Range.second->print(OS, MAI);
1460   }
1461 }
1462 
1463 void MCAsmStreamer::emitCVDefRangeDirective(
1464     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1465     codeview::DefRangeRegisterRelHeader DRHdr) {
1466   PrintCVDefRangePrefix(Ranges);
1467   OS << ", reg_rel, ";
1468   OS << DRHdr.Register << ", " << DRHdr.Flags << ", "
1469      << DRHdr.BasePointerOffset;
1470   EmitEOL();
1471 }
1472 
1473 void MCAsmStreamer::emitCVDefRangeDirective(
1474     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1475     codeview::DefRangeSubfieldRegisterHeader DRHdr) {
1476   PrintCVDefRangePrefix(Ranges);
1477   OS << ", subfield_reg, ";
1478   OS << DRHdr.Register << ", " << DRHdr.OffsetInParent;
1479   EmitEOL();
1480 }
1481 
1482 void MCAsmStreamer::emitCVDefRangeDirective(
1483     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1484     codeview::DefRangeRegisterHeader DRHdr) {
1485   PrintCVDefRangePrefix(Ranges);
1486   OS << ", reg, ";
1487   OS << DRHdr.Register;
1488   EmitEOL();
1489 }
1490 
1491 void MCAsmStreamer::emitCVDefRangeDirective(
1492     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1493     codeview::DefRangeFramePointerRelHeader DRHdr) {
1494   PrintCVDefRangePrefix(Ranges);
1495   OS << ", frame_ptr_rel, ";
1496   OS << DRHdr.Offset;
1497   EmitEOL();
1498 }
1499 
1500 void MCAsmStreamer::emitCVStringTableDirective() {
1501   OS << "\t.cv_stringtable";
1502   EmitEOL();
1503 }
1504 
1505 void MCAsmStreamer::emitCVFileChecksumsDirective() {
1506   OS << "\t.cv_filechecksums";
1507   EmitEOL();
1508 }
1509 
1510 void MCAsmStreamer::emitCVFileChecksumOffsetDirective(unsigned FileNo) {
1511   OS << "\t.cv_filechecksumoffset\t" << FileNo;
1512   EmitEOL();
1513 }
1514 
1515 void MCAsmStreamer::EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) {
1516   OS << "\t.cv_fpo_data\t";
1517   ProcSym->print(OS, MAI);
1518   EmitEOL();
1519 }
1520 
1521 void MCAsmStreamer::emitIdent(StringRef IdentString) {
1522   assert(MAI->hasIdentDirective() && ".ident directive not supported");
1523   OS << "\t.ident\t";
1524   PrintQuotedString(IdentString, OS);
1525   EmitEOL();
1526 }
1527 
1528 void MCAsmStreamer::emitCFISections(bool EH, bool Debug) {
1529   MCStreamer::emitCFISections(EH, Debug);
1530   OS << "\t.cfi_sections ";
1531   if (EH) {
1532     OS << ".eh_frame";
1533     if (Debug)
1534       OS << ", .debug_frame";
1535   } else if (Debug) {
1536     OS << ".debug_frame";
1537   }
1538 
1539   EmitEOL();
1540 }
1541 
1542 void MCAsmStreamer::emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
1543   OS << "\t.cfi_startproc";
1544   if (Frame.IsSimple)
1545     OS << " simple";
1546   EmitEOL();
1547 }
1548 
1549 void MCAsmStreamer::emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
1550   MCStreamer::emitCFIEndProcImpl(Frame);
1551   OS << "\t.cfi_endproc";
1552   EmitEOL();
1553 }
1554 
1555 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
1556   if (!MAI->useDwarfRegNumForCFI()) {
1557     // User .cfi_* directives can use arbitrary DWARF register numbers, not
1558     // just ones that map to LLVM register numbers and have known names.
1559     // Fall back to using the original number directly if no name is known.
1560     const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1561     if (Optional<unsigned> LLVMRegister = MRI->getLLVMRegNum(Register, true)) {
1562       InstPrinter->printRegName(OS, *LLVMRegister);
1563       return;
1564     }
1565   }
1566   OS << Register;
1567 }
1568 
1569 void MCAsmStreamer::emitCFIDefCfa(int64_t Register, int64_t Offset) {
1570   MCStreamer::emitCFIDefCfa(Register, Offset);
1571   OS << "\t.cfi_def_cfa ";
1572   EmitRegisterName(Register);
1573   OS << ", " << Offset;
1574   EmitEOL();
1575 }
1576 
1577 void MCAsmStreamer::emitCFIDefCfaOffset(int64_t Offset) {
1578   MCStreamer::emitCFIDefCfaOffset(Offset);
1579   OS << "\t.cfi_def_cfa_offset " << Offset;
1580   EmitEOL();
1581 }
1582 
1583 static void PrintCFIEscape(llvm::formatted_raw_ostream &OS, StringRef Values) {
1584   OS << "\t.cfi_escape ";
1585   if (!Values.empty()) {
1586     size_t e = Values.size() - 1;
1587     for (size_t i = 0; i < e; ++i)
1588       OS << format("0x%02x", uint8_t(Values[i])) << ", ";
1589     OS << format("0x%02x", uint8_t(Values[e]));
1590   }
1591 }
1592 
1593 void MCAsmStreamer::emitCFIEscape(StringRef Values) {
1594   MCStreamer::emitCFIEscape(Values);
1595   PrintCFIEscape(OS, Values);
1596   EmitEOL();
1597 }
1598 
1599 void MCAsmStreamer::emitCFIGnuArgsSize(int64_t Size) {
1600   MCStreamer::emitCFIGnuArgsSize(Size);
1601 
1602   uint8_t Buffer[16] = { dwarf::DW_CFA_GNU_args_size };
1603   unsigned Len = encodeULEB128(Size, Buffer + 1) + 1;
1604 
1605   PrintCFIEscape(OS, StringRef((const char *)&Buffer[0], Len));
1606   EmitEOL();
1607 }
1608 
1609 void MCAsmStreamer::emitCFIDefCfaRegister(int64_t Register) {
1610   MCStreamer::emitCFIDefCfaRegister(Register);
1611   OS << "\t.cfi_def_cfa_register ";
1612   EmitRegisterName(Register);
1613   EmitEOL();
1614 }
1615 
1616 void MCAsmStreamer::emitCFIOffset(int64_t Register, int64_t Offset) {
1617   this->MCStreamer::emitCFIOffset(Register, Offset);
1618   OS << "\t.cfi_offset ";
1619   EmitRegisterName(Register);
1620   OS << ", " << Offset;
1621   EmitEOL();
1622 }
1623 
1624 void MCAsmStreamer::emitCFIPersonality(const MCSymbol *Sym,
1625                                        unsigned Encoding) {
1626   MCStreamer::emitCFIPersonality(Sym, Encoding);
1627   OS << "\t.cfi_personality " << Encoding << ", ";
1628   Sym->print(OS, MAI);
1629   EmitEOL();
1630 }
1631 
1632 void MCAsmStreamer::emitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1633   MCStreamer::emitCFILsda(Sym, Encoding);
1634   OS << "\t.cfi_lsda " << Encoding << ", ";
1635   Sym->print(OS, MAI);
1636   EmitEOL();
1637 }
1638 
1639 void MCAsmStreamer::emitCFIRememberState() {
1640   MCStreamer::emitCFIRememberState();
1641   OS << "\t.cfi_remember_state";
1642   EmitEOL();
1643 }
1644 
1645 void MCAsmStreamer::emitCFIRestoreState() {
1646   MCStreamer::emitCFIRestoreState();
1647   OS << "\t.cfi_restore_state";
1648   EmitEOL();
1649 }
1650 
1651 void MCAsmStreamer::emitCFIRestore(int64_t Register) {
1652   MCStreamer::emitCFIRestore(Register);
1653   OS << "\t.cfi_restore ";
1654   EmitRegisterName(Register);
1655   EmitEOL();
1656 }
1657 
1658 void MCAsmStreamer::emitCFISameValue(int64_t Register) {
1659   MCStreamer::emitCFISameValue(Register);
1660   OS << "\t.cfi_same_value ";
1661   EmitRegisterName(Register);
1662   EmitEOL();
1663 }
1664 
1665 void MCAsmStreamer::emitCFIRelOffset(int64_t Register, int64_t Offset) {
1666   MCStreamer::emitCFIRelOffset(Register, Offset);
1667   OS << "\t.cfi_rel_offset ";
1668   EmitRegisterName(Register);
1669   OS << ", " << Offset;
1670   EmitEOL();
1671 }
1672 
1673 void MCAsmStreamer::emitCFIAdjustCfaOffset(int64_t Adjustment) {
1674   MCStreamer::emitCFIAdjustCfaOffset(Adjustment);
1675   OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1676   EmitEOL();
1677 }
1678 
1679 void MCAsmStreamer::emitCFISignalFrame() {
1680   MCStreamer::emitCFISignalFrame();
1681   OS << "\t.cfi_signal_frame";
1682   EmitEOL();
1683 }
1684 
1685 void MCAsmStreamer::emitCFIUndefined(int64_t Register) {
1686   MCStreamer::emitCFIUndefined(Register);
1687   OS << "\t.cfi_undefined ";
1688   EmitRegisterName(Register);
1689   EmitEOL();
1690 }
1691 
1692 void MCAsmStreamer::emitCFIRegister(int64_t Register1, int64_t Register2) {
1693   MCStreamer::emitCFIRegister(Register1, Register2);
1694   OS << "\t.cfi_register ";
1695   EmitRegisterName(Register1);
1696   OS << ", ";
1697   EmitRegisterName(Register2);
1698   EmitEOL();
1699 }
1700 
1701 void MCAsmStreamer::emitCFIWindowSave() {
1702   MCStreamer::emitCFIWindowSave();
1703   OS << "\t.cfi_window_save";
1704   EmitEOL();
1705 }
1706 
1707 void MCAsmStreamer::emitCFINegateRAState() {
1708   MCStreamer::emitCFINegateRAState();
1709   OS << "\t.cfi_negate_ra_state";
1710   EmitEOL();
1711 }
1712 
1713 void MCAsmStreamer::emitCFIReturnColumn(int64_t Register) {
1714   MCStreamer::emitCFIReturnColumn(Register);
1715   OS << "\t.cfi_return_column ";
1716   EmitRegisterName(Register);
1717   EmitEOL();
1718 }
1719 
1720 void MCAsmStreamer::emitCFIBKeyFrame() {
1721   MCStreamer::emitCFIBKeyFrame();
1722   OS << "\t.cfi_b_key_frame";
1723   EmitEOL();
1724 }
1725 
1726 void MCAsmStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) {
1727   MCStreamer::EmitWinCFIStartProc(Symbol, Loc);
1728 
1729   OS << ".seh_proc ";
1730   Symbol->print(OS, MAI);
1731   EmitEOL();
1732 }
1733 
1734 void MCAsmStreamer::EmitWinCFIEndProc(SMLoc Loc) {
1735   MCStreamer::EmitWinCFIEndProc(Loc);
1736 
1737   OS << "\t.seh_endproc";
1738   EmitEOL();
1739 }
1740 
1741 // TODO: Implement
1742 void MCAsmStreamer::EmitWinCFIFuncletOrFuncEnd(SMLoc Loc) {
1743 }
1744 
1745 void MCAsmStreamer::EmitWinCFIStartChained(SMLoc Loc) {
1746   MCStreamer::EmitWinCFIStartChained(Loc);
1747 
1748   OS << "\t.seh_startchained";
1749   EmitEOL();
1750 }
1751 
1752 void MCAsmStreamer::EmitWinCFIEndChained(SMLoc Loc) {
1753   MCStreamer::EmitWinCFIEndChained(Loc);
1754 
1755   OS << "\t.seh_endchained";
1756   EmitEOL();
1757 }
1758 
1759 void MCAsmStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind,
1760                                      bool Except, SMLoc Loc) {
1761   MCStreamer::EmitWinEHHandler(Sym, Unwind, Except, Loc);
1762 
1763   OS << "\t.seh_handler ";
1764   Sym->print(OS, MAI);
1765   if (Unwind)
1766     OS << ", @unwind";
1767   if (Except)
1768     OS << ", @except";
1769   EmitEOL();
1770 }
1771 
1772 void MCAsmStreamer::EmitWinEHHandlerData(SMLoc Loc) {
1773   MCStreamer::EmitWinEHHandlerData(Loc);
1774 
1775   // Switch sections. Don't call SwitchSection directly, because that will
1776   // cause the section switch to be visible in the emitted assembly.
1777   // We only do this so the section switch that terminates the handler
1778   // data block is visible.
1779   WinEH::FrameInfo *CurFrame = getCurrentWinFrameInfo();
1780 
1781   // Do nothing if no frame is open. MCStreamer should've already reported an
1782   // error.
1783   if (!CurFrame)
1784     return;
1785 
1786   MCSection *TextSec = &CurFrame->Function->getSection();
1787   MCSection *XData = getAssociatedXDataSection(TextSec);
1788   SwitchSectionNoChange(XData);
1789 
1790   OS << "\t.seh_handlerdata";
1791   EmitEOL();
1792 }
1793 
1794 void MCAsmStreamer::EmitWinCFIPushReg(MCRegister Register, SMLoc Loc) {
1795   MCStreamer::EmitWinCFIPushReg(Register, Loc);
1796 
1797   OS << "\t.seh_pushreg ";
1798   InstPrinter->printRegName(OS, Register);
1799   EmitEOL();
1800 }
1801 
1802 void MCAsmStreamer::EmitWinCFISetFrame(MCRegister Register, unsigned Offset,
1803                                        SMLoc Loc) {
1804   MCStreamer::EmitWinCFISetFrame(Register, Offset, Loc);
1805 
1806   OS << "\t.seh_setframe ";
1807   InstPrinter->printRegName(OS, Register);
1808   OS << ", " << Offset;
1809   EmitEOL();
1810 }
1811 
1812 void MCAsmStreamer::EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) {
1813   MCStreamer::EmitWinCFIAllocStack(Size, Loc);
1814 
1815   OS << "\t.seh_stackalloc " << Size;
1816   EmitEOL();
1817 }
1818 
1819 void MCAsmStreamer::EmitWinCFISaveReg(MCRegister Register, unsigned Offset,
1820                                       SMLoc Loc) {
1821   MCStreamer::EmitWinCFISaveReg(Register, Offset, Loc);
1822 
1823   OS << "\t.seh_savereg ";
1824   InstPrinter->printRegName(OS, Register);
1825   OS << ", " << Offset;
1826   EmitEOL();
1827 }
1828 
1829 void MCAsmStreamer::EmitWinCFISaveXMM(MCRegister Register, unsigned Offset,
1830                                       SMLoc Loc) {
1831   MCStreamer::EmitWinCFISaveXMM(Register, Offset, Loc);
1832 
1833   OS << "\t.seh_savexmm ";
1834   InstPrinter->printRegName(OS, Register);
1835   OS << ", " << Offset;
1836   EmitEOL();
1837 }
1838 
1839 void MCAsmStreamer::EmitWinCFIPushFrame(bool Code, SMLoc Loc) {
1840   MCStreamer::EmitWinCFIPushFrame(Code, Loc);
1841 
1842   OS << "\t.seh_pushframe";
1843   if (Code)
1844     OS << " @code";
1845   EmitEOL();
1846 }
1847 
1848 void MCAsmStreamer::EmitWinCFIEndProlog(SMLoc Loc) {
1849   MCStreamer::EmitWinCFIEndProlog(Loc);
1850 
1851   OS << "\t.seh_endprologue";
1852   EmitEOL();
1853 }
1854 
1855 void MCAsmStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
1856                                        const MCSymbolRefExpr *To,
1857                                        uint64_t Count) {
1858   OS << "\t.cg_profile ";
1859   From->getSymbol().print(OS, MAI);
1860   OS << ", ";
1861   To->getSymbol().print(OS, MAI);
1862   OS << ", " << Count;
1863   EmitEOL();
1864 }
1865 
1866 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1867                                        const MCSubtargetInfo &STI) {
1868   raw_ostream &OS = GetCommentOS();
1869   SmallString<256> Code;
1870   SmallVector<MCFixup, 4> Fixups;
1871   raw_svector_ostream VecOS(Code);
1872 
1873   // If we have no code emitter, don't emit code.
1874   if (!getAssembler().getEmitterPtr())
1875     return;
1876 
1877   getAssembler().getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
1878 
1879   // If we are showing fixups, create symbolic markers in the encoded
1880   // representation. We do this by making a per-bit map to the fixup item index,
1881   // then trying to display it as nicely as possible.
1882   SmallVector<uint8_t, 64> FixupMap;
1883   FixupMap.resize(Code.size() * 8);
1884   for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1885     FixupMap[i] = 0;
1886 
1887   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1888     MCFixup &F = Fixups[i];
1889     const MCFixupKindInfo &Info =
1890         getAssembler().getBackend().getFixupKindInfo(F.getKind());
1891     for (unsigned j = 0; j != Info.TargetSize; ++j) {
1892       unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1893       assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1894       FixupMap[Index] = 1 + i;
1895     }
1896   }
1897 
1898   // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1899   // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1900   OS << "encoding: [";
1901   for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1902     if (i)
1903       OS << ',';
1904 
1905     // See if all bits are the same map entry.
1906     uint8_t MapEntry = FixupMap[i * 8 + 0];
1907     for (unsigned j = 1; j != 8; ++j) {
1908       if (FixupMap[i * 8 + j] == MapEntry)
1909         continue;
1910 
1911       MapEntry = uint8_t(~0U);
1912       break;
1913     }
1914 
1915     if (MapEntry != uint8_t(~0U)) {
1916       if (MapEntry == 0) {
1917         OS << format("0x%02x", uint8_t(Code[i]));
1918       } else {
1919         if (Code[i]) {
1920           // FIXME: Some of the 8 bits require fix up.
1921           OS << format("0x%02x", uint8_t(Code[i])) << '\''
1922              << char('A' + MapEntry - 1) << '\'';
1923         } else
1924           OS << char('A' + MapEntry - 1);
1925       }
1926     } else {
1927       // Otherwise, write out in binary.
1928       OS << "0b";
1929       for (unsigned j = 8; j--;) {
1930         unsigned Bit = (Code[i] >> j) & 1;
1931 
1932         unsigned FixupBit;
1933         if (MAI->isLittleEndian())
1934           FixupBit = i * 8 + j;
1935         else
1936           FixupBit = i * 8 + (7-j);
1937 
1938         if (uint8_t MapEntry = FixupMap[FixupBit]) {
1939           assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1940           OS << char('A' + MapEntry - 1);
1941         } else
1942           OS << Bit;
1943       }
1944     }
1945   }
1946   OS << "]\n";
1947 
1948   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1949     MCFixup &F = Fixups[i];
1950     const MCFixupKindInfo &Info =
1951         getAssembler().getBackend().getFixupKindInfo(F.getKind());
1952     OS << "  fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1953        << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1954   }
1955 }
1956 
1957 void MCAsmStreamer::emitInstruction(const MCInst &Inst,
1958                                     const MCSubtargetInfo &STI) {
1959   assert(getCurrentSectionOnly() &&
1960          "Cannot emit contents before setting section!");
1961 
1962   // Show the encoding in a comment if we have a code emitter.
1963   AddEncodingComment(Inst, STI);
1964 
1965   // Show the MCInst if enabled.
1966   if (ShowInst) {
1967     Inst.dump_pretty(GetCommentOS(), InstPrinter.get(), "\n ");
1968     GetCommentOS() << "\n";
1969   }
1970 
1971   if(getTargetStreamer())
1972     getTargetStreamer()->prettyPrintAsm(*InstPrinter, 0, Inst, STI, OS);
1973   else
1974     InstPrinter->printInst(&Inst, 0, "", STI, OS);
1975 
1976   StringRef Comments = CommentToEmit;
1977   if (Comments.size() && Comments.back() != '\n')
1978     GetCommentOS() << "\n";
1979 
1980   EmitEOL();
1981 }
1982 
1983 void MCAsmStreamer::emitBundleAlignMode(unsigned AlignPow2) {
1984   OS << "\t.bundle_align_mode " << AlignPow2;
1985   EmitEOL();
1986 }
1987 
1988 void MCAsmStreamer::emitBundleLock(bool AlignToEnd) {
1989   OS << "\t.bundle_lock";
1990   if (AlignToEnd)
1991     OS << " align_to_end";
1992   EmitEOL();
1993 }
1994 
1995 void MCAsmStreamer::emitBundleUnlock() {
1996   OS << "\t.bundle_unlock";
1997   EmitEOL();
1998 }
1999 
2000 bool MCAsmStreamer::emitRelocDirective(const MCExpr &Offset, StringRef Name,
2001                                        const MCExpr *Expr, SMLoc,
2002                                        const MCSubtargetInfo &STI) {
2003   OS << "\t.reloc ";
2004   Offset.print(OS, MAI);
2005   OS << ", " << Name;
2006   if (Expr) {
2007     OS << ", ";
2008     Expr->print(OS, MAI);
2009   }
2010   EmitEOL();
2011   return false;
2012 }
2013 
2014 void MCAsmStreamer::emitAddrsig() {
2015   OS << "\t.addrsig";
2016   EmitEOL();
2017 }
2018 
2019 void MCAsmStreamer::emitAddrsigSym(const MCSymbol *Sym) {
2020   OS << "\t.addrsig_sym ";
2021   Sym->print(OS, MAI);
2022   EmitEOL();
2023 }
2024 
2025 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
2026 /// the specified string in the output .s file.  This capability is
2027 /// indicated by the hasRawTextSupport() predicate.
2028 void MCAsmStreamer::emitRawTextImpl(StringRef String) {
2029   if (!String.empty() && String.back() == '\n')
2030     String = String.substr(0, String.size()-1);
2031   OS << String;
2032   EmitEOL();
2033 }
2034 
2035 void MCAsmStreamer::finishImpl() {
2036   // If we are generating dwarf for assembly source files dump out the sections.
2037   if (getContext().getGenDwarfForAssembly())
2038     MCGenDwarfInfo::Emit(this);
2039 
2040   // Emit the label for the line table, if requested - since the rest of the
2041   // line table will be defined by .loc/.file directives, and not emitted
2042   // directly, the label is the only work required here.
2043   const auto &Tables = getContext().getMCDwarfLineTables();
2044   if (!Tables.empty()) {
2045     assert(Tables.size() == 1 && "asm output only supports one line table");
2046     if (auto *Label = Tables.begin()->second.getLabel()) {
2047       SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
2048       emitLabel(Label);
2049     }
2050   }
2051 }
2052 
2053 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
2054                                     std::unique_ptr<formatted_raw_ostream> OS,
2055                                     bool isVerboseAsm, bool useDwarfDirectory,
2056                                     MCInstPrinter *IP,
2057                                     std::unique_ptr<MCCodeEmitter> &&CE,
2058                                     std::unique_ptr<MCAsmBackend> &&MAB,
2059                                     bool ShowInst) {
2060   return new MCAsmStreamer(Context, std::move(OS), isVerboseAsm,
2061                            useDwarfDirectory, IP, std::move(CE), std::move(MAB),
2062                            ShowInst);
2063 }
2064