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 void emitRawComment(const Twine &T, bool TabPrefix = true) LLVM_OVERRIDE;
120 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
121 virtual void AddBlankLine() {
125 /// @name MCStreamer Interface
128 virtual void ChangeSection(const MCSection *Section,
129 const MCExpr *Subsection);
131 virtual void InitSections() {
135 virtual void InitToTextSection() {
136 SwitchSection(getContext().getObjectFileInfo()->getTextSection());
139 virtual void EmitLabel(MCSymbol *Symbol);
140 virtual void EmitDebugLabel(MCSymbol *Symbol);
142 virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
144 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
145 virtual void EmitLinkerOptions(ArrayRef<std::string> Options);
146 virtual void EmitDataRegion(MCDataRegionType Kind);
147 virtual void EmitThumbFunc(MCSymbol *Func);
149 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
150 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
151 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
152 const MCSymbol *LastLabel,
153 const MCSymbol *Label,
154 unsigned PointerSize);
155 virtual void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
156 const MCSymbol *Label);
158 virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
160 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
161 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
162 virtual void EmitCOFFSymbolStorageClass(int StorageClass);
163 virtual void EmitCOFFSymbolType(int Type);
164 virtual void EndCOFFSymbolDef();
165 virtual void EmitCOFFSectionIndex(MCSymbol const *Symbol);
166 virtual void EmitCOFFSecRel32(MCSymbol const *Symbol);
167 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
168 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
169 unsigned ByteAlignment);
171 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
173 /// @param Symbol - The common symbol to emit.
174 /// @param Size - The size of the common symbol.
175 /// @param ByteAlignment - The alignment of the common symbol in bytes.
176 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
177 unsigned ByteAlignment);
179 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
180 uint64_t Size = 0, unsigned ByteAlignment = 0);
182 virtual void EmitTBSSSymbol (const MCSection *Section, MCSymbol *Symbol,
183 uint64_t Size, unsigned ByteAlignment = 0);
185 virtual void EmitBytes(StringRef Data);
187 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size);
188 virtual void EmitIntValue(uint64_t Value, unsigned Size);
190 virtual void EmitULEB128Value(const MCExpr *Value);
192 virtual void EmitSLEB128Value(const MCExpr *Value);
194 virtual void EmitGPRel64Value(const MCExpr *Value);
196 virtual void EmitGPRel32Value(const MCExpr *Value);
199 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue);
201 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
202 unsigned ValueSize = 1,
203 unsigned MaxBytesToEmit = 0);
205 virtual void EmitCodeAlignment(unsigned ByteAlignment,
206 unsigned MaxBytesToEmit = 0);
208 virtual bool EmitValueToOffset(const MCExpr *Offset,
209 unsigned char Value = 0);
211 virtual void EmitFileDirective(StringRef Filename);
212 virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
213 StringRef Filename, unsigned CUID = 0);
214 virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
215 unsigned Column, unsigned Flags,
216 unsigned Isa, unsigned Discriminator,
219 virtual void EmitIdent(StringRef IdentString);
220 virtual void EmitCFISections(bool EH, bool Debug);
221 virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
222 virtual void EmitCFIDefCfaOffset(int64_t Offset);
223 virtual void EmitCFIDefCfaRegister(int64_t Register);
224 virtual void EmitCFIOffset(int64_t Register, int64_t Offset);
225 virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
226 virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
227 virtual void EmitCFIRememberState();
228 virtual void EmitCFIRestoreState();
229 virtual void EmitCFISameValue(int64_t Register);
230 virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
231 virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
232 virtual void EmitCFISignalFrame();
233 virtual void EmitCFIUndefined(int64_t Register);
234 virtual void EmitCFIRegister(int64_t Register1, int64_t Register2);
235 virtual void EmitCFIWindowSave();
237 virtual void EmitWin64EHStartProc(const MCSymbol *Symbol);
238 virtual void EmitWin64EHEndProc();
239 virtual void EmitWin64EHStartChained();
240 virtual void EmitWin64EHEndChained();
241 virtual void EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
243 virtual void EmitWin64EHHandlerData();
244 virtual void EmitWin64EHPushReg(unsigned Register);
245 virtual void EmitWin64EHSetFrame(unsigned Register, unsigned Offset);
246 virtual void EmitWin64EHAllocStack(unsigned Size);
247 virtual void EmitWin64EHSaveReg(unsigned Register, unsigned Offset);
248 virtual void EmitWin64EHSaveXMM(unsigned Register, unsigned Offset);
249 virtual void EmitWin64EHPushFrame(bool Code);
250 virtual void EmitWin64EHEndProlog();
252 virtual void EmitInstruction(const MCInst &Inst);
254 virtual void EmitBundleAlignMode(unsigned AlignPow2);
255 virtual void EmitBundleLock(bool AlignToEnd);
256 virtual void EmitBundleUnlock();
258 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
259 /// the specified string in the output .s file. This capability is
260 /// indicated by the hasRawTextSupport() predicate.
261 virtual void EmitRawTextImpl(StringRef String);
263 virtual void FinishImpl();
266 } // end anonymous namespace.
268 /// AddComment - Add a comment that can be emitted to the generated .s
269 /// file if applicable as a QoI issue to make the output of the compiler
270 /// more readable. This only affects the MCAsmStreamer, and only when
271 /// verbose assembly output is enabled.
272 void MCAsmStreamer::AddComment(const Twine &T) {
273 if (!IsVerboseAsm) return;
275 // Make sure that CommentStream is flushed.
276 CommentStream.flush();
278 T.toVector(CommentToEmit);
279 // Each comment goes on its own line.
280 CommentToEmit.push_back('\n');
282 // Tell the comment stream that the vector changed underneath it.
283 CommentStream.resync();
286 void MCAsmStreamer::EmitCommentsAndEOL() {
287 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
292 CommentStream.flush();
293 StringRef Comments = CommentToEmit.str();
295 assert(Comments.back() == '\n' &&
296 "Comment array not newline terminated");
298 // Emit a line of comments.
299 OS.PadToColumn(MAI->getCommentColumn());
300 size_t Position = Comments.find('\n');
301 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
303 Comments = Comments.substr(Position+1);
304 } while (!Comments.empty());
306 CommentToEmit.clear();
307 // Tell the comment stream that the vector changed underneath it.
308 CommentStream.resync();
311 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
312 assert(Bytes && "Invalid size!");
313 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
316 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
319 OS << MAI->getCommentString() << T;
323 void MCAsmStreamer::ChangeSection(const MCSection *Section,
324 const MCExpr *Subsection) {
325 assert(Section && "Cannot switch to a null section!");
326 Section->PrintSwitchToSection(*MAI, OS, Subsection);
329 void MCAsmStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
330 MCSymbol *EHSymbol) {
334 unsigned Flags = FlagMap.lookup(Symbol);
336 if (Flags & EHGlobal)
337 EmitSymbolAttribute(EHSymbol, MCSA_Global);
338 if (Flags & EHWeakDefinition)
339 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
340 if (Flags & EHPrivateExtern)
341 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
344 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
345 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
346 MCStreamer::EmitLabel(Symbol);
348 OS << *Symbol << MAI->getLabelSuffix();
352 void MCAsmStreamer::EmitDebugLabel(MCSymbol *Symbol) {
353 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
354 MCStreamer::EmitDebugLabel(Symbol);
356 OS << *Symbol << MAI->getDebugLabelSuffix();
360 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
362 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
363 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
364 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
365 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
366 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
371 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
372 assert(!Options.empty() && "At least one option is required!");
373 OS << "\t.linker_option \"" << Options[0] << '"';
374 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
375 ie = Options.end(); it != ie; ++it) {
376 OS << ", " << '"' << *it << '"';
381 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
382 if (!MAI->doesSupportDataRegionDirectives())
385 case MCDR_DataRegion: OS << "\t.data_region"; break;
386 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
387 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
388 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
389 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
394 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
395 // This needs to emit to a temporary string to get properly quoted
396 // MCSymbols when they have spaces in them.
397 OS << "\t.thumb_func";
398 // Only Mach-O hasSubsectionsViaSymbols()
399 if (MAI->hasSubsectionsViaSymbols())
404 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
405 OS << *Symbol << " = " << *Value;
408 // FIXME: Lift context changes into super class.
409 Symbol->setVariableValue(Value);
412 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
413 OS << ".weakref " << *Alias << ", " << *Symbol;
417 void MCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
418 const MCSymbol *LastLabel,
419 const MCSymbol *Label,
420 unsigned PointerSize) {
421 EmitDwarfSetLineAddr(LineDelta, Label, PointerSize);
424 void MCAsmStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
425 const MCSymbol *Label) {
426 EmitIntValue(dwarf::DW_CFA_advance_loc4, 1);
427 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
428 AddrDelta = ForceExpAbs(AddrDelta);
429 EmitValue(AddrDelta, 4);
433 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
434 MCSymbolAttr Attribute) {
436 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
437 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
438 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
439 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
440 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
441 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
442 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
443 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
444 if (!MAI->hasDotTypeDotSizeDirective())
445 return false; // Symbol attribute not supported
446 OS << "\t.type\t" << *Symbol << ','
447 << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
449 default: return false;
450 case MCSA_ELF_TypeFunction: OS << "function"; break;
451 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
452 case MCSA_ELF_TypeObject: OS << "object"; break;
453 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
454 case MCSA_ELF_TypeCommon: OS << "common"; break;
455 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
456 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
460 case MCSA_Global: // .globl/.global
461 OS << MAI->getGlobalDirective();
462 FlagMap[Symbol] |= EHGlobal;
464 case MCSA_Hidden: OS << "\t.hidden\t"; break;
465 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
466 case MCSA_Internal: OS << "\t.internal\t"; break;
467 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
468 case MCSA_Local: OS << "\t.local\t"; break;
469 case MCSA_NoDeadStrip: OS << "\t.no_dead_strip\t"; break;
470 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
471 case MCSA_PrivateExtern:
472 OS << "\t.private_extern\t";
473 FlagMap[Symbol] |= EHPrivateExtern;
475 case MCSA_Protected: OS << "\t.protected\t"; break;
476 case MCSA_Reference: OS << "\t.reference\t"; break;
477 case MCSA_Weak: OS << "\t.weak\t"; break;
478 case MCSA_WeakDefinition:
479 OS << "\t.weak_definition\t";
480 FlagMap[Symbol] |= EHWeakDefinition;
483 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
484 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
493 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
494 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
498 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
499 OS << "\t.def\t " << *Symbol << ';';
503 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
504 OS << "\t.scl\t" << StorageClass << ';';
508 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
509 OS << "\t.type\t" << Type << ';';
513 void MCAsmStreamer::EndCOFFSymbolDef() {
518 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
519 OS << "\t.secidx\t" << *Symbol;
523 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) {
524 OS << "\t.secrel32\t" << *Symbol;
528 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
529 assert(MAI->hasDotTypeDotSizeDirective());
530 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
533 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
534 unsigned ByteAlignment) {
535 // Common symbols do not belong to any actual section.
536 AssignSection(Symbol, NULL);
538 OS << "\t.comm\t" << *Symbol << ',' << Size;
539 if (ByteAlignment != 0) {
540 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
541 OS << ',' << ByteAlignment;
543 OS << ',' << Log2_32(ByteAlignment);
548 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
550 /// @param Symbol - The common symbol to emit.
551 /// @param Size - The size of the common symbol.
552 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
553 unsigned ByteAlign) {
554 // Common symbols do not belong to any actual section.
555 AssignSection(Symbol, NULL);
557 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
559 switch (MAI->getLCOMMDirectiveAlignmentType()) {
560 case LCOMM::NoAlignment:
561 llvm_unreachable("alignment not supported on .lcomm!");
562 case LCOMM::ByteAlignment:
563 OS << ',' << ByteAlign;
565 case LCOMM::Log2Alignment:
566 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
567 OS << ',' << Log2_32(ByteAlign);
574 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
575 uint64_t Size, unsigned ByteAlignment) {
577 AssignSection(Symbol, Section);
579 // Note: a .zerofill directive does not switch sections.
582 // This is a mach-o specific directive.
583 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
584 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
586 if (Symbol != NULL) {
587 OS << ',' << *Symbol << ',' << Size;
588 if (ByteAlignment != 0)
589 OS << ',' << Log2_32(ByteAlignment);
594 // .tbss sym, size, align
595 // This depends that the symbol has already been mangled from the original,
597 void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
598 uint64_t Size, unsigned ByteAlignment) {
599 AssignSection(Symbol, Section);
601 assert(Symbol != NULL && "Symbol shouldn't be NULL!");
602 // Instead of using the Section we'll just use the shortcut.
603 // This is a mach-o specific directive and section.
604 OS << ".tbss " << *Symbol << ", " << Size;
606 // Output align if we have it. We default to 1 so don't bother printing
608 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
613 static inline char toOctal(int X) { return (X&7)+'0'; }
615 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
618 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
619 unsigned char C = Data[i];
620 if (C == '"' || C == '\\') {
621 OS << '\\' << (char)C;
625 if (isprint((unsigned char)C)) {
631 case '\b': OS << "\\b"; break;
632 case '\f': OS << "\\f"; break;
633 case '\n': OS << "\\n"; break;
634 case '\r': OS << "\\r"; break;
635 case '\t': OS << "\\t"; break;
638 OS << toOctal(C >> 6);
639 OS << toOctal(C >> 3);
640 OS << toOctal(C >> 0);
649 void MCAsmStreamer::EmitBytes(StringRef Data) {
650 assert(getCurrentSection().first &&
651 "Cannot emit contents before setting section!");
652 if (Data.empty()) return;
654 if (Data.size() == 1) {
655 OS << MAI->getData8bitsDirective();
656 OS << (unsigned)(unsigned char)Data[0];
661 // If the data ends with 0 and the target supports .asciz, use it, otherwise
663 if (MAI->getAscizDirective() && Data.back() == 0) {
664 OS << MAI->getAscizDirective();
665 Data = Data.substr(0, Data.size()-1);
667 OS << MAI->getAsciiDirective();
670 PrintQuotedString(Data, OS);
674 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
675 EmitValue(MCConstantExpr::Create(Value, getContext()), Size);
678 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size) {
679 assert(getCurrentSection().first &&
680 "Cannot emit contents before setting section!");
681 const char *Directive = 0;
684 case 1: Directive = MAI->getData8bitsDirective(); break;
685 case 2: Directive = MAI->getData16bitsDirective(); break;
686 case 4: Directive = MAI->getData32bitsDirective(); break;
688 Directive = MAI->getData64bitsDirective();
689 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
690 if (Directive) break;
692 if (!Value->EvaluateAsAbsolute(IntValue))
693 report_fatal_error("Don't know how to emit this value.");
694 if (MAI->isLittleEndian()) {
695 EmitIntValue((uint32_t)(IntValue >> 0 ), 4);
696 EmitIntValue((uint32_t)(IntValue >> 32), 4);
698 EmitIntValue((uint32_t)(IntValue >> 32), 4);
699 EmitIntValue((uint32_t)(IntValue >> 0 ), 4);
704 assert(Directive && "Invalid size for machine code value!");
705 OS << Directive << *Value;
709 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
711 if (Value->EvaluateAsAbsolute(IntValue)) {
712 EmitULEB128IntValue(IntValue);
715 assert(MAI->hasLEB128() && "Cannot print a .uleb");
716 OS << ".uleb128 " << *Value;
720 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
722 if (Value->EvaluateAsAbsolute(IntValue)) {
723 EmitSLEB128IntValue(IntValue);
726 assert(MAI->hasLEB128() && "Cannot print a .sleb");
727 OS << ".sleb128 " << *Value;
731 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
732 assert(MAI->getGPRel64Directive() != 0);
733 OS << MAI->getGPRel64Directive() << *Value;
737 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
738 assert(MAI->getGPRel32Directive() != 0);
739 OS << MAI->getGPRel32Directive() << *Value;
744 /// EmitFill - Emit NumBytes bytes worth of the value specified by
745 /// FillValue. This implements directives such as '.space'.
746 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
747 if (NumBytes == 0) return;
749 if (const char *ZeroDirective = MAI->getZeroDirective()) {
750 OS << ZeroDirective << NumBytes;
752 OS << ',' << (int)FillValue;
757 // Emit a byte at a time.
758 MCStreamer::EmitFill(NumBytes, FillValue);
761 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
763 unsigned MaxBytesToEmit) {
764 // Some assemblers don't support non-power of two alignments, so we always
765 // emit alignments as a power of two if possible.
766 if (isPowerOf2_32(ByteAlignment)) {
768 default: llvm_unreachable("Invalid size for machine code value!");
769 case 1: OS << MAI->getAlignDirective(); break;
770 // FIXME: use MAI for this!
771 case 2: OS << ".p2alignw "; break;
772 case 4: OS << ".p2alignl "; break;
773 case 8: llvm_unreachable("Unsupported alignment size!");
776 if (MAI->getAlignmentIsInBytes())
779 OS << Log2_32(ByteAlignment);
781 if (Value || MaxBytesToEmit) {
783 OS.write_hex(truncateToSize(Value, ValueSize));
786 OS << ", " << MaxBytesToEmit;
792 // Non-power of two alignment. This is not widely supported by assemblers.
793 // FIXME: Parameterize this based on MAI.
795 default: llvm_unreachable("Invalid size for machine code value!");
796 case 1: OS << ".balign"; break;
797 case 2: OS << ".balignw"; break;
798 case 4: OS << ".balignl"; break;
799 case 8: llvm_unreachable("Unsupported alignment size!");
802 OS << ' ' << ByteAlignment;
803 OS << ", " << truncateToSize(Value, ValueSize);
805 OS << ", " << MaxBytesToEmit;
809 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
810 unsigned MaxBytesToEmit) {
811 // Emit with a text fill value.
812 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
816 bool MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
817 unsigned char Value) {
818 // FIXME: Verify that Offset is associated with the current section.
819 OS << ".org " << *Offset << ", " << (unsigned) Value;
825 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
826 assert(MAI->hasSingleParameterDotFile());
828 PrintQuotedString(Filename, OS);
832 bool MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
833 StringRef Filename, unsigned CUID) {
834 if (!UseDwarfDirectory && !Directory.empty()) {
835 if (sys::path::is_absolute(Filename))
836 return EmitDwarfFileDirective(FileNo, "", Filename, CUID);
838 SmallString<128> FullPathName = Directory;
839 sys::path::append(FullPathName, Filename);
840 return EmitDwarfFileDirective(FileNo, "", FullPathName, CUID);
844 OS << "\t.file\t" << FileNo << ' ';
845 if (!Directory.empty()) {
846 PrintQuotedString(Directory, OS);
849 PrintQuotedString(Filename, OS);
851 // All .file will belong to a single CUID.
854 return this->MCStreamer::EmitDwarfFileDirective(FileNo, Directory, Filename,
858 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
859 unsigned Column, unsigned Flags,
861 unsigned Discriminator,
862 StringRef FileName) {
863 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
864 Isa, Discriminator, FileName);
868 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
869 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
870 OS << " basic_block";
871 if (Flags & DWARF2_FLAG_PROLOGUE_END)
872 OS << " prologue_end";
873 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
874 OS << " epilogue_begin";
876 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
877 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
880 if (Flags & DWARF2_FLAG_IS_STMT)
889 OS << "discriminator " << Discriminator;
892 OS.PadToColumn(MAI->getCommentColumn());
893 OS << MAI->getCommentString() << ' ' << FileName << ':'
894 << Line << ':' << Column;
899 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
900 assert(MAI->hasIdentDirective() && ".ident directive not supported");
902 PrintQuotedString(IdentString, OS);
906 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
907 MCStreamer::EmitCFISections(EH, Debug);
912 OS << "\t.cfi_sections ";
916 OS << ", .debug_frame";
918 OS << ".debug_frame";
924 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
926 RecordProcStart(Frame);
930 OS << "\t.cfi_startproc";
934 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
936 RecordProcEnd(Frame);
940 // Put a dummy non-null value in Frame.End to mark that this frame has been
942 Frame.End = (MCSymbol *) 1;
944 OS << "\t.cfi_endproc";
948 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
949 if (InstPrinter && !MAI->useDwarfRegNumForCFI()) {
950 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
951 unsigned LLVMRegister = MRI->getLLVMRegNum(Register, true);
952 InstPrinter->printRegName(OS, LLVMRegister);
958 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
959 MCStreamer::EmitCFIDefCfa(Register, Offset);
964 OS << "\t.cfi_def_cfa ";
965 EmitRegisterName(Register);
966 OS << ", " << Offset;
970 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
971 MCStreamer::EmitCFIDefCfaOffset(Offset);
976 OS << "\t.cfi_def_cfa_offset " << Offset;
980 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
981 MCStreamer::EmitCFIDefCfaRegister(Register);
986 OS << "\t.cfi_def_cfa_register ";
987 EmitRegisterName(Register);
991 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
992 this->MCStreamer::EmitCFIOffset(Register, Offset);
997 OS << "\t.cfi_offset ";
998 EmitRegisterName(Register);
999 OS << ", " << Offset;
1003 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1004 unsigned Encoding) {
1005 MCStreamer::EmitCFIPersonality(Sym, Encoding);
1010 OS << "\t.cfi_personality " << Encoding << ", " << *Sym;
1014 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1015 MCStreamer::EmitCFILsda(Sym, Encoding);
1020 OS << "\t.cfi_lsda " << Encoding << ", " << *Sym;
1024 void MCAsmStreamer::EmitCFIRememberState() {
1025 MCStreamer::EmitCFIRememberState();
1030 OS << "\t.cfi_remember_state";
1034 void MCAsmStreamer::EmitCFIRestoreState() {
1035 MCStreamer::EmitCFIRestoreState();
1040 OS << "\t.cfi_restore_state";
1044 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1045 MCStreamer::EmitCFISameValue(Register);
1050 OS << "\t.cfi_same_value ";
1051 EmitRegisterName(Register);
1055 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1056 MCStreamer::EmitCFIRelOffset(Register, Offset);
1061 OS << "\t.cfi_rel_offset ";
1062 EmitRegisterName(Register);
1063 OS << ", " << Offset;
1067 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1068 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1073 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1077 void MCAsmStreamer::EmitCFISignalFrame() {
1078 MCStreamer::EmitCFISignalFrame();
1083 OS << "\t.cfi_signal_frame";
1087 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1088 MCStreamer::EmitCFIUndefined(Register);
1093 OS << "\t.cfi_undefined " << Register;
1097 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1098 MCStreamer::EmitCFIRegister(Register1, Register2);
1103 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1107 void MCAsmStreamer::EmitCFIWindowSave() {
1108 MCStreamer::EmitCFIWindowSave();
1113 OS << "\t.cfi_window_save";
1117 void MCAsmStreamer::EmitWin64EHStartProc(const MCSymbol *Symbol) {
1118 MCStreamer::EmitWin64EHStartProc(Symbol);
1120 OS << ".seh_proc " << *Symbol;
1124 void MCAsmStreamer::EmitWin64EHEndProc() {
1125 MCStreamer::EmitWin64EHEndProc();
1127 OS << "\t.seh_endproc";
1131 void MCAsmStreamer::EmitWin64EHStartChained() {
1132 MCStreamer::EmitWin64EHStartChained();
1134 OS << "\t.seh_startchained";
1138 void MCAsmStreamer::EmitWin64EHEndChained() {
1139 MCStreamer::EmitWin64EHEndChained();
1141 OS << "\t.seh_endchained";
1145 void MCAsmStreamer::EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
1147 MCStreamer::EmitWin64EHHandler(Sym, Unwind, Except);
1149 OS << "\t.seh_handler " << *Sym;
1157 static const MCSection *getWin64EHTableSection(StringRef suffix,
1158 MCContext &context) {
1159 // FIXME: This doesn't belong in MCObjectFileInfo. However,
1160 /// this duplicate code in MCWin64EH.cpp.
1162 return context.getObjectFileInfo()->getXDataSection();
1163 return context.getCOFFSection((".xdata"+suffix).str(),
1164 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1165 COFF::IMAGE_SCN_MEM_READ |
1166 COFF::IMAGE_SCN_MEM_WRITE,
1167 SectionKind::getDataRel());
1170 void MCAsmStreamer::EmitWin64EHHandlerData() {
1171 MCStreamer::EmitWin64EHHandlerData();
1173 // Switch sections. Don't call SwitchSection directly, because that will
1174 // cause the section switch to be visible in the emitted assembly.
1175 // We only do this so the section switch that terminates the handler
1176 // data block is visible.
1177 MCWin64EHUnwindInfo *CurFrame = getCurrentW64UnwindInfo();
1178 StringRef suffix=MCWin64EHUnwindEmitter::GetSectionSuffix(CurFrame->Function);
1179 const MCSection *xdataSect = getWin64EHTableSection(suffix, getContext());
1181 SwitchSectionNoChange(xdataSect);
1183 OS << "\t.seh_handlerdata";
1187 void MCAsmStreamer::EmitWin64EHPushReg(unsigned Register) {
1188 MCStreamer::EmitWin64EHPushReg(Register);
1190 OS << "\t.seh_pushreg " << Register;
1194 void MCAsmStreamer::EmitWin64EHSetFrame(unsigned Register, unsigned Offset) {
1195 MCStreamer::EmitWin64EHSetFrame(Register, Offset);
1197 OS << "\t.seh_setframe " << Register << ", " << Offset;
1201 void MCAsmStreamer::EmitWin64EHAllocStack(unsigned Size) {
1202 MCStreamer::EmitWin64EHAllocStack(Size);
1204 OS << "\t.seh_stackalloc " << Size;
1208 void MCAsmStreamer::EmitWin64EHSaveReg(unsigned Register, unsigned Offset) {
1209 MCStreamer::EmitWin64EHSaveReg(Register, Offset);
1211 OS << "\t.seh_savereg " << Register << ", " << Offset;
1215 void MCAsmStreamer::EmitWin64EHSaveXMM(unsigned Register, unsigned Offset) {
1216 MCStreamer::EmitWin64EHSaveXMM(Register, Offset);
1218 OS << "\t.seh_savexmm " << Register << ", " << Offset;
1222 void MCAsmStreamer::EmitWin64EHPushFrame(bool Code) {
1223 MCStreamer::EmitWin64EHPushFrame(Code);
1225 OS << "\t.seh_pushframe";
1231 void MCAsmStreamer::EmitWin64EHEndProlog(void) {
1232 MCStreamer::EmitWin64EHEndProlog();
1234 OS << "\t.seh_endprologue";
1238 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst) {
1239 raw_ostream &OS = GetCommentOS();
1240 SmallString<256> Code;
1241 SmallVector<MCFixup, 4> Fixups;
1242 raw_svector_ostream VecOS(Code);
1243 Emitter->EncodeInstruction(Inst, VecOS, Fixups);
1246 // If we are showing fixups, create symbolic markers in the encoded
1247 // representation. We do this by making a per-bit map to the fixup item index,
1248 // then trying to display it as nicely as possible.
1249 SmallVector<uint8_t, 64> FixupMap;
1250 FixupMap.resize(Code.size() * 8);
1251 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1254 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1255 MCFixup &F = Fixups[i];
1256 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1257 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1258 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1259 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1260 FixupMap[Index] = 1 + i;
1264 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1265 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1266 OS << "encoding: [";
1267 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1271 // See if all bits are the same map entry.
1272 uint8_t MapEntry = FixupMap[i * 8 + 0];
1273 for (unsigned j = 1; j != 8; ++j) {
1274 if (FixupMap[i * 8 + j] == MapEntry)
1277 MapEntry = uint8_t(~0U);
1281 if (MapEntry != uint8_t(~0U)) {
1282 if (MapEntry == 0) {
1283 OS << format("0x%02x", uint8_t(Code[i]));
1286 // FIXME: Some of the 8 bits require fix up.
1287 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1288 << char('A' + MapEntry - 1) << '\'';
1290 OS << char('A' + MapEntry - 1);
1293 // Otherwise, write out in binary.
1295 for (unsigned j = 8; j--;) {
1296 unsigned Bit = (Code[i] >> j) & 1;
1299 if (MAI->isLittleEndian())
1300 FixupBit = i * 8 + j;
1302 FixupBit = i * 8 + (7-j);
1304 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1305 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1306 OS << char('A' + MapEntry - 1);
1314 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1315 MCFixup &F = Fixups[i];
1316 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1317 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1318 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1322 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
1323 assert(getCurrentSection().first &&
1324 "Cannot emit contents before setting section!");
1326 // Show the encoding in a comment if we have a code emitter.
1328 AddEncodingComment(Inst);
1330 // Show the MCInst if enabled.
1332 Inst.dump_pretty(GetCommentOS(), MAI, InstPrinter.get(), "\n ");
1333 GetCommentOS() << "\n";
1336 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
1338 InstPrinter->printInst(&Inst, OS, "");
1340 Inst.print(OS, MAI);
1344 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1345 OS << "\t.bundle_align_mode " << AlignPow2;
1349 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1350 OS << "\t.bundle_lock";
1352 OS << " align_to_end";
1356 void MCAsmStreamer::EmitBundleUnlock() {
1357 OS << "\t.bundle_unlock";
1361 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1362 /// the specified string in the output .s file. This capability is
1363 /// indicated by the hasRawTextSupport() predicate.
1364 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1365 if (!String.empty() && String.back() == '\n')
1366 String = String.substr(0, String.size()-1);
1371 void MCAsmStreamer::FinishImpl() {
1372 // FIXME: This header is duplicated with MCObjectStreamer
1373 // Dump out the dwarf file & directory tables and line tables.
1374 const MCSymbol *LineSectionSymbol = NULL;
1375 if (getContext().hasDwarfFiles() && !UseLoc)
1376 LineSectionSymbol = MCDwarfFileTable::Emit(this);
1378 // If we are generating dwarf for assembly source files dump out the sections.
1379 if (getContext().getGenDwarfForAssembly())
1380 MCGenDwarfInfo::Emit(this, LineSectionSymbol);
1383 EmitFrames(AsmBackend.get(), false);
1386 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1387 MCTargetStreamer *TargetStreamer,
1388 formatted_raw_ostream &OS,
1389 bool isVerboseAsm, bool useLoc, bool useCFI,
1390 bool useDwarfDirectory, MCInstPrinter *IP,
1391 MCCodeEmitter *CE, MCAsmBackend *MAB,
1393 return new MCAsmStreamer(Context, TargetStreamer, OS, isVerboseAsm, useLoc,
1394 useCFI, useDwarfDirectory, IP, CE, MAB, ShowInst);