1 //===- lib/MC/MCAsmStreamer.cpp - Text Assembly Output --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCStreamer.h"
11 #include "llvm/ADT/OwningPtr.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/StringExtras.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/MC/MCAsmBackend.h"
16 #include "llvm/MC/MCAsmInfo.h"
17 #include "llvm/MC/MCCodeEmitter.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/MCSymbol.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/Format.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Path.h"
39 class MCAsmStreamer : public MCStreamer {
41 formatted_raw_ostream &OS;
44 OwningPtr<MCInstPrinter> InstPrinter;
45 OwningPtr<MCCodeEmitter> Emitter;
46 OwningPtr<MCAsmBackend> AsmBackend;
48 SmallString<128> CommentToEmit;
49 raw_svector_ostream CommentStream;
51 unsigned IsVerboseAsm : 1;
52 unsigned ShowInst : 1;
55 unsigned UseDwarfDirectory : 1;
57 enum EHSymbolFlags { EHGlobal = 1,
58 EHWeakDefinition = 1 << 1,
59 EHPrivateExtern = 1 << 2 };
60 DenseMap<const MCSymbol*, unsigned> FlagMap;
62 bool needsSet(const MCExpr *Value);
64 void EmitRegisterName(int64_t Register);
65 virtual void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame);
66 virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame);
69 MCAsmStreamer(MCContext &Context, MCTargetStreamer *TargetStreamer,
70 formatted_raw_ostream &os, bool isVerboseAsm, bool useLoc,
71 bool useCFI, bool useDwarfDirectory, MCInstPrinter *printer,
72 MCCodeEmitter *emitter, MCAsmBackend *asmbackend, bool showInst)
73 : MCStreamer(Context, TargetStreamer), OS(os), MAI(Context.getAsmInfo()),
74 InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
75 CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
76 ShowInst(showInst), UseLoc(useLoc), UseCFI(useCFI),
77 UseDwarfDirectory(useDwarfDirectory) {
78 if (InstPrinter && IsVerboseAsm)
79 InstPrinter->setCommentStream(CommentStream);
83 inline void EmitEOL() {
84 // If we don't have any comments, just emit a \n.
91 void EmitCommentsAndEOL();
93 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
95 virtual bool isVerboseAsm() const { return IsVerboseAsm; }
97 /// hasRawTextSupport - We support EmitRawText.
98 virtual bool hasRawTextSupport() const { return true; }
100 /// AddComment - Add a comment that can be emitted to the generated .s
101 /// file if applicable as a QoI issue to make the output of the compiler
102 /// more readable. This only affects the MCAsmStreamer, and only when
103 /// verbose assembly output is enabled.
104 virtual void AddComment(const Twine &T);
106 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
107 virtual void AddEncodingComment(const MCInst &Inst);
109 /// GetCommentOS - Return a raw_ostream that comments can be written to.
110 /// Unlike AddComment, you are required to terminate comments with \n if you
112 virtual raw_ostream &GetCommentOS() {
114 return nulls(); // Discard comments unless in verbose asm mode.
115 return CommentStream;
118 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
119 virtual void AddBlankLine() {
123 /// @name MCStreamer Interface
126 virtual void ChangeSection(const MCSection *Section,
127 const MCExpr *Subsection);
129 virtual void InitSections() {
133 virtual void InitToTextSection() {
134 SwitchSection(getContext().getObjectFileInfo()->getTextSection());
137 virtual void EmitLabel(MCSymbol *Symbol);
138 virtual void EmitDebugLabel(MCSymbol *Symbol);
140 virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
142 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
143 virtual void EmitLinkerOptions(ArrayRef<std::string> Options);
144 virtual void EmitDataRegion(MCDataRegionType Kind);
145 virtual void EmitThumbFunc(MCSymbol *Func);
147 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
148 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
149 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
150 const MCSymbol *LastLabel,
151 const MCSymbol *Label,
152 unsigned PointerSize);
153 virtual void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
154 const MCSymbol *Label);
156 virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
158 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
159 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
160 virtual void EmitCOFFSymbolStorageClass(int StorageClass);
161 virtual void EmitCOFFSymbolType(int Type);
162 virtual void EndCOFFSymbolDef();
163 virtual void EmitCOFFSectionIndex(MCSymbol const *Symbol);
164 virtual void EmitCOFFSecRel32(MCSymbol const *Symbol);
165 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
166 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
167 unsigned ByteAlignment);
169 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
171 /// @param Symbol - The common symbol to emit.
172 /// @param Size - The size of the common symbol.
173 /// @param ByteAlignment - The alignment of the common symbol in bytes.
174 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
175 unsigned ByteAlignment);
177 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
178 uint64_t Size = 0, unsigned ByteAlignment = 0);
180 virtual void EmitTBSSSymbol (const MCSection *Section, MCSymbol *Symbol,
181 uint64_t Size, unsigned ByteAlignment = 0);
183 virtual void EmitBytes(StringRef Data);
185 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size);
186 virtual void EmitIntValue(uint64_t Value, unsigned Size);
188 virtual void EmitULEB128Value(const MCExpr *Value);
190 virtual void EmitSLEB128Value(const MCExpr *Value);
192 virtual void EmitGPRel64Value(const MCExpr *Value);
194 virtual void EmitGPRel32Value(const MCExpr *Value);
197 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue);
199 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
200 unsigned ValueSize = 1,
201 unsigned MaxBytesToEmit = 0);
203 virtual void EmitCodeAlignment(unsigned ByteAlignment,
204 unsigned MaxBytesToEmit = 0);
206 virtual bool EmitValueToOffset(const MCExpr *Offset,
207 unsigned char Value = 0);
209 virtual void EmitFileDirective(StringRef Filename);
210 virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
211 StringRef Filename, unsigned CUID = 0);
212 virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
213 unsigned Column, unsigned Flags,
214 unsigned Isa, unsigned Discriminator,
217 virtual void EmitIdent(StringRef IdentString);
218 virtual void EmitCFISections(bool EH, bool Debug);
219 virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
220 virtual void EmitCFIDefCfaOffset(int64_t Offset);
221 virtual void EmitCFIDefCfaRegister(int64_t Register);
222 virtual void EmitCFIOffset(int64_t Register, int64_t Offset);
223 virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
224 virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
225 virtual void EmitCFIRememberState();
226 virtual void EmitCFIRestoreState();
227 virtual void EmitCFISameValue(int64_t Register);
228 virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
229 virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
230 virtual void EmitCFISignalFrame();
231 virtual void EmitCFIUndefined(int64_t Register);
232 virtual void EmitCFIRegister(int64_t Register1, int64_t Register2);
233 virtual void EmitCFIWindowSave();
235 virtual void EmitWin64EHStartProc(const MCSymbol *Symbol);
236 virtual void EmitWin64EHEndProc();
237 virtual void EmitWin64EHStartChained();
238 virtual void EmitWin64EHEndChained();
239 virtual void EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
241 virtual void EmitWin64EHHandlerData();
242 virtual void EmitWin64EHPushReg(unsigned Register);
243 virtual void EmitWin64EHSetFrame(unsigned Register, unsigned Offset);
244 virtual void EmitWin64EHAllocStack(unsigned Size);
245 virtual void EmitWin64EHSaveReg(unsigned Register, unsigned Offset);
246 virtual void EmitWin64EHSaveXMM(unsigned Register, unsigned Offset);
247 virtual void EmitWin64EHPushFrame(bool Code);
248 virtual void EmitWin64EHEndProlog();
250 virtual void EmitInstruction(const MCInst &Inst);
252 virtual void EmitBundleAlignMode(unsigned AlignPow2);
253 virtual void EmitBundleLock(bool AlignToEnd);
254 virtual void EmitBundleUnlock();
256 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
257 /// the specified string in the output .s file. This capability is
258 /// indicated by the hasRawTextSupport() predicate.
259 virtual void EmitRawTextImpl(StringRef String);
261 virtual void FinishImpl();
264 } // end anonymous namespace.
266 /// AddComment - Add a comment that can be emitted to the generated .s
267 /// file if applicable as a QoI issue to make the output of the compiler
268 /// more readable. This only affects the MCAsmStreamer, and only when
269 /// verbose assembly output is enabled.
270 void MCAsmStreamer::AddComment(const Twine &T) {
271 if (!IsVerboseAsm) return;
273 // Make sure that CommentStream is flushed.
274 CommentStream.flush();
276 T.toVector(CommentToEmit);
277 // Each comment goes on its own line.
278 CommentToEmit.push_back('\n');
280 // Tell the comment stream that the vector changed underneath it.
281 CommentStream.resync();
284 void MCAsmStreamer::EmitCommentsAndEOL() {
285 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
290 CommentStream.flush();
291 StringRef Comments = CommentToEmit.str();
293 assert(Comments.back() == '\n' &&
294 "Comment array not newline terminated");
296 // Emit a line of comments.
297 OS.PadToColumn(MAI->getCommentColumn());
298 size_t Position = Comments.find('\n');
299 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
301 Comments = Comments.substr(Position+1);
302 } while (!Comments.empty());
304 CommentToEmit.clear();
305 // Tell the comment stream that the vector changed underneath it.
306 CommentStream.resync();
309 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
310 assert(Bytes && "Invalid size!");
311 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
314 void MCAsmStreamer::ChangeSection(const MCSection *Section,
315 const MCExpr *Subsection) {
316 assert(Section && "Cannot switch to a null section!");
317 Section->PrintSwitchToSection(*MAI, OS, Subsection);
320 void MCAsmStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
321 MCSymbol *EHSymbol) {
325 unsigned Flags = FlagMap.lookup(Symbol);
327 if (Flags & EHGlobal)
328 EmitSymbolAttribute(EHSymbol, MCSA_Global);
329 if (Flags & EHWeakDefinition)
330 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
331 if (Flags & EHPrivateExtern)
332 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
335 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
336 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
337 MCStreamer::EmitLabel(Symbol);
339 OS << *Symbol << MAI->getLabelSuffix();
343 void MCAsmStreamer::EmitDebugLabel(MCSymbol *Symbol) {
344 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
345 MCStreamer::EmitDebugLabel(Symbol);
347 OS << *Symbol << MAI->getDebugLabelSuffix();
351 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
353 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
354 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
355 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
356 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
357 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
362 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
363 assert(!Options.empty() && "At least one option is required!");
364 OS << "\t.linker_option \"" << Options[0] << '"';
365 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
366 ie = Options.end(); it != ie; ++it) {
367 OS << ", " << '"' << *it << '"';
372 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
373 if (!MAI->doesSupportDataRegionDirectives())
376 case MCDR_DataRegion: OS << "\t.data_region"; break;
377 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
378 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
379 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
380 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
385 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
386 // This needs to emit to a temporary string to get properly quoted
387 // MCSymbols when they have spaces in them.
388 OS << "\t.thumb_func";
389 // Only Mach-O hasSubsectionsViaSymbols()
390 if (MAI->hasSubsectionsViaSymbols())
395 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
396 OS << *Symbol << " = " << *Value;
399 // FIXME: Lift context changes into super class.
400 Symbol->setVariableValue(Value);
403 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
404 OS << ".weakref " << *Alias << ", " << *Symbol;
408 void MCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
409 const MCSymbol *LastLabel,
410 const MCSymbol *Label,
411 unsigned PointerSize) {
412 EmitDwarfSetLineAddr(LineDelta, Label, PointerSize);
415 void MCAsmStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
416 const MCSymbol *Label) {
417 EmitIntValue(dwarf::DW_CFA_advance_loc4, 1);
418 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
419 AddrDelta = ForceExpAbs(AddrDelta);
420 EmitValue(AddrDelta, 4);
424 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
425 MCSymbolAttr Attribute) {
427 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
428 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
429 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
430 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
431 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
432 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
433 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
434 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
435 if (!MAI->hasDotTypeDotSizeDirective())
436 return false; // Symbol attribute not supported
437 OS << "\t.type\t" << *Symbol << ','
438 << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
440 default: return false;
441 case MCSA_ELF_TypeFunction: OS << "function"; break;
442 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
443 case MCSA_ELF_TypeObject: OS << "object"; break;
444 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
445 case MCSA_ELF_TypeCommon: OS << "common"; break;
446 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
447 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
451 case MCSA_Global: // .globl/.global
452 OS << MAI->getGlobalDirective();
453 FlagMap[Symbol] |= EHGlobal;
455 case MCSA_Hidden: OS << "\t.hidden\t"; break;
456 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
457 case MCSA_Internal: OS << "\t.internal\t"; break;
458 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
459 case MCSA_Local: OS << "\t.local\t"; break;
460 case MCSA_NoDeadStrip: OS << "\t.no_dead_strip\t"; break;
461 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
462 case MCSA_PrivateExtern:
463 OS << "\t.private_extern\t";
464 FlagMap[Symbol] |= EHPrivateExtern;
466 case MCSA_Protected: OS << "\t.protected\t"; break;
467 case MCSA_Reference: OS << "\t.reference\t"; break;
468 case MCSA_Weak: OS << "\t.weak\t"; break;
469 case MCSA_WeakDefinition:
470 OS << "\t.weak_definition\t";
471 FlagMap[Symbol] |= EHWeakDefinition;
474 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
475 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
484 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
485 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
489 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
490 OS << "\t.def\t " << *Symbol << ';';
494 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
495 OS << "\t.scl\t" << StorageClass << ';';
499 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
500 OS << "\t.type\t" << Type << ';';
504 void MCAsmStreamer::EndCOFFSymbolDef() {
509 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
510 OS << "\t.secidx\t" << *Symbol;
514 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) {
515 OS << "\t.secrel32\t" << *Symbol;
519 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
520 assert(MAI->hasDotTypeDotSizeDirective());
521 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
524 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
525 unsigned ByteAlignment) {
526 // Common symbols do not belong to any actual section.
527 AssignSection(Symbol, NULL);
529 OS << "\t.comm\t" << *Symbol << ',' << Size;
530 if (ByteAlignment != 0) {
531 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
532 OS << ',' << ByteAlignment;
534 OS << ',' << Log2_32(ByteAlignment);
539 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
541 /// @param Symbol - The common symbol to emit.
542 /// @param Size - The size of the common symbol.
543 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
544 unsigned ByteAlign) {
545 // Common symbols do not belong to any actual section.
546 AssignSection(Symbol, NULL);
548 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
550 switch (MAI->getLCOMMDirectiveAlignmentType()) {
551 case LCOMM::NoAlignment:
552 llvm_unreachable("alignment not supported on .lcomm!");
553 case LCOMM::ByteAlignment:
554 OS << ',' << ByteAlign;
556 case LCOMM::Log2Alignment:
557 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
558 OS << ',' << Log2_32(ByteAlign);
565 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
566 uint64_t Size, unsigned ByteAlignment) {
568 AssignSection(Symbol, Section);
570 // Note: a .zerofill directive does not switch sections.
573 // This is a mach-o specific directive.
574 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
575 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
577 if (Symbol != NULL) {
578 OS << ',' << *Symbol << ',' << Size;
579 if (ByteAlignment != 0)
580 OS << ',' << Log2_32(ByteAlignment);
585 // .tbss sym, size, align
586 // This depends that the symbol has already been mangled from the original,
588 void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
589 uint64_t Size, unsigned ByteAlignment) {
590 AssignSection(Symbol, Section);
592 assert(Symbol != NULL && "Symbol shouldn't be NULL!");
593 // Instead of using the Section we'll just use the shortcut.
594 // This is a mach-o specific directive and section.
595 OS << ".tbss " << *Symbol << ", " << Size;
597 // Output align if we have it. We default to 1 so don't bother printing
599 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
604 static inline char toOctal(int X) { return (X&7)+'0'; }
606 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
609 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
610 unsigned char C = Data[i];
611 if (C == '"' || C == '\\') {
612 OS << '\\' << (char)C;
616 if (isprint((unsigned char)C)) {
622 case '\b': OS << "\\b"; break;
623 case '\f': OS << "\\f"; break;
624 case '\n': OS << "\\n"; break;
625 case '\r': OS << "\\r"; break;
626 case '\t': OS << "\\t"; break;
629 OS << toOctal(C >> 6);
630 OS << toOctal(C >> 3);
631 OS << toOctal(C >> 0);
640 void MCAsmStreamer::EmitBytes(StringRef Data) {
641 assert(getCurrentSection().first &&
642 "Cannot emit contents before setting section!");
643 if (Data.empty()) return;
645 if (Data.size() == 1) {
646 OS << MAI->getData8bitsDirective();
647 OS << (unsigned)(unsigned char)Data[0];
652 // If the data ends with 0 and the target supports .asciz, use it, otherwise
654 if (MAI->getAscizDirective() && Data.back() == 0) {
655 OS << MAI->getAscizDirective();
656 Data = Data.substr(0, Data.size()-1);
658 OS << MAI->getAsciiDirective();
661 PrintQuotedString(Data, OS);
665 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
666 EmitValue(MCConstantExpr::Create(Value, getContext()), Size);
669 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size) {
670 assert(getCurrentSection().first &&
671 "Cannot emit contents before setting section!");
672 const char *Directive = 0;
675 case 1: Directive = MAI->getData8bitsDirective(); break;
676 case 2: Directive = MAI->getData16bitsDirective(); break;
677 case 4: Directive = MAI->getData32bitsDirective(); break;
679 Directive = MAI->getData64bitsDirective();
680 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
681 if (Directive) break;
683 if (!Value->EvaluateAsAbsolute(IntValue))
684 report_fatal_error("Don't know how to emit this value.");
685 if (MAI->isLittleEndian()) {
686 EmitIntValue((uint32_t)(IntValue >> 0 ), 4);
687 EmitIntValue((uint32_t)(IntValue >> 32), 4);
689 EmitIntValue((uint32_t)(IntValue >> 32), 4);
690 EmitIntValue((uint32_t)(IntValue >> 0 ), 4);
695 assert(Directive && "Invalid size for machine code value!");
696 OS << Directive << *Value;
700 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
702 if (Value->EvaluateAsAbsolute(IntValue)) {
703 EmitULEB128IntValue(IntValue);
706 assert(MAI->hasLEB128() && "Cannot print a .uleb");
707 OS << ".uleb128 " << *Value;
711 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
713 if (Value->EvaluateAsAbsolute(IntValue)) {
714 EmitSLEB128IntValue(IntValue);
717 assert(MAI->hasLEB128() && "Cannot print a .sleb");
718 OS << ".sleb128 " << *Value;
722 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
723 assert(MAI->getGPRel64Directive() != 0);
724 OS << MAI->getGPRel64Directive() << *Value;
728 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
729 assert(MAI->getGPRel32Directive() != 0);
730 OS << MAI->getGPRel32Directive() << *Value;
735 /// EmitFill - Emit NumBytes bytes worth of the value specified by
736 /// FillValue. This implements directives such as '.space'.
737 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
738 if (NumBytes == 0) return;
740 if (const char *ZeroDirective = MAI->getZeroDirective()) {
741 OS << ZeroDirective << NumBytes;
743 OS << ',' << (int)FillValue;
748 // Emit a byte at a time.
749 MCStreamer::EmitFill(NumBytes, FillValue);
752 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
754 unsigned MaxBytesToEmit) {
755 // Some assemblers don't support non-power of two alignments, so we always
756 // emit alignments as a power of two if possible.
757 if (isPowerOf2_32(ByteAlignment)) {
759 default: llvm_unreachable("Invalid size for machine code value!");
760 case 1: OS << MAI->getAlignDirective(); break;
761 // FIXME: use MAI for this!
762 case 2: OS << ".p2alignw "; break;
763 case 4: OS << ".p2alignl "; break;
764 case 8: llvm_unreachable("Unsupported alignment size!");
767 if (MAI->getAlignmentIsInBytes())
770 OS << Log2_32(ByteAlignment);
772 if (Value || MaxBytesToEmit) {
774 OS.write_hex(truncateToSize(Value, ValueSize));
777 OS << ", " << MaxBytesToEmit;
783 // Non-power of two alignment. This is not widely supported by assemblers.
784 // FIXME: Parameterize this based on MAI.
786 default: llvm_unreachable("Invalid size for machine code value!");
787 case 1: OS << ".balign"; break;
788 case 2: OS << ".balignw"; break;
789 case 4: OS << ".balignl"; break;
790 case 8: llvm_unreachable("Unsupported alignment size!");
793 OS << ' ' << ByteAlignment;
794 OS << ", " << truncateToSize(Value, ValueSize);
796 OS << ", " << MaxBytesToEmit;
800 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
801 unsigned MaxBytesToEmit) {
802 // Emit with a text fill value.
803 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
807 bool MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
808 unsigned char Value) {
809 // FIXME: Verify that Offset is associated with the current section.
810 OS << ".org " << *Offset << ", " << (unsigned) Value;
816 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
817 assert(MAI->hasSingleParameterDotFile());
819 PrintQuotedString(Filename, OS);
823 bool MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
824 StringRef Filename, unsigned CUID) {
825 if (!UseDwarfDirectory && !Directory.empty()) {
826 if (sys::path::is_absolute(Filename))
827 return EmitDwarfFileDirective(FileNo, "", Filename, CUID);
829 SmallString<128> FullPathName = Directory;
830 sys::path::append(FullPathName, Filename);
831 return EmitDwarfFileDirective(FileNo, "", FullPathName, CUID);
835 OS << "\t.file\t" << FileNo << ' ';
836 if (!Directory.empty()) {
837 PrintQuotedString(Directory, OS);
840 PrintQuotedString(Filename, OS);
842 // All .file will belong to a single CUID.
845 return this->MCStreamer::EmitDwarfFileDirective(FileNo, Directory, Filename,
849 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
850 unsigned Column, unsigned Flags,
852 unsigned Discriminator,
853 StringRef FileName) {
854 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
855 Isa, Discriminator, FileName);
859 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
860 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
861 OS << " basic_block";
862 if (Flags & DWARF2_FLAG_PROLOGUE_END)
863 OS << " prologue_end";
864 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
865 OS << " epilogue_begin";
867 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
868 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
871 if (Flags & DWARF2_FLAG_IS_STMT)
880 OS << "discriminator " << Discriminator;
883 OS.PadToColumn(MAI->getCommentColumn());
884 OS << MAI->getCommentString() << ' ' << FileName << ':'
885 << Line << ':' << Column;
890 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
891 assert(MAI->hasIdentDirective() && ".ident directive not supported");
893 PrintQuotedString(IdentString, OS);
897 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
898 MCStreamer::EmitCFISections(EH, Debug);
903 OS << "\t.cfi_sections ";
907 OS << ", .debug_frame";
909 OS << ".debug_frame";
915 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
917 RecordProcStart(Frame);
921 OS << "\t.cfi_startproc";
925 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
927 RecordProcEnd(Frame);
931 // Put a dummy non-null value in Frame.End to mark that this frame has been
933 Frame.End = (MCSymbol *) 1;
935 OS << "\t.cfi_endproc";
939 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
940 if (InstPrinter && !MAI->useDwarfRegNumForCFI()) {
941 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
942 unsigned LLVMRegister = MRI->getLLVMRegNum(Register, true);
943 InstPrinter->printRegName(OS, LLVMRegister);
949 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
950 MCStreamer::EmitCFIDefCfa(Register, Offset);
955 OS << "\t.cfi_def_cfa ";
956 EmitRegisterName(Register);
957 OS << ", " << Offset;
961 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
962 MCStreamer::EmitCFIDefCfaOffset(Offset);
967 OS << "\t.cfi_def_cfa_offset " << Offset;
971 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
972 MCStreamer::EmitCFIDefCfaRegister(Register);
977 OS << "\t.cfi_def_cfa_register ";
978 EmitRegisterName(Register);
982 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
983 this->MCStreamer::EmitCFIOffset(Register, Offset);
988 OS << "\t.cfi_offset ";
989 EmitRegisterName(Register);
990 OS << ", " << Offset;
994 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
996 MCStreamer::EmitCFIPersonality(Sym, Encoding);
1001 OS << "\t.cfi_personality " << Encoding << ", " << *Sym;
1005 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1006 MCStreamer::EmitCFILsda(Sym, Encoding);
1011 OS << "\t.cfi_lsda " << Encoding << ", " << *Sym;
1015 void MCAsmStreamer::EmitCFIRememberState() {
1016 MCStreamer::EmitCFIRememberState();
1021 OS << "\t.cfi_remember_state";
1025 void MCAsmStreamer::EmitCFIRestoreState() {
1026 MCStreamer::EmitCFIRestoreState();
1031 OS << "\t.cfi_restore_state";
1035 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1036 MCStreamer::EmitCFISameValue(Register);
1041 OS << "\t.cfi_same_value ";
1042 EmitRegisterName(Register);
1046 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1047 MCStreamer::EmitCFIRelOffset(Register, Offset);
1052 OS << "\t.cfi_rel_offset ";
1053 EmitRegisterName(Register);
1054 OS << ", " << Offset;
1058 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1059 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1064 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1068 void MCAsmStreamer::EmitCFISignalFrame() {
1069 MCStreamer::EmitCFISignalFrame();
1074 OS << "\t.cfi_signal_frame";
1078 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1079 MCStreamer::EmitCFIUndefined(Register);
1084 OS << "\t.cfi_undefined " << Register;
1088 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1089 MCStreamer::EmitCFIRegister(Register1, Register2);
1094 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1098 void MCAsmStreamer::EmitCFIWindowSave() {
1099 MCStreamer::EmitCFIWindowSave();
1104 OS << "\t.cfi_window_save";
1108 void MCAsmStreamer::EmitWin64EHStartProc(const MCSymbol *Symbol) {
1109 MCStreamer::EmitWin64EHStartProc(Symbol);
1111 OS << ".seh_proc " << *Symbol;
1115 void MCAsmStreamer::EmitWin64EHEndProc() {
1116 MCStreamer::EmitWin64EHEndProc();
1118 OS << "\t.seh_endproc";
1122 void MCAsmStreamer::EmitWin64EHStartChained() {
1123 MCStreamer::EmitWin64EHStartChained();
1125 OS << "\t.seh_startchained";
1129 void MCAsmStreamer::EmitWin64EHEndChained() {
1130 MCStreamer::EmitWin64EHEndChained();
1132 OS << "\t.seh_endchained";
1136 void MCAsmStreamer::EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
1138 MCStreamer::EmitWin64EHHandler(Sym, Unwind, Except);
1140 OS << "\t.seh_handler " << *Sym;
1148 static const MCSection *getWin64EHTableSection(StringRef suffix,
1149 MCContext &context) {
1150 // FIXME: This doesn't belong in MCObjectFileInfo. However,
1151 /// this duplicate code in MCWin64EH.cpp.
1153 return context.getObjectFileInfo()->getXDataSection();
1154 return context.getCOFFSection((".xdata"+suffix).str(),
1155 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1156 COFF::IMAGE_SCN_MEM_READ |
1157 COFF::IMAGE_SCN_MEM_WRITE,
1158 SectionKind::getDataRel());
1161 void MCAsmStreamer::EmitWin64EHHandlerData() {
1162 MCStreamer::EmitWin64EHHandlerData();
1164 // Switch sections. Don't call SwitchSection directly, because that will
1165 // cause the section switch to be visible in the emitted assembly.
1166 // We only do this so the section switch that terminates the handler
1167 // data block is visible.
1168 MCWin64EHUnwindInfo *CurFrame = getCurrentW64UnwindInfo();
1169 StringRef suffix=MCWin64EHUnwindEmitter::GetSectionSuffix(CurFrame->Function);
1170 const MCSection *xdataSect = getWin64EHTableSection(suffix, getContext());
1172 SwitchSectionNoChange(xdataSect);
1174 OS << "\t.seh_handlerdata";
1178 void MCAsmStreamer::EmitWin64EHPushReg(unsigned Register) {
1179 MCStreamer::EmitWin64EHPushReg(Register);
1181 OS << "\t.seh_pushreg " << Register;
1185 void MCAsmStreamer::EmitWin64EHSetFrame(unsigned Register, unsigned Offset) {
1186 MCStreamer::EmitWin64EHSetFrame(Register, Offset);
1188 OS << "\t.seh_setframe " << Register << ", " << Offset;
1192 void MCAsmStreamer::EmitWin64EHAllocStack(unsigned Size) {
1193 MCStreamer::EmitWin64EHAllocStack(Size);
1195 OS << "\t.seh_stackalloc " << Size;
1199 void MCAsmStreamer::EmitWin64EHSaveReg(unsigned Register, unsigned Offset) {
1200 MCStreamer::EmitWin64EHSaveReg(Register, Offset);
1202 OS << "\t.seh_savereg " << Register << ", " << Offset;
1206 void MCAsmStreamer::EmitWin64EHSaveXMM(unsigned Register, unsigned Offset) {
1207 MCStreamer::EmitWin64EHSaveXMM(Register, Offset);
1209 OS << "\t.seh_savexmm " << Register << ", " << Offset;
1213 void MCAsmStreamer::EmitWin64EHPushFrame(bool Code) {
1214 MCStreamer::EmitWin64EHPushFrame(Code);
1216 OS << "\t.seh_pushframe";
1222 void MCAsmStreamer::EmitWin64EHEndProlog(void) {
1223 MCStreamer::EmitWin64EHEndProlog();
1225 OS << "\t.seh_endprologue";
1229 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst) {
1230 raw_ostream &OS = GetCommentOS();
1231 SmallString<256> Code;
1232 SmallVector<MCFixup, 4> Fixups;
1233 raw_svector_ostream VecOS(Code);
1234 Emitter->EncodeInstruction(Inst, VecOS, Fixups);
1237 // If we are showing fixups, create symbolic markers in the encoded
1238 // representation. We do this by making a per-bit map to the fixup item index,
1239 // then trying to display it as nicely as possible.
1240 SmallVector<uint8_t, 64> FixupMap;
1241 FixupMap.resize(Code.size() * 8);
1242 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1245 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1246 MCFixup &F = Fixups[i];
1247 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1248 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1249 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1250 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1251 FixupMap[Index] = 1 + i;
1255 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1256 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1257 OS << "encoding: [";
1258 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1262 // See if all bits are the same map entry.
1263 uint8_t MapEntry = FixupMap[i * 8 + 0];
1264 for (unsigned j = 1; j != 8; ++j) {
1265 if (FixupMap[i * 8 + j] == MapEntry)
1268 MapEntry = uint8_t(~0U);
1272 if (MapEntry != uint8_t(~0U)) {
1273 if (MapEntry == 0) {
1274 OS << format("0x%02x", uint8_t(Code[i]));
1277 // FIXME: Some of the 8 bits require fix up.
1278 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1279 << char('A' + MapEntry - 1) << '\'';
1281 OS << char('A' + MapEntry - 1);
1284 // Otherwise, write out in binary.
1286 for (unsigned j = 8; j--;) {
1287 unsigned Bit = (Code[i] >> j) & 1;
1290 if (MAI->isLittleEndian())
1291 FixupBit = i * 8 + j;
1293 FixupBit = i * 8 + (7-j);
1295 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1296 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1297 OS << char('A' + MapEntry - 1);
1305 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1306 MCFixup &F = Fixups[i];
1307 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1308 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1309 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1313 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
1314 assert(getCurrentSection().first &&
1315 "Cannot emit contents before setting section!");
1317 // Show the encoding in a comment if we have a code emitter.
1319 AddEncodingComment(Inst);
1321 // Show the MCInst if enabled.
1323 Inst.dump_pretty(GetCommentOS(), MAI, InstPrinter.get(), "\n ");
1324 GetCommentOS() << "\n";
1327 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
1329 InstPrinter->printInst(&Inst, OS, "");
1331 Inst.print(OS, MAI);
1335 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1336 OS << "\t.bundle_align_mode " << AlignPow2;
1340 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1341 OS << "\t.bundle_lock";
1343 OS << " align_to_end";
1347 void MCAsmStreamer::EmitBundleUnlock() {
1348 OS << "\t.bundle_unlock";
1352 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1353 /// the specified string in the output .s file. This capability is
1354 /// indicated by the hasRawTextSupport() predicate.
1355 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1356 if (!String.empty() && String.back() == '\n')
1357 String = String.substr(0, String.size()-1);
1362 void MCAsmStreamer::FinishImpl() {
1363 // FIXME: This header is duplicated with MCObjectStreamer
1364 // Dump out the dwarf file & directory tables and line tables.
1365 const MCSymbol *LineSectionSymbol = NULL;
1366 if (getContext().hasDwarfFiles() && !UseLoc)
1367 LineSectionSymbol = MCDwarfFileTable::Emit(this);
1369 // If we are generating dwarf for assembly source files dump out the sections.
1370 if (getContext().getGenDwarfForAssembly())
1371 MCGenDwarfInfo::Emit(this, LineSectionSymbol);
1374 EmitFrames(AsmBackend.get(), false);
1377 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1378 MCTargetStreamer *TargetStreamer,
1379 formatted_raw_ostream &OS,
1380 bool isVerboseAsm, bool useLoc, bool useCFI,
1381 bool useDwarfDirectory, MCInstPrinter *IP,
1382 MCCodeEmitter *CE, MCAsmBackend *MAB,
1384 return new MCAsmStreamer(Context, TargetStreamer, OS, isVerboseAsm, useLoc,
1385 useCFI, useDwarfDirectory, IP, CE, MAB, ShowInst);