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;
54 unsigned UseDwarfDirectory : 1;
56 enum EHSymbolFlags { EHGlobal = 1,
57 EHWeakDefinition = 1 << 1,
58 EHPrivateExtern = 1 << 2 };
59 DenseMap<const MCSymbol*, unsigned> FlagMap;
61 bool needsSet(const MCExpr *Value);
63 void EmitRegisterName(int64_t Register);
64 virtual void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame);
65 virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame);
68 MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
69 bool isVerboseAsm, bool useCFI, bool useDwarfDirectory,
70 MCInstPrinter *printer, MCCodeEmitter *emitter,
71 MCAsmBackend *asmbackend, bool showInst)
72 : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
73 InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
74 CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
75 ShowInst(showInst), UseCFI(useCFI),
76 UseDwarfDirectory(useDwarfDirectory) {
77 if (InstPrinter && IsVerboseAsm)
78 InstPrinter->setCommentStream(CommentStream);
82 inline void EmitEOL() {
83 // If we don't have any comments, just emit a \n.
90 void EmitCommentsAndEOL();
92 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
94 virtual bool isVerboseAsm() const { return IsVerboseAsm; }
96 /// hasRawTextSupport - We support EmitRawText.
97 virtual bool hasRawTextSupport() const { return true; }
99 /// AddComment - Add a comment that can be emitted to the generated .s
100 /// file if applicable as a QoI issue to make the output of the compiler
101 /// more readable. This only affects the MCAsmStreamer, and only when
102 /// verbose assembly output is enabled.
103 virtual void AddComment(const Twine &T);
105 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
106 virtual void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &);
108 /// GetCommentOS - Return a raw_ostream that comments can be written to.
109 /// Unlike AddComment, you are required to terminate comments with \n if you
111 virtual raw_ostream &GetCommentOS() {
113 return nulls(); // Discard comments unless in verbose asm mode.
114 return CommentStream;
117 void emitRawComment(const Twine &T, bool TabPrefix = true) override;
119 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
120 virtual void AddBlankLine() {
124 /// @name MCStreamer Interface
127 virtual void ChangeSection(const MCSection *Section,
128 const MCExpr *Subsection);
130 virtual void InitSections(bool Force) {
132 SwitchSection(getContext().getObjectFileInfo()->getTextSection());
135 virtual void EmitLabel(MCSymbol *Symbol);
136 virtual void EmitDebugLabel(MCSymbol *Symbol);
138 virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
140 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
141 virtual void EmitLinkerOptions(ArrayRef<std::string> Options);
142 virtual void EmitDataRegion(MCDataRegionType Kind);
143 virtual void EmitThumbFunc(MCSymbol *Func);
145 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
146 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
147 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
148 const MCSymbol *LastLabel,
149 const MCSymbol *Label,
150 unsigned PointerSize);
151 virtual void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
152 const MCSymbol *Label);
154 virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
156 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
157 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
158 virtual void EmitCOFFSymbolStorageClass(int StorageClass);
159 virtual void EmitCOFFSymbolType(int Type);
160 virtual void EndCOFFSymbolDef();
161 virtual void EmitCOFFSectionIndex(MCSymbol const *Symbol);
162 virtual void EmitCOFFSecRel32(MCSymbol const *Symbol);
163 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
164 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
165 unsigned ByteAlignment);
167 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
169 /// @param Symbol - The common symbol to emit.
170 /// @param Size - The size of the common symbol.
171 /// @param ByteAlignment - The alignment of the common symbol in bytes.
172 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
173 unsigned ByteAlignment);
175 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
176 uint64_t Size = 0, unsigned ByteAlignment = 0);
178 virtual void EmitTBSSSymbol (const MCSection *Section, MCSymbol *Symbol,
179 uint64_t Size, unsigned ByteAlignment = 0);
181 virtual void EmitBytes(StringRef Data);
183 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size);
184 virtual void EmitIntValue(uint64_t Value, unsigned Size);
186 virtual void EmitULEB128Value(const MCExpr *Value);
188 virtual void EmitSLEB128Value(const MCExpr *Value);
190 virtual void EmitGPRel64Value(const MCExpr *Value);
192 virtual void EmitGPRel32Value(const MCExpr *Value);
195 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue);
197 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
198 unsigned ValueSize = 1,
199 unsigned MaxBytesToEmit = 0);
201 virtual void EmitCodeAlignment(unsigned ByteAlignment,
202 unsigned MaxBytesToEmit = 0);
204 virtual bool EmitValueToOffset(const MCExpr *Offset,
205 unsigned char Value = 0);
207 virtual void EmitFileDirective(StringRef Filename);
208 virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
209 StringRef Filename, unsigned CUID = 0);
210 virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
211 unsigned Column, unsigned Flags,
212 unsigned Isa, unsigned Discriminator,
215 virtual void EmitIdent(StringRef IdentString);
216 virtual void EmitCFISections(bool EH, bool Debug);
217 virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
218 virtual void EmitCFIDefCfaOffset(int64_t Offset);
219 virtual void EmitCFIDefCfaRegister(int64_t Register);
220 virtual void EmitCFIOffset(int64_t Register, int64_t Offset);
221 virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
222 virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
223 virtual void EmitCFIRememberState();
224 virtual void EmitCFIRestoreState();
225 virtual void EmitCFISameValue(int64_t Register);
226 virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
227 virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
228 virtual void EmitCFISignalFrame();
229 virtual void EmitCFIUndefined(int64_t Register);
230 virtual void EmitCFIRegister(int64_t Register1, int64_t Register2);
231 virtual void EmitCFIWindowSave();
233 virtual void EmitWin64EHStartProc(const MCSymbol *Symbol);
234 virtual void EmitWin64EHEndProc();
235 virtual void EmitWin64EHStartChained();
236 virtual void EmitWin64EHEndChained();
237 virtual void EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
239 virtual void EmitWin64EHHandlerData();
240 virtual void EmitWin64EHPushReg(unsigned Register);
241 virtual void EmitWin64EHSetFrame(unsigned Register, unsigned Offset);
242 virtual void EmitWin64EHAllocStack(unsigned Size);
243 virtual void EmitWin64EHSaveReg(unsigned Register, unsigned Offset);
244 virtual void EmitWin64EHSaveXMM(unsigned Register, unsigned Offset);
245 virtual void EmitWin64EHPushFrame(bool Code);
246 virtual void EmitWin64EHEndProlog();
248 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI);
250 virtual void EmitBundleAlignMode(unsigned AlignPow2);
251 virtual void EmitBundleLock(bool AlignToEnd);
252 virtual void EmitBundleUnlock();
254 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
255 /// the specified string in the output .s file. This capability is
256 /// indicated by the hasRawTextSupport() predicate.
257 virtual void EmitRawTextImpl(StringRef String);
259 virtual void FinishImpl();
262 } // end anonymous namespace.
264 /// AddComment - Add a comment that can be emitted to the generated .s
265 /// file if applicable as a QoI issue to make the output of the compiler
266 /// more readable. This only affects the MCAsmStreamer, and only when
267 /// verbose assembly output is enabled.
268 void MCAsmStreamer::AddComment(const Twine &T) {
269 if (!IsVerboseAsm) return;
271 // Make sure that CommentStream is flushed.
272 CommentStream.flush();
274 T.toVector(CommentToEmit);
275 // Each comment goes on its own line.
276 CommentToEmit.push_back('\n');
278 // Tell the comment stream that the vector changed underneath it.
279 CommentStream.resync();
282 void MCAsmStreamer::EmitCommentsAndEOL() {
283 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
288 CommentStream.flush();
289 StringRef Comments = CommentToEmit.str();
291 assert(Comments.back() == '\n' &&
292 "Comment array not newline terminated");
294 // Emit a line of comments.
295 OS.PadToColumn(MAI->getCommentColumn());
296 size_t Position = Comments.find('\n');
297 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
299 Comments = Comments.substr(Position+1);
300 } while (!Comments.empty());
302 CommentToEmit.clear();
303 // Tell the comment stream that the vector changed underneath it.
304 CommentStream.resync();
307 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
308 assert(Bytes && "Invalid size!");
309 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
312 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
315 OS << MAI->getCommentString() << T;
319 void MCAsmStreamer::ChangeSection(const MCSection *Section,
320 const MCExpr *Subsection) {
321 assert(Section && "Cannot switch to a null section!");
322 Section->PrintSwitchToSection(*MAI, OS, Subsection);
325 void MCAsmStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
326 MCSymbol *EHSymbol) {
330 unsigned Flags = FlagMap.lookup(Symbol);
332 if (Flags & EHGlobal)
333 EmitSymbolAttribute(EHSymbol, MCSA_Global);
334 if (Flags & EHWeakDefinition)
335 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
336 if (Flags & EHPrivateExtern)
337 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
340 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
341 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
342 MCStreamer::EmitLabel(Symbol);
344 OS << *Symbol << MAI->getLabelSuffix();
348 void MCAsmStreamer::EmitDebugLabel(MCSymbol *Symbol) {
349 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
350 MCStreamer::EmitDebugLabel(Symbol);
352 OS << *Symbol << MAI->getDebugLabelSuffix();
356 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
358 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
359 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
360 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
361 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
362 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
367 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
368 assert(!Options.empty() && "At least one option is required!");
369 OS << "\t.linker_option \"" << Options[0] << '"';
370 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
371 ie = Options.end(); it != ie; ++it) {
372 OS << ", " << '"' << *it << '"';
377 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
378 if (!MAI->doesSupportDataRegionDirectives())
381 case MCDR_DataRegion: OS << "\t.data_region"; break;
382 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
383 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
384 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
385 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
390 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
391 // This needs to emit to a temporary string to get properly quoted
392 // MCSymbols when they have spaces in them.
393 OS << "\t.thumb_func";
394 // Only Mach-O hasSubsectionsViaSymbols()
395 if (MAI->hasSubsectionsViaSymbols())
400 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
401 OS << *Symbol << " = " << *Value;
404 // FIXME: Lift context changes into super class.
405 Symbol->setVariableValue(Value);
408 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
409 OS << ".weakref " << *Alias << ", " << *Symbol;
413 void MCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
414 const MCSymbol *LastLabel,
415 const MCSymbol *Label,
416 unsigned PointerSize) {
417 EmitDwarfSetLineAddr(LineDelta, Label, PointerSize);
420 void MCAsmStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
421 const MCSymbol *Label) {
422 EmitIntValue(dwarf::DW_CFA_advance_loc4, 1);
423 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
424 AddrDelta = ForceExpAbs(AddrDelta);
425 EmitValue(AddrDelta, 4);
429 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
430 MCSymbolAttr Attribute) {
432 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
433 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
434 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
435 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
436 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
437 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
438 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
439 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
440 if (!MAI->hasDotTypeDotSizeDirective())
441 return false; // Symbol attribute not supported
442 OS << "\t.type\t" << *Symbol << ','
443 << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
445 default: return false;
446 case MCSA_ELF_TypeFunction: OS << "function"; break;
447 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
448 case MCSA_ELF_TypeObject: OS << "object"; break;
449 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
450 case MCSA_ELF_TypeCommon: OS << "common"; break;
451 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
452 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
456 case MCSA_Global: // .globl/.global
457 OS << MAI->getGlobalDirective();
458 FlagMap[Symbol] |= EHGlobal;
460 case MCSA_Hidden: OS << "\t.hidden\t"; break;
461 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
462 case MCSA_Internal: OS << "\t.internal\t"; break;
463 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
464 case MCSA_Local: OS << "\t.local\t"; break;
465 case MCSA_NoDeadStrip: OS << "\t.no_dead_strip\t"; break;
466 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
467 case MCSA_PrivateExtern:
468 OS << "\t.private_extern\t";
469 FlagMap[Symbol] |= EHPrivateExtern;
471 case MCSA_Protected: OS << "\t.protected\t"; break;
472 case MCSA_Reference: OS << "\t.reference\t"; break;
473 case MCSA_Weak: OS << "\t.weak\t"; break;
474 case MCSA_WeakDefinition:
475 OS << "\t.weak_definition\t";
476 FlagMap[Symbol] |= EHWeakDefinition;
479 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
480 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
489 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
490 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
494 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
495 OS << "\t.def\t " << *Symbol << ';';
499 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
500 OS << "\t.scl\t" << StorageClass << ';';
504 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
505 OS << "\t.type\t" << Type << ';';
509 void MCAsmStreamer::EndCOFFSymbolDef() {
514 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
515 OS << "\t.secidx\t" << *Symbol;
519 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) {
520 OS << "\t.secrel32\t" << *Symbol;
524 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
525 assert(MAI->hasDotTypeDotSizeDirective());
526 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
529 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
530 unsigned ByteAlignment) {
531 // Common symbols do not belong to any actual section.
532 AssignSection(Symbol, NULL);
534 OS << "\t.comm\t" << *Symbol << ',' << Size;
535 if (ByteAlignment != 0) {
536 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
537 OS << ',' << ByteAlignment;
539 OS << ',' << Log2_32(ByteAlignment);
544 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
546 /// @param Symbol - The common symbol to emit.
547 /// @param Size - The size of the common symbol.
548 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
549 unsigned ByteAlign) {
550 // Common symbols do not belong to any actual section.
551 AssignSection(Symbol, NULL);
553 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
555 switch (MAI->getLCOMMDirectiveAlignmentType()) {
556 case LCOMM::NoAlignment:
557 llvm_unreachable("alignment not supported on .lcomm!");
558 case LCOMM::ByteAlignment:
559 OS << ',' << ByteAlign;
561 case LCOMM::Log2Alignment:
562 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
563 OS << ',' << Log2_32(ByteAlign);
570 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
571 uint64_t Size, unsigned ByteAlignment) {
573 AssignSection(Symbol, Section);
575 // Note: a .zerofill directive does not switch sections.
578 // This is a mach-o specific directive.
579 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
580 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
582 if (Symbol != NULL) {
583 OS << ',' << *Symbol << ',' << Size;
584 if (ByteAlignment != 0)
585 OS << ',' << Log2_32(ByteAlignment);
590 // .tbss sym, size, align
591 // This depends that the symbol has already been mangled from the original,
593 void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
594 uint64_t Size, unsigned ByteAlignment) {
595 AssignSection(Symbol, Section);
597 assert(Symbol != NULL && "Symbol shouldn't be NULL!");
598 // Instead of using the Section we'll just use the shortcut.
599 // This is a mach-o specific directive and section.
600 OS << ".tbss " << *Symbol << ", " << Size;
602 // Output align if we have it. We default to 1 so don't bother printing
604 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
609 static inline char toOctal(int X) { return (X&7)+'0'; }
611 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
614 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
615 unsigned char C = Data[i];
616 if (C == '"' || C == '\\') {
617 OS << '\\' << (char)C;
621 if (isprint((unsigned char)C)) {
627 case '\b': OS << "\\b"; break;
628 case '\f': OS << "\\f"; break;
629 case '\n': OS << "\\n"; break;
630 case '\r': OS << "\\r"; break;
631 case '\t': OS << "\\t"; break;
634 OS << toOctal(C >> 6);
635 OS << toOctal(C >> 3);
636 OS << toOctal(C >> 0);
645 void MCAsmStreamer::EmitBytes(StringRef Data) {
646 assert(getCurrentSection().first &&
647 "Cannot emit contents before setting section!");
648 if (Data.empty()) return;
650 if (Data.size() == 1) {
651 OS << MAI->getData8bitsDirective();
652 OS << (unsigned)(unsigned char)Data[0];
657 // If the data ends with 0 and the target supports .asciz, use it, otherwise
659 if (MAI->getAscizDirective() && Data.back() == 0) {
660 OS << MAI->getAscizDirective();
661 Data = Data.substr(0, Data.size()-1);
663 OS << MAI->getAsciiDirective();
666 PrintQuotedString(Data, OS);
670 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
671 EmitValue(MCConstantExpr::Create(Value, getContext()), Size);
674 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size) {
675 assert(Size <= 8 && "Invalid size");
676 assert(getCurrentSection().first &&
677 "Cannot emit contents before setting section!");
678 const char *Directive = 0;
681 case 1: Directive = MAI->getData8bitsDirective(); break;
682 case 2: Directive = MAI->getData16bitsDirective(); break;
683 case 4: Directive = MAI->getData32bitsDirective(); break;
684 case 8: Directive = MAI->getData64bitsDirective(); break;
689 if (!Value->EvaluateAsAbsolute(IntValue))
690 report_fatal_error("Don't know how to emit this value.");
692 // We couldn't handle the requested integer size so we fallback by breaking
693 // the request down into several, smaller, integers. Since sizes greater
694 // than eight are invalid and size equivalent to eight should have been
695 // handled earlier, we use four bytes as our largest piece of granularity.
696 bool IsLittleEndian = MAI->isLittleEndian();
697 for (unsigned Emitted = 0; Emitted != Size;) {
698 unsigned Remaining = Size - Emitted;
699 // The size of our partial emission must be a power of two less than
701 unsigned EmissionSize = PowerOf2Floor(Remaining);
702 if (EmissionSize > 4)
704 // Calculate the byte offset of our partial emission taking into account
705 // the endianness of the target.
706 unsigned ByteOffset =
707 IsLittleEndian ? Emitted : (Remaining - EmissionSize);
708 uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
709 // We truncate our partial emission to fit within the bounds of the
710 // emission domain. This produces nicer output and silences potential
711 // truncation warnings when round tripping through another assembler.
712 ValueToEmit &= ~0ULL >> (64 - EmissionSize * 8);
713 EmitIntValue(ValueToEmit, EmissionSize);
714 Emitted += EmissionSize;
719 assert(Directive && "Invalid size for machine code value!");
720 OS << Directive << *Value;
724 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
726 if (Value->EvaluateAsAbsolute(IntValue)) {
727 EmitULEB128IntValue(IntValue);
730 assert(MAI->hasLEB128() && "Cannot print a .uleb");
731 OS << ".uleb128 " << *Value;
735 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
737 if (Value->EvaluateAsAbsolute(IntValue)) {
738 EmitSLEB128IntValue(IntValue);
741 assert(MAI->hasLEB128() && "Cannot print a .sleb");
742 OS << ".sleb128 " << *Value;
746 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
747 assert(MAI->getGPRel64Directive() != 0);
748 OS << MAI->getGPRel64Directive() << *Value;
752 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
753 assert(MAI->getGPRel32Directive() != 0);
754 OS << MAI->getGPRel32Directive() << *Value;
759 /// EmitFill - Emit NumBytes bytes worth of the value specified by
760 /// FillValue. This implements directives such as '.space'.
761 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
762 if (NumBytes == 0) return;
764 if (const char *ZeroDirective = MAI->getZeroDirective()) {
765 OS << ZeroDirective << NumBytes;
767 OS << ',' << (int)FillValue;
772 // Emit a byte at a time.
773 MCStreamer::EmitFill(NumBytes, FillValue);
776 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
778 unsigned MaxBytesToEmit) {
779 // Some assemblers don't support non-power of two alignments, so we always
780 // emit alignments as a power of two if possible.
781 if (isPowerOf2_32(ByteAlignment)) {
784 llvm_unreachable("Invalid size for machine code value!");
795 llvm_unreachable("Unsupported alignment size!");
798 if (MAI->getAlignmentIsInBytes())
801 OS << Log2_32(ByteAlignment);
803 if (Value || MaxBytesToEmit) {
805 OS.write_hex(truncateToSize(Value, ValueSize));
808 OS << ", " << MaxBytesToEmit;
814 // Non-power of two alignment. This is not widely supported by assemblers.
815 // FIXME: Parameterize this based on MAI.
817 default: llvm_unreachable("Invalid size for machine code value!");
818 case 1: OS << ".balign"; break;
819 case 2: OS << ".balignw"; break;
820 case 4: OS << ".balignl"; break;
821 case 8: llvm_unreachable("Unsupported alignment size!");
824 OS << ' ' << ByteAlignment;
825 OS << ", " << truncateToSize(Value, ValueSize);
827 OS << ", " << MaxBytesToEmit;
831 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
832 unsigned MaxBytesToEmit) {
833 // Emit with a text fill value.
834 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
838 bool MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
839 unsigned char Value) {
840 // FIXME: Verify that Offset is associated with the current section.
841 OS << ".org " << *Offset << ", " << (unsigned) Value;
847 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
848 assert(MAI->hasSingleParameterDotFile());
850 PrintQuotedString(Filename, OS);
854 bool MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
855 StringRef Filename, unsigned CUID) {
856 if (!UseDwarfDirectory && !Directory.empty()) {
857 if (sys::path::is_absolute(Filename))
858 return EmitDwarfFileDirective(FileNo, "", Filename, CUID);
860 SmallString<128> FullPathName = Directory;
861 sys::path::append(FullPathName, Filename);
862 return EmitDwarfFileDirective(FileNo, "", FullPathName, CUID);
865 OS << "\t.file\t" << FileNo << ' ';
866 if (!Directory.empty()) {
867 PrintQuotedString(Directory, OS);
870 PrintQuotedString(Filename, OS);
872 // All .file will belong to a single CUID.
875 return this->MCStreamer::EmitDwarfFileDirective(FileNo, Directory, Filename,
879 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
880 unsigned Column, unsigned Flags,
882 unsigned Discriminator,
883 StringRef FileName) {
884 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
885 Isa, Discriminator, FileName);
886 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
887 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
888 OS << " basic_block";
889 if (Flags & DWARF2_FLAG_PROLOGUE_END)
890 OS << " prologue_end";
891 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
892 OS << " epilogue_begin";
894 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
895 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
898 if (Flags & DWARF2_FLAG_IS_STMT)
905 OS << " isa " << Isa;
907 OS << " discriminator " << Discriminator;
910 OS.PadToColumn(MAI->getCommentColumn());
911 OS << MAI->getCommentString() << ' ' << FileName << ':'
912 << Line << ':' << Column;
917 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
918 assert(MAI->hasIdentDirective() && ".ident directive not supported");
920 PrintQuotedString(IdentString, OS);
924 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
925 MCStreamer::EmitCFISections(EH, Debug);
930 OS << "\t.cfi_sections ";
934 OS << ", .debug_frame";
936 OS << ".debug_frame";
942 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
944 RecordProcStart(Frame);
948 OS << "\t.cfi_startproc";
954 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
956 RecordProcEnd(Frame);
960 // Put a dummy non-null value in Frame.End to mark that this frame has been
962 Frame.End = (MCSymbol *) 1;
964 OS << "\t.cfi_endproc";
968 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
969 if (InstPrinter && !MAI->useDwarfRegNumForCFI()) {
970 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
971 unsigned LLVMRegister = MRI->getLLVMRegNum(Register, true);
972 InstPrinter->printRegName(OS, LLVMRegister);
978 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
979 MCStreamer::EmitCFIDefCfa(Register, Offset);
984 OS << "\t.cfi_def_cfa ";
985 EmitRegisterName(Register);
986 OS << ", " << Offset;
990 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
991 MCStreamer::EmitCFIDefCfaOffset(Offset);
996 OS << "\t.cfi_def_cfa_offset " << Offset;
1000 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
1001 MCStreamer::EmitCFIDefCfaRegister(Register);
1006 OS << "\t.cfi_def_cfa_register ";
1007 EmitRegisterName(Register);
1011 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
1012 this->MCStreamer::EmitCFIOffset(Register, Offset);
1017 OS << "\t.cfi_offset ";
1018 EmitRegisterName(Register);
1019 OS << ", " << Offset;
1023 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1024 unsigned Encoding) {
1025 MCStreamer::EmitCFIPersonality(Sym, Encoding);
1030 OS << "\t.cfi_personality " << Encoding << ", " << *Sym;
1034 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1035 MCStreamer::EmitCFILsda(Sym, Encoding);
1040 OS << "\t.cfi_lsda " << Encoding << ", " << *Sym;
1044 void MCAsmStreamer::EmitCFIRememberState() {
1045 MCStreamer::EmitCFIRememberState();
1050 OS << "\t.cfi_remember_state";
1054 void MCAsmStreamer::EmitCFIRestoreState() {
1055 MCStreamer::EmitCFIRestoreState();
1060 OS << "\t.cfi_restore_state";
1064 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1065 MCStreamer::EmitCFISameValue(Register);
1070 OS << "\t.cfi_same_value ";
1071 EmitRegisterName(Register);
1075 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1076 MCStreamer::EmitCFIRelOffset(Register, Offset);
1081 OS << "\t.cfi_rel_offset ";
1082 EmitRegisterName(Register);
1083 OS << ", " << Offset;
1087 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1088 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1093 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1097 void MCAsmStreamer::EmitCFISignalFrame() {
1098 MCStreamer::EmitCFISignalFrame();
1103 OS << "\t.cfi_signal_frame";
1107 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1108 MCStreamer::EmitCFIUndefined(Register);
1113 OS << "\t.cfi_undefined " << Register;
1117 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1118 MCStreamer::EmitCFIRegister(Register1, Register2);
1123 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1127 void MCAsmStreamer::EmitCFIWindowSave() {
1128 MCStreamer::EmitCFIWindowSave();
1133 OS << "\t.cfi_window_save";
1137 void MCAsmStreamer::EmitWin64EHStartProc(const MCSymbol *Symbol) {
1138 MCStreamer::EmitWin64EHStartProc(Symbol);
1140 OS << ".seh_proc " << *Symbol;
1144 void MCAsmStreamer::EmitWin64EHEndProc() {
1145 MCStreamer::EmitWin64EHEndProc();
1147 OS << "\t.seh_endproc";
1151 void MCAsmStreamer::EmitWin64EHStartChained() {
1152 MCStreamer::EmitWin64EHStartChained();
1154 OS << "\t.seh_startchained";
1158 void MCAsmStreamer::EmitWin64EHEndChained() {
1159 MCStreamer::EmitWin64EHEndChained();
1161 OS << "\t.seh_endchained";
1165 void MCAsmStreamer::EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
1167 MCStreamer::EmitWin64EHHandler(Sym, Unwind, Except);
1169 OS << "\t.seh_handler " << *Sym;
1177 static const MCSection *getWin64EHTableSection(StringRef suffix,
1178 MCContext &context) {
1179 // FIXME: This doesn't belong in MCObjectFileInfo. However,
1180 /// this duplicate code in MCWin64EH.cpp.
1182 return context.getObjectFileInfo()->getXDataSection();
1183 return context.getCOFFSection((".xdata"+suffix).str(),
1184 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1185 COFF::IMAGE_SCN_MEM_READ |
1186 COFF::IMAGE_SCN_MEM_WRITE,
1187 SectionKind::getDataRel());
1190 void MCAsmStreamer::EmitWin64EHHandlerData() {
1191 MCStreamer::EmitWin64EHHandlerData();
1193 // Switch sections. Don't call SwitchSection directly, because that will
1194 // cause the section switch to be visible in the emitted assembly.
1195 // We only do this so the section switch that terminates the handler
1196 // data block is visible.
1197 MCWin64EHUnwindInfo *CurFrame = getCurrentW64UnwindInfo();
1198 StringRef suffix=MCWin64EHUnwindEmitter::GetSectionSuffix(CurFrame->Function);
1199 const MCSection *xdataSect = getWin64EHTableSection(suffix, getContext());
1201 SwitchSectionNoChange(xdataSect);
1203 OS << "\t.seh_handlerdata";
1207 void MCAsmStreamer::EmitWin64EHPushReg(unsigned Register) {
1208 MCStreamer::EmitWin64EHPushReg(Register);
1210 OS << "\t.seh_pushreg " << Register;
1214 void MCAsmStreamer::EmitWin64EHSetFrame(unsigned Register, unsigned Offset) {
1215 MCStreamer::EmitWin64EHSetFrame(Register, Offset);
1217 OS << "\t.seh_setframe " << Register << ", " << Offset;
1221 void MCAsmStreamer::EmitWin64EHAllocStack(unsigned Size) {
1222 MCStreamer::EmitWin64EHAllocStack(Size);
1224 OS << "\t.seh_stackalloc " << Size;
1228 void MCAsmStreamer::EmitWin64EHSaveReg(unsigned Register, unsigned Offset) {
1229 MCStreamer::EmitWin64EHSaveReg(Register, Offset);
1231 OS << "\t.seh_savereg " << Register << ", " << Offset;
1235 void MCAsmStreamer::EmitWin64EHSaveXMM(unsigned Register, unsigned Offset) {
1236 MCStreamer::EmitWin64EHSaveXMM(Register, Offset);
1238 OS << "\t.seh_savexmm " << Register << ", " << Offset;
1242 void MCAsmStreamer::EmitWin64EHPushFrame(bool Code) {
1243 MCStreamer::EmitWin64EHPushFrame(Code);
1245 OS << "\t.seh_pushframe";
1251 void MCAsmStreamer::EmitWin64EHEndProlog(void) {
1252 MCStreamer::EmitWin64EHEndProlog();
1254 OS << "\t.seh_endprologue";
1258 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1259 const MCSubtargetInfo &STI) {
1260 raw_ostream &OS = GetCommentOS();
1261 SmallString<256> Code;
1262 SmallVector<MCFixup, 4> Fixups;
1263 raw_svector_ostream VecOS(Code);
1264 Emitter->EncodeInstruction(Inst, VecOS, Fixups, STI);
1267 // If we are showing fixups, create symbolic markers in the encoded
1268 // representation. We do this by making a per-bit map to the fixup item index,
1269 // then trying to display it as nicely as possible.
1270 SmallVector<uint8_t, 64> FixupMap;
1271 FixupMap.resize(Code.size() * 8);
1272 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1275 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1276 MCFixup &F = Fixups[i];
1277 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1278 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1279 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1280 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1281 FixupMap[Index] = 1 + i;
1285 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1286 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1287 OS << "encoding: [";
1288 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1292 // See if all bits are the same map entry.
1293 uint8_t MapEntry = FixupMap[i * 8 + 0];
1294 for (unsigned j = 1; j != 8; ++j) {
1295 if (FixupMap[i * 8 + j] == MapEntry)
1298 MapEntry = uint8_t(~0U);
1302 if (MapEntry != uint8_t(~0U)) {
1303 if (MapEntry == 0) {
1304 OS << format("0x%02x", uint8_t(Code[i]));
1307 // FIXME: Some of the 8 bits require fix up.
1308 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1309 << char('A' + MapEntry - 1) << '\'';
1311 OS << char('A' + MapEntry - 1);
1314 // Otherwise, write out in binary.
1316 for (unsigned j = 8; j--;) {
1317 unsigned Bit = (Code[i] >> j) & 1;
1320 if (MAI->isLittleEndian())
1321 FixupBit = i * 8 + j;
1323 FixupBit = i * 8 + (7-j);
1325 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1326 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1327 OS << char('A' + MapEntry - 1);
1335 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1336 MCFixup &F = Fixups[i];
1337 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1338 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1339 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1343 void MCAsmStreamer::EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) {
1344 assert(getCurrentSection().first &&
1345 "Cannot emit contents before setting section!");
1347 // Show the encoding in a comment if we have a code emitter.
1349 AddEncodingComment(Inst, STI);
1351 // Show the MCInst if enabled.
1353 Inst.dump_pretty(GetCommentOS(), MAI, InstPrinter.get(), "\n ");
1354 GetCommentOS() << "\n";
1357 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
1359 InstPrinter->printInst(&Inst, OS, "");
1361 Inst.print(OS, MAI);
1365 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1366 OS << "\t.bundle_align_mode " << AlignPow2;
1370 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1371 OS << "\t.bundle_lock";
1373 OS << " align_to_end";
1377 void MCAsmStreamer::EmitBundleUnlock() {
1378 OS << "\t.bundle_unlock";
1382 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1383 /// the specified string in the output .s file. This capability is
1384 /// indicated by the hasRawTextSupport() predicate.
1385 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1386 if (!String.empty() && String.back() == '\n')
1387 String = String.substr(0, String.size()-1);
1392 void MCAsmStreamer::FinishImpl() {
1393 // If we are generating dwarf for assembly source files dump out the sections.
1394 if (getContext().getGenDwarfForAssembly())
1395 MCGenDwarfInfo::Emit(this, NULL);
1398 EmitFrames(AsmBackend.get(), false);
1401 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1402 formatted_raw_ostream &OS,
1403 bool isVerboseAsm, bool useCFI,
1404 bool useDwarfDirectory, MCInstPrinter *IP,
1405 MCCodeEmitter *CE, MCAsmBackend *MAB,
1407 return new MCAsmStreamer(Context, OS, isVerboseAsm, useCFI, useDwarfDirectory,
1408 IP, CE, MAB, ShowInst);