Index: head/contrib/llvm/include/llvm/MC/MCObjectStreamer.h =================================================================== --- head/contrib/llvm/include/llvm/MC/MCObjectStreamer.h (revision 328593) +++ head/contrib/llvm/include/llvm/MC/MCObjectStreamer.h (revision 328594) @@ -1,188 +1,187 @@ //===- MCObjectStreamer.h - MCStreamer Object File Interface ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_MC_MCOBJECTSTREAMER_H #define LLVM_MC_MCOBJECTSTREAMER_H #include "llvm/ADT/SmallVector.h" #include "llvm/MC/MCAssembler.h" #include "llvm/MC/MCSection.h" #include "llvm/MC/MCStreamer.h" namespace llvm { class MCAssembler; class MCCodeEmitter; class MCSubtargetInfo; class MCExpr; class MCFragment; class MCDataFragment; class MCAsmBackend; class raw_ostream; class raw_pwrite_stream; /// \brief Streaming object file generation interface. /// /// This class provides an implementation of the MCStreamer interface which is /// suitable for use with the assembler backend. Specific object file formats /// are expected to subclass this interface to implement directives specific /// to that file format or custom semantics expected by the object writer /// implementation. class MCObjectStreamer : public MCStreamer { std::unique_ptr ObjectWriter; std::unique_ptr TAB; std::unique_ptr Emitter; std::unique_ptr Assembler; MCSection::iterator CurInsertionPoint; bool EmitEHFrame; bool EmitDebugFrame; SmallVector PendingLabels; virtual void EmitInstToData(const MCInst &Inst, const MCSubtargetInfo&) = 0; void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override; void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override; MCSymbol *EmitCFILabel() override; void EmitInstructionImpl(const MCInst &Inst, const MCSubtargetInfo &STI); protected: MCObjectStreamer(MCContext &Context, std::unique_ptr TAB, raw_pwrite_stream &OS, std::unique_ptr Emitter); ~MCObjectStreamer(); public: /// state management void reset() override; /// Object streamers require the integrated assembler. bool isIntegratedAssemblerRequired() const override { return true; } void EmitFrames(MCAsmBackend *MAB); void EmitCFISections(bool EH, bool Debug) override; MCFragment *getCurrentFragment() const; void insert(MCFragment *F) { flushPendingLabels(F); MCSection *CurSection = getCurrentSectionOnly(); CurSection->getFragmentList().insert(CurInsertionPoint, F); F->setParent(CurSection); } /// Get a data fragment to write into, creating a new one if the current /// fragment is not a data fragment. MCDataFragment *getOrCreateDataFragment(); MCPaddingFragment *getOrCreatePaddingFragment(); protected: bool changeSectionImpl(MCSection *Section, const MCExpr *Subsection); /// If any labels have been emitted but not assigned fragments, ensure that /// they get assigned, either to F if possible or to a new data fragment. /// Optionally, it is also possible to provide an offset \p FOffset, which /// will be used as a symbol offset within the fragment. void flushPendingLabels(MCFragment *F, uint64_t FOffset = 0); public: void visitUsedSymbol(const MCSymbol &Sym) override; MCAssembler &getAssembler() { return *Assembler; } /// \name MCStreamer Interface /// @{ void EmitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc()) override; virtual void EmitLabel(MCSymbol *Symbol, SMLoc Loc, MCFragment *F); void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override; void EmitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc = SMLoc()) override; void EmitULEB128Value(const MCExpr *Value) override; void EmitSLEB128Value(const MCExpr *Value) override; void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override; void ChangeSection(MCSection *Section, const MCExpr *Subsection) override; void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI, bool = false) override; /// \brief Emit an instruction to a special fragment, because this instruction /// can change its size during relaxation. virtual void EmitInstToFragment(const MCInst &Inst, const MCSubtargetInfo &); void EmitBundleAlignMode(unsigned AlignPow2) override; void EmitBundleLock(bool AlignToEnd) override; void EmitBundleUnlock() override; void EmitBytes(StringRef Data) override; void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0, unsigned ValueSize = 1, unsigned MaxBytesToEmit = 0) override; void EmitCodeAlignment(unsigned ByteAlignment, unsigned MaxBytesToEmit = 0) override; void emitValueToOffset(const MCExpr *Offset, unsigned char Value, SMLoc Loc) override; void EmitCodePaddingBasicBlockStart(const MCCodePaddingContext &Context) override; void EmitCodePaddingBasicBlockEnd(const MCCodePaddingContext &Context) override; void EmitDwarfLocDirective(unsigned FileNo, unsigned Line, unsigned Column, unsigned Flags, unsigned Isa, unsigned Discriminator, StringRef FileName) override; void EmitDwarfAdvanceLineAddr(int64_t LineDelta, const MCSymbol *LastLabel, const MCSymbol *Label, unsigned PointerSize); void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel, const MCSymbol *Label); void EmitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line, unsigned Column, bool PrologueEnd, bool IsStmt, StringRef FileName, SMLoc Loc) override; void EmitCVLinetableDirective(unsigned FunctionId, const MCSymbol *Begin, const MCSymbol *End) override; void EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId, unsigned SourceFileId, unsigned SourceLineNum, const MCSymbol *FnStartSym, const MCSymbol *FnEndSym) override; void EmitCVDefRangeDirective( ArrayRef> Ranges, StringRef FixedSizePortion) override; void EmitCVStringTableDirective() override; void EmitCVFileChecksumsDirective() override; void EmitCVFileChecksumOffsetDirective(unsigned FileNo) override; void EmitDTPRel32Value(const MCExpr *Value) override; void EmitDTPRel64Value(const MCExpr *Value) override; void EmitTPRel32Value(const MCExpr *Value) override; void EmitTPRel64Value(const MCExpr *Value) override; void EmitGPRel32Value(const MCExpr *Value) override; void EmitGPRel64Value(const MCExpr *Value) override; bool EmitRelocDirective(const MCExpr &Offset, StringRef Name, const MCExpr *Expr, SMLoc Loc) override; using MCStreamer::emitFill; - void emitFill(uint64_t NumBytes, uint8_t FillValue) override; void emitFill(const MCExpr &NumBytes, uint64_t FillValue, SMLoc Loc = SMLoc()) override; void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr, SMLoc Loc = SMLoc()) override; void EmitFileDirective(StringRef Filename) override; void FinishImpl() override; /// Emit the absolute difference between two symbols if possible. /// /// Emit the absolute difference between \c Hi and \c Lo, as long as we can /// compute it. Currently, that requires that both symbols are in the same /// data fragment. Otherwise, do nothing and return \c false. /// /// \pre Offset of \c Hi is greater than the offset \c Lo. void emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo, unsigned Size) override; bool mayHaveInstructions(MCSection &Sec) const override; }; } // end namespace llvm #endif Index: head/contrib/llvm/include/llvm/MC/MCStreamer.h =================================================================== --- head/contrib/llvm/include/llvm/MC/MCStreamer.h (revision 328593) +++ head/contrib/llvm/include/llvm/MC/MCStreamer.h (revision 328594) @@ -1,947 +1,947 @@ //===- MCStreamer.h - High-level Streaming Machine Code Output --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares the MCStreamer class. // //===----------------------------------------------------------------------===// #ifndef LLVM_MC_MCSTREAMER_H #define LLVM_MC_MCSTREAMER_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/MC/MCDirectives.h" #include "llvm/MC/MCDwarf.h" #include "llvm/MC/MCLinkerOptimizationHint.h" #include "llvm/MC/MCSymbol.h" #include "llvm/MC/MCWinEH.h" #include "llvm/Support/SMLoc.h" #include "llvm/Support/TargetParser.h" #include #include #include #include #include #include namespace llvm { class AssemblerConstantPools; class formatted_raw_ostream; class MCAsmBackend; class MCCodeEmitter; struct MCCodePaddingContext; class MCContext; class MCExpr; class MCInst; class MCInstPrinter; class MCSection; class MCStreamer; class MCSymbolRefExpr; class MCSubtargetInfo; class raw_ostream; class Twine; using MCSectionSubPair = std::pair; /// Target specific streamer interface. This is used so that targets can /// implement support for target specific assembly directives. /// /// If target foo wants to use this, it should implement 3 classes: /// * FooTargetStreamer : public MCTargetStreamer /// * FooTargetAsmStreamer : public FooTargetStreamer /// * FooTargetELFStreamer : public FooTargetStreamer /// /// FooTargetStreamer should have a pure virtual method for each directive. For /// example, for a ".bar symbol_name" directive, it should have /// virtual emitBar(const MCSymbol &Symbol) = 0; /// /// The FooTargetAsmStreamer and FooTargetELFStreamer classes implement the /// method. The assembly streamer just prints ".bar symbol_name". The object /// streamer does whatever is needed to implement .bar in the object file. /// /// In the assembly printer and parser the target streamer can be used by /// calling getTargetStreamer and casting it to FooTargetStreamer: /// /// MCTargetStreamer &TS = OutStreamer.getTargetStreamer(); /// FooTargetStreamer &ATS = static_cast(TS); /// /// The base classes FooTargetAsmStreamer and FooTargetELFStreamer should /// *never* be treated differently. Callers should always talk to a /// FooTargetStreamer. class MCTargetStreamer { protected: MCStreamer &Streamer; public: MCTargetStreamer(MCStreamer &S); virtual ~MCTargetStreamer(); MCStreamer &getStreamer() { return Streamer; } // Allow a target to add behavior to the EmitLabel of MCStreamer. virtual void emitLabel(MCSymbol *Symbol); // Allow a target to add behavior to the emitAssignment of MCStreamer. virtual void emitAssignment(MCSymbol *Symbol, const MCExpr *Value); virtual void prettyPrintAsm(MCInstPrinter &InstPrinter, raw_ostream &OS, const MCInst &Inst, const MCSubtargetInfo &STI); virtual void emitDwarfFileDirective(StringRef Directive); /// Update streamer for a new active section. /// /// This is called by PopSection and SwitchSection, if the current /// section changes. virtual void changeSection(const MCSection *CurSection, MCSection *Section, const MCExpr *SubSection, raw_ostream &OS); virtual void emitValue(const MCExpr *Value); virtual void finish(); }; // FIXME: declared here because it is used from // lib/CodeGen/AsmPrinter/ARMException.cpp. class ARMTargetStreamer : public MCTargetStreamer { public: ARMTargetStreamer(MCStreamer &S); ~ARMTargetStreamer() override; virtual void emitFnStart(); virtual void emitFnEnd(); virtual void emitCantUnwind(); virtual void emitPersonality(const MCSymbol *Personality); virtual void emitPersonalityIndex(unsigned Index); virtual void emitHandlerData(); virtual void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0); virtual void emitMovSP(unsigned Reg, int64_t Offset = 0); virtual void emitPad(int64_t Offset); virtual void emitRegSave(const SmallVectorImpl &RegList, bool isVector); virtual void emitUnwindRaw(int64_t StackOffset, const SmallVectorImpl &Opcodes); virtual void switchVendor(StringRef Vendor); virtual void emitAttribute(unsigned Attribute, unsigned Value); virtual void emitTextAttribute(unsigned Attribute, StringRef String); virtual void emitIntTextAttribute(unsigned Attribute, unsigned IntValue, StringRef StringValue = ""); virtual void emitFPU(unsigned FPU); virtual void emitArch(ARM::ArchKind Arch); virtual void emitArchExtension(unsigned ArchExt); virtual void emitObjectArch(ARM::ArchKind Arch); void emitTargetAttributes(const MCSubtargetInfo &STI); virtual void finishAttributeSection(); virtual void emitInst(uint32_t Inst, char Suffix = '\0'); virtual void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE); virtual void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value); void finish() override; /// Reset any state between object emissions, i.e. the equivalent of /// MCStreamer's reset method. virtual void reset(); /// Callback used to implement the ldr= pseudo. /// Add a new entry to the constant pool for the current section and return an /// MCExpr that can be used to refer to the constant pool location. const MCExpr *addConstantPoolEntry(const MCExpr *, SMLoc Loc); /// Callback used to implemnt the .ltorg directive. /// Emit contents of constant pool for the current section. void emitCurrentConstantPool(); private: std::unique_ptr ConstantPools; }; /// \brief Streaming machine code generation interface. /// /// This interface is intended to provide a programatic interface that is very /// similar to the level that an assembler .s file provides. It has callbacks /// to emit bytes, handle directives, etc. The implementation of this interface /// retains state to know what the current section is etc. /// /// There are multiple implementations of this interface: one for writing out /// a .s file, and implementations that write out .o files of various formats. /// class MCStreamer { MCContext &Context; std::unique_ptr TargetStreamer; std::vector DwarfFrameInfos; MCDwarfFrameInfo *getCurrentDwarfFrameInfo(); /// Similar to DwarfFrameInfos, but for SEH unwind info. Chained frames may /// refer to each other, so use std::unique_ptr to provide pointer stability. std::vector> WinFrameInfos; WinEH::FrameInfo *CurrentWinFrameInfo; /// Retreive the current frame info if one is available and it is not yet /// closed. Otherwise, issue an error and return null. WinEH::FrameInfo *EnsureValidWinFrameInfo(SMLoc Loc); /// \brief Tracks an index to represent the order a symbol was emitted in. /// Zero means we did not emit that symbol. DenseMap SymbolOrdering; /// \brief This is stack of current and previous section values saved by /// PushSection. SmallVector, 4> SectionStack; /// The next unique ID to use when creating a WinCFI-related section (.pdata /// or .xdata). This ID ensures that we have a one-to-one mapping from /// code section to unwind info section, which MSVC's incremental linker /// requires. unsigned NextWinCFIID = 0; protected: MCStreamer(MCContext &Ctx); virtual void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame); virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &CurFrame); /// When emitting an object file, create and emit a real label. When emitting /// textual assembly, this should do nothing to avoid polluting our output. virtual MCSymbol *EmitCFILabel(); WinEH::FrameInfo *getCurrentWinFrameInfo() { return CurrentWinFrameInfo; } virtual void EmitWindowsUnwindTables(); virtual void EmitRawTextImpl(StringRef String); public: MCStreamer(const MCStreamer &) = delete; MCStreamer &operator=(const MCStreamer &) = delete; virtual ~MCStreamer(); void visitUsedExpr(const MCExpr &Expr); virtual void visitUsedSymbol(const MCSymbol &Sym); void setTargetStreamer(MCTargetStreamer *TS) { TargetStreamer.reset(TS); } /// State management /// virtual void reset(); MCContext &getContext() const { return Context; } MCTargetStreamer *getTargetStreamer() { return TargetStreamer.get(); } unsigned getNumFrameInfos() { return DwarfFrameInfos.size(); } ArrayRef getDwarfFrameInfos() const { return DwarfFrameInfos; } bool hasUnfinishedDwarfFrameInfo(); unsigned getNumWinFrameInfos() { return WinFrameInfos.size(); } ArrayRef> getWinFrameInfos() const { return WinFrameInfos; } void generateCompactUnwindEncodings(MCAsmBackend *MAB); /// \name Assembly File Formatting. /// @{ /// \brief Return true if this streamer supports verbose assembly and if it is /// enabled. virtual bool isVerboseAsm() const { return false; } /// \brief Return true if this asm streamer supports emitting unformatted text /// to the .s file with EmitRawText. virtual bool hasRawTextSupport() const { return false; } /// \brief Is the integrated assembler required for this streamer to function /// correctly? virtual bool isIntegratedAssemblerRequired() const { return false; } /// \brief Add a textual comment. /// /// Typically for comments that can be emitted to the generated .s /// file if applicable as a QoI issue to make the output of the compiler /// more readable. This only affects the MCAsmStreamer, and only when /// verbose assembly output is enabled. /// /// If the comment includes embedded \n's, they will each get the comment /// prefix as appropriate. The added comment should not end with a \n. /// By default, each comment is terminated with an end of line, i.e. the /// EOL param is set to true by default. If one prefers not to end the /// comment with a new line then the EOL param should be passed /// with a false value. virtual void AddComment(const Twine &T, bool EOL = true) {} /// \brief Return a raw_ostream that comments can be written to. Unlike /// AddComment, you are required to terminate comments with \n if you use this /// method. virtual raw_ostream &GetCommentOS(); /// \brief Print T and prefix it with the comment string (normally #) and /// optionally a tab. This prints the comment immediately, not at the end of /// the current line. It is basically a safe version of EmitRawText: since it /// only prints comments, the object streamer ignores it instead of asserting. virtual void emitRawComment(const Twine &T, bool TabPrefix = true); /// \brief Add explicit comment T. T is required to be a valid /// comment in the output and does not need to be escaped. virtual void addExplicitComment(const Twine &T); /// \brief Emit added explicit comments. virtual void emitExplicitComments(); /// AddBlankLine - Emit a blank line to a .s file to pretty it up. virtual void AddBlankLine() {} /// @} /// \name Symbol & Section Management /// @{ /// \brief Return the current section that the streamer is emitting code to. MCSectionSubPair getCurrentSection() const { if (!SectionStack.empty()) return SectionStack.back().first; return MCSectionSubPair(); } MCSection *getCurrentSectionOnly() const { return getCurrentSection().first; } /// \brief Return the previous section that the streamer is emitting code to. MCSectionSubPair getPreviousSection() const { if (!SectionStack.empty()) return SectionStack.back().second; return MCSectionSubPair(); } /// \brief Returns an index to represent the order a symbol was emitted in. /// (zero if we did not emit that symbol) unsigned GetSymbolOrder(const MCSymbol *Sym) const { return SymbolOrdering.lookup(Sym); } /// \brief Update streamer for a new active section. /// /// This is called by PopSection and SwitchSection, if the current /// section changes. virtual void ChangeSection(MCSection *, const MCExpr *); /// \brief Save the current and previous section on the section stack. void PushSection() { SectionStack.push_back( std::make_pair(getCurrentSection(), getPreviousSection())); } /// \brief Restore the current and previous section from the section stack. /// Calls ChangeSection as needed. /// /// Returns false if the stack was empty. bool PopSection() { if (SectionStack.size() <= 1) return false; auto I = SectionStack.end(); --I; MCSectionSubPair OldSection = I->first; --I; MCSectionSubPair NewSection = I->first; if (OldSection != NewSection) ChangeSection(NewSection.first, NewSection.second); SectionStack.pop_back(); return true; } bool SubSection(const MCExpr *Subsection) { if (SectionStack.empty()) return false; SwitchSection(SectionStack.back().first.first, Subsection); return true; } /// Set the current section where code is being emitted to \p Section. This /// is required to update CurSection. /// /// This corresponds to assembler directives like .section, .text, etc. virtual void SwitchSection(MCSection *Section, const MCExpr *Subsection = nullptr); /// \brief Set the current section where code is being emitted to \p Section. /// This is required to update CurSection. This version does not call /// ChangeSection. void SwitchSectionNoChange(MCSection *Section, const MCExpr *Subsection = nullptr) { assert(Section && "Cannot switch to a null section!"); MCSectionSubPair curSection = SectionStack.back().first; SectionStack.back().second = curSection; if (MCSectionSubPair(Section, Subsection) != curSection) SectionStack.back().first = MCSectionSubPair(Section, Subsection); } /// \brief Create the default sections and set the initial one. virtual void InitSections(bool NoExecStack); MCSymbol *endSection(MCSection *Section); /// \brief Sets the symbol's section. /// /// Each emitted symbol will be tracked in the ordering table, /// so we can sort on them later. void AssignFragment(MCSymbol *Symbol, MCFragment *Fragment); /// \brief Emit a label for \p Symbol into the current section. /// /// This corresponds to an assembler statement such as: /// foo: /// /// \param Symbol - The symbol to emit. A given symbol should only be /// emitted as a label once, and symbols emitted as a label should never be /// used in an assignment. // FIXME: These emission are non-const because we mutate the symbol to // add the section we're emitting it to later. virtual void EmitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc()); virtual void EmitEHSymAttributes(const MCSymbol *Symbol, MCSymbol *EHSymbol); /// \brief Note in the output the specified \p Flag. virtual void EmitAssemblerFlag(MCAssemblerFlag Flag); /// \brief Emit the given list \p Options of strings as linker /// options into the output. virtual void EmitLinkerOptions(ArrayRef Kind) {} /// \brief Note in the output the specified region \p Kind. virtual void EmitDataRegion(MCDataRegionType Kind) {} /// \brief Specify the Mach-O minimum deployment target version. virtual void EmitVersionMin(MCVersionMinType Type, unsigned Major, unsigned Minor, unsigned Update) {} /// Emit/Specify Mach-O build version command. /// \p Platform should be one of MachO::PlatformType. virtual void EmitBuildVersion(unsigned Platform, unsigned Major, unsigned Minor, unsigned Update) {} void EmitVersionForTarget(const Triple &Target); /// \brief Note in the output that the specified \p Func is a Thumb mode /// function (ARM target only). virtual void EmitThumbFunc(MCSymbol *Func); /// \brief Emit an assignment of \p Value to \p Symbol. /// /// This corresponds to an assembler statement such as: /// symbol = value /// /// The assignment generates no code, but has the side effect of binding the /// value in the current context. For the assembly streamer, this prints the /// binding into the .s file. /// /// \param Symbol - The symbol being assigned to. /// \param Value - The value for the symbol. virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value); /// \brief Emit an weak reference from \p Alias to \p Symbol. /// /// This corresponds to an assembler statement such as: /// .weakref alias, symbol /// /// \param Alias - The alias that is being created. /// \param Symbol - The symbol being aliased. virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol); /// \brief Add the given \p Attribute to \p Symbol. virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) = 0; /// \brief Set the \p DescValue for the \p Symbol. /// /// \param Symbol - The symbol to have its n_desc field set. /// \param DescValue - The value to set into the n_desc field. virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue); /// \brief Start emitting COFF symbol definition /// /// \param Symbol - The symbol to have its External & Type fields set. virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol); /// \brief Emit the storage class of the symbol. /// /// \param StorageClass - The storage class the symbol should have. virtual void EmitCOFFSymbolStorageClass(int StorageClass); /// \brief Emit the type of the symbol. /// /// \param Type - A COFF type identifier (see COFF::SymbolType in X86COFF.h) virtual void EmitCOFFSymbolType(int Type); /// \brief Marks the end of the symbol definition. virtual void EndCOFFSymbolDef(); virtual void EmitCOFFSafeSEH(MCSymbol const *Symbol); /// \brief Emits a COFF section index. /// /// \param Symbol - Symbol the section number relocation should point to. virtual void EmitCOFFSectionIndex(MCSymbol const *Symbol); /// \brief Emits a COFF section relative relocation. /// /// \param Symbol - Symbol the section relative relocation should point to. virtual void EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset); /// \brief Emit an ELF .size directive. /// /// This corresponds to an assembler statement such as: /// .size symbol, expression virtual void emitELFSize(MCSymbol *Symbol, const MCExpr *Value); /// \brief Emit an ELF .symver directive. /// /// This corresponds to an assembler statement such as: /// .symver _start, foo@@SOME_VERSION /// \param Alias - The versioned alias (i.e. "foo@@SOME_VERSION") /// \param Aliasee - The aliased symbol (i.e. "_start") virtual void emitELFSymverDirective(MCSymbol *Alias, const MCSymbol *Aliasee); /// \brief Emit a Linker Optimization Hint (LOH) directive. /// \param Args - Arguments of the LOH. virtual void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {} /// \brief Emit a common symbol. /// /// \param Symbol - The common symbol to emit. /// \param Size - The size of the common symbol. /// \param ByteAlignment - The alignment of the symbol if /// non-zero. This must be a power of 2. virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) = 0; /// \brief Emit a local common (.lcomm) symbol. /// /// \param Symbol - The common symbol to emit. /// \param Size - The size of the common symbol. /// \param ByteAlignment - The alignment of the common symbol in bytes. virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment); /// \brief Emit the zerofill section and an optional symbol. /// /// \param Section - The zerofill section to create and or to put the symbol /// \param Symbol - The zerofill symbol to emit, if non-NULL. /// \param Size - The size of the zerofill symbol. /// \param ByteAlignment - The alignment of the zerofill symbol if /// non-zero. This must be a power of 2 on some targets. virtual void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr, uint64_t Size = 0, unsigned ByteAlignment = 0) = 0; /// \brief Emit a thread local bss (.tbss) symbol. /// /// \param Section - The thread local common section. /// \param Symbol - The thread local common symbol to emit. /// \param Size - The size of the symbol. /// \param ByteAlignment - The alignment of the thread local common symbol /// if non-zero. This must be a power of 2 on some targets. virtual void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment = 0); /// @} /// \name Generating Data /// @{ /// \brief Emit the bytes in \p Data into the output. /// /// This is used to implement assembler directives such as .byte, .ascii, /// etc. virtual void EmitBytes(StringRef Data); /// Functionally identical to EmitBytes. When emitting textual assembly, this /// method uses .byte directives instead of .ascii or .asciz for readability. virtual void EmitBinaryData(StringRef Data); /// \brief Emit the expression \p Value into the output as a native /// integer of the given \p Size bytes. /// /// This is used to implement assembler directives such as .word, .quad, /// etc. /// /// \param Value - The value to emit. /// \param Size - The size of the integer (in bytes) to emit. This must /// match a native machine width. /// \param Loc - The location of the expression for error reporting. virtual void EmitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc = SMLoc()); void EmitValue(const MCExpr *Value, unsigned Size, SMLoc Loc = SMLoc()); /// \brief Special case of EmitValue that avoids the client having /// to pass in a MCExpr for constant integers. virtual void EmitIntValue(uint64_t Value, unsigned Size); virtual void EmitULEB128Value(const MCExpr *Value); virtual void EmitSLEB128Value(const MCExpr *Value); /// \brief Special case of EmitULEB128Value that avoids the client having to /// pass in a MCExpr for constant integers. void EmitULEB128IntValue(uint64_t Value); /// \brief Like EmitULEB128Value but pads the output to specific number of /// bytes. void EmitPaddedULEB128IntValue(uint64_t Value, unsigned PadTo); /// \brief Special case of EmitSLEB128Value that avoids the client having to /// pass in a MCExpr for constant integers. void EmitSLEB128IntValue(int64_t Value); /// \brief Special case of EmitValue that avoids the client having to pass in /// a MCExpr for MCSymbols. void EmitSymbolValue(const MCSymbol *Sym, unsigned Size, bool IsSectionRelative = false); /// \brief Emit the expression \p Value into the output as a dtprel /// (64-bit DTP relative) value. /// /// This is used to implement assembler directives such as .dtpreldword on /// targets that support them. virtual void EmitDTPRel64Value(const MCExpr *Value); /// \brief Emit the expression \p Value into the output as a dtprel /// (32-bit DTP relative) value. /// /// This is used to implement assembler directives such as .dtprelword on /// targets that support them. virtual void EmitDTPRel32Value(const MCExpr *Value); /// \brief Emit the expression \p Value into the output as a tprel /// (64-bit TP relative) value. /// /// This is used to implement assembler directives such as .tpreldword on /// targets that support them. virtual void EmitTPRel64Value(const MCExpr *Value); /// \brief Emit the expression \p Value into the output as a tprel /// (32-bit TP relative) value. /// /// This is used to implement assembler directives such as .tprelword on /// targets that support them. virtual void EmitTPRel32Value(const MCExpr *Value); /// \brief Emit the expression \p Value into the output as a gprel64 (64-bit /// GP relative) value. /// /// This is used to implement assembler directives such as .gpdword on /// targets that support them. virtual void EmitGPRel64Value(const MCExpr *Value); /// \brief Emit the expression \p Value into the output as a gprel32 (32-bit /// GP relative) value. /// /// This is used to implement assembler directives such as .gprel32 on /// targets that support them. virtual void EmitGPRel32Value(const MCExpr *Value); /// \brief Emit NumBytes bytes worth of the value specified by FillValue. /// This implements directives such as '.space'. - virtual void emitFill(uint64_t NumBytes, uint8_t FillValue); + void emitFill(uint64_t NumBytes, uint8_t FillValue); /// \brief Emit \p Size bytes worth of the value specified by \p FillValue. /// /// This is used to implement assembler directives such as .space or .skip. /// /// \param NumBytes - The number of bytes to emit. /// \param FillValue - The value to use when filling bytes. /// \param Loc - The location of the expression for error reporting. virtual void emitFill(const MCExpr &NumBytes, uint64_t FillValue, SMLoc Loc = SMLoc()); /// \brief Emit \p NumValues copies of \p Size bytes. Each \p Size bytes is /// taken from the lowest order 4 bytes of \p Expr expression. /// /// This is used to implement assembler directives such as .fill. /// /// \param NumValues - The number of copies of \p Size bytes to emit. /// \param Size - The size (in bytes) of each repeated value. /// \param Expr - The expression from which \p Size bytes are used. virtual void emitFill(uint64_t NumValues, int64_t Size, int64_t Expr); virtual void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr, SMLoc Loc = SMLoc()); /// \brief Emit NumBytes worth of zeros. /// This function properly handles data in virtual sections. void EmitZeros(uint64_t NumBytes); /// \brief Emit some number of copies of \p Value until the byte alignment \p /// ByteAlignment is reached. /// /// If the number of bytes need to emit for the alignment is not a multiple /// of \p ValueSize, then the contents of the emitted fill bytes is /// undefined. /// /// This used to implement the .align assembler directive. /// /// \param ByteAlignment - The alignment to reach. This must be a power of /// two on some targets. /// \param Value - The value to use when filling bytes. /// \param ValueSize - The size of the integer (in bytes) to emit for /// \p Value. This must match a native machine width. /// \param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If /// the alignment cannot be reached in this many bytes, no bytes are /// emitted. virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0, unsigned ValueSize = 1, unsigned MaxBytesToEmit = 0); /// \brief Emit nops until the byte alignment \p ByteAlignment is reached. /// /// This used to align code where the alignment bytes may be executed. This /// can emit different bytes for different sizes to optimize execution. /// /// \param ByteAlignment - The alignment to reach. This must be a power of /// two on some targets. /// \param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If /// the alignment cannot be reached in this many bytes, no bytes are /// emitted. virtual void EmitCodeAlignment(unsigned ByteAlignment, unsigned MaxBytesToEmit = 0); /// \brief Emit some number of copies of \p Value until the byte offset \p /// Offset is reached. /// /// This is used to implement assembler directives such as .org. /// /// \param Offset - The offset to reach. This may be an expression, but the /// expression must be associated with the current section. /// \param Value - The value to use when filling bytes. virtual void emitValueToOffset(const MCExpr *Offset, unsigned char Value, SMLoc Loc); virtual void EmitCodePaddingBasicBlockStart(const MCCodePaddingContext &Context) {} virtual void EmitCodePaddingBasicBlockEnd(const MCCodePaddingContext &Context) {} /// @} /// \brief Switch to a new logical file. This is used to implement the '.file /// "foo.c"' assembler directive. virtual void EmitFileDirective(StringRef Filename); /// \brief Emit the "identifiers" directive. This implements the /// '.ident "version foo"' assembler directive. virtual void EmitIdent(StringRef IdentString) {} /// \brief Associate a filename with a specified logical file number. This /// implements the DWARF2 '.file 4 "foo.c"' assembler directive. virtual unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory, StringRef Filename, unsigned CUID = 0); /// \brief This implements the DWARF2 '.loc fileno lineno ...' assembler /// directive. virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line, unsigned Column, unsigned Flags, unsigned Isa, unsigned Discriminator, StringRef FileName); /// Associate a filename with a specified logical file number, and also /// specify that file's checksum information. This implements the '.cv_file 4 /// "foo.c"' assembler directive. Returns true on success. virtual bool EmitCVFileDirective(unsigned FileNo, StringRef Filename, ArrayRef Checksum, unsigned ChecksumKind); /// \brief Introduces a function id for use with .cv_loc. virtual bool EmitCVFuncIdDirective(unsigned FunctionId); /// \brief Introduces an inline call site id for use with .cv_loc. Includes /// extra information for inline line table generation. virtual bool EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc, unsigned IAFile, unsigned IALine, unsigned IACol, SMLoc Loc); /// \brief This implements the CodeView '.cv_loc' assembler directive. virtual void EmitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line, unsigned Column, bool PrologueEnd, bool IsStmt, StringRef FileName, SMLoc Loc); /// \brief This implements the CodeView '.cv_linetable' assembler directive. virtual void EmitCVLinetableDirective(unsigned FunctionId, const MCSymbol *FnStart, const MCSymbol *FnEnd); /// \brief This implements the CodeView '.cv_inline_linetable' assembler /// directive. virtual void EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId, unsigned SourceFileId, unsigned SourceLineNum, const MCSymbol *FnStartSym, const MCSymbol *FnEndSym); /// \brief This implements the CodeView '.cv_def_range' assembler /// directive. virtual void EmitCVDefRangeDirective( ArrayRef> Ranges, StringRef FixedSizePortion); /// \brief This implements the CodeView '.cv_stringtable' assembler directive. virtual void EmitCVStringTableDirective() {} /// \brief This implements the CodeView '.cv_filechecksums' assembler directive. virtual void EmitCVFileChecksumsDirective() {} /// This implements the CodeView '.cv_filechecksumoffset' assembler /// directive. virtual void EmitCVFileChecksumOffsetDirective(unsigned FileNo) {} /// This implements the CodeView '.cv_fpo_data' assembler directive. virtual void EmitCVFPOData(const MCSymbol *ProcSym, SMLoc Loc = {}) {} /// Emit the absolute difference between two symbols. /// /// \pre Offset of \c Hi is greater than the offset \c Lo. virtual void emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo, unsigned Size); virtual MCSymbol *getDwarfLineTableSymbol(unsigned CUID); virtual void EmitCFISections(bool EH, bool Debug); void EmitCFIStartProc(bool IsSimple); void EmitCFIEndProc(); virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset); virtual void EmitCFIDefCfaOffset(int64_t Offset); virtual void EmitCFIDefCfaRegister(int64_t Register); virtual void EmitCFIOffset(int64_t Register, int64_t Offset); virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding); virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding); virtual void EmitCFIRememberState(); virtual void EmitCFIRestoreState(); virtual void EmitCFISameValue(int64_t Register); virtual void EmitCFIRestore(int64_t Register); virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset); virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment); virtual void EmitCFIEscape(StringRef Values); virtual void EmitCFIReturnColumn(int64_t Register); virtual void EmitCFIGnuArgsSize(int64_t Size); virtual void EmitCFISignalFrame(); virtual void EmitCFIUndefined(int64_t Register); virtual void EmitCFIRegister(int64_t Register1, int64_t Register2); virtual void EmitCFIWindowSave(); virtual void EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc = SMLoc()); virtual void EmitWinCFIEndProc(SMLoc Loc = SMLoc()); virtual void EmitWinCFIStartChained(SMLoc Loc = SMLoc()); virtual void EmitWinCFIEndChained(SMLoc Loc = SMLoc()); virtual void EmitWinCFIPushReg(unsigned Register, SMLoc Loc = SMLoc()); virtual void EmitWinCFISetFrame(unsigned Register, unsigned Offset, SMLoc Loc = SMLoc()); virtual void EmitWinCFIAllocStack(unsigned Size, SMLoc Loc = SMLoc()); virtual void EmitWinCFISaveReg(unsigned Register, unsigned Offset, SMLoc Loc = SMLoc()); virtual void EmitWinCFISaveXMM(unsigned Register, unsigned Offset, SMLoc Loc = SMLoc()); virtual void EmitWinCFIPushFrame(bool Code, SMLoc Loc = SMLoc()); virtual void EmitWinCFIEndProlog(SMLoc Loc = SMLoc()); virtual void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except, SMLoc Loc = SMLoc()); virtual void EmitWinEHHandlerData(SMLoc Loc = SMLoc()); /// Get the .pdata section used for the given section. Typically the given /// section is either the main .text section or some other COMDAT .text /// section, but it may be any section containing code. MCSection *getAssociatedPDataSection(const MCSection *TextSec); /// Get the .xdata section used for the given section. MCSection *getAssociatedXDataSection(const MCSection *TextSec); virtual void EmitSyntaxDirective(); /// \brief Emit a .reloc directive. /// Returns true if the relocation could not be emitted because Name is not /// known. virtual bool EmitRelocDirective(const MCExpr &Offset, StringRef Name, const MCExpr *Expr, SMLoc Loc) { return true; } /// \brief Emit the given \p Instruction into the current section. /// PrintSchedInfo == true then schedul comment should be added to output virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI, bool PrintSchedInfo = false); /// \brief Set the bundle alignment mode from now on in the section. /// The argument is the power of 2 to which the alignment is set. The /// value 0 means turn the bundle alignment off. virtual void EmitBundleAlignMode(unsigned AlignPow2); /// \brief The following instructions are a bundle-locked group. /// /// \param AlignToEnd - If true, the bundle-locked group will be aligned to /// the end of a bundle. virtual void EmitBundleLock(bool AlignToEnd); /// \brief Ends a bundle-locked group. virtual void EmitBundleUnlock(); /// \brief If this file is backed by a assembly streamer, this dumps the /// specified string in the output .s file. This capability is indicated by /// the hasRawTextSupport() predicate. By default this aborts. void EmitRawText(const Twine &String); /// \brief Streamer specific finalization. virtual void FinishImpl(); /// \brief Finish emission of machine code. void Finish(); virtual bool mayHaveInstructions(MCSection &Sec) const { return true; } }; /// Create a dummy machine code streamer, which does nothing. This is useful for /// timing the assembler front end. MCStreamer *createNullStreamer(MCContext &Ctx); /// Create a machine code streamer which will print out assembly for the native /// target, suitable for compiling with a native assembler. /// /// \param InstPrint - If given, the instruction printer to use. If not given /// the MCInst representation will be printed. This method takes ownership of /// InstPrint. /// /// \param CE - If given, a code emitter to use to show the instruction /// encoding inline with the assembly. This method takes ownership of \p CE. /// /// \param TAB - If given, a target asm backend to use to show the fixup /// information in conjunction with encoding information. This method takes /// ownership of \p TAB. /// /// \param ShowInst - Whether to show the MCInst representation inline with /// the assembly. MCStreamer *createAsmStreamer(MCContext &Ctx, std::unique_ptr OS, bool isVerboseAsm, bool useDwarfDirectory, MCInstPrinter *InstPrint, MCCodeEmitter *CE, MCAsmBackend *TAB, bool ShowInst); } // end namespace llvm #endif // LLVM_MC_MCSTREAMER_H Index: head/contrib/llvm/lib/MC/MCAsmStreamer.cpp =================================================================== --- head/contrib/llvm/lib/MC/MCAsmStreamer.cpp (revision 328593) +++ head/contrib/llvm/lib/MC/MCAsmStreamer.cpp (revision 328594) @@ -1,1796 +1,1788 @@ //===- lib/MC/MCAsmStreamer.cpp - Text Assembly Output ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Twine.h" #include "llvm/MC/MCAsmBackend.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCCodeEmitter.h" #include "llvm/MC/MCCodeView.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCFixupKindInfo.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCInstPrinter.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSectionMachO.h" #include "llvm/MC/MCStreamer.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Format.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/LEB128.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/Path.h" #include using namespace llvm; namespace { class MCAsmStreamer final : public MCStreamer { std::unique_ptr OSOwner; formatted_raw_ostream &OS; const MCAsmInfo *MAI; std::unique_ptr InstPrinter; std::unique_ptr Emitter; std::unique_ptr AsmBackend; SmallString<128> ExplicitCommentToEmit; SmallString<128> CommentToEmit; raw_svector_ostream CommentStream; unsigned IsVerboseAsm : 1; unsigned ShowInst : 1; unsigned UseDwarfDirectory : 1; void EmitRegisterName(int64_t Register); void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override; void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override; public: MCAsmStreamer(MCContext &Context, std::unique_ptr os, bool isVerboseAsm, bool useDwarfDirectory, MCInstPrinter *printer, MCCodeEmitter *emitter, MCAsmBackend *asmbackend, bool showInst) : MCStreamer(Context), OSOwner(std::move(os)), OS(*OSOwner), MAI(Context.getAsmInfo()), InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend), CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm), ShowInst(showInst), UseDwarfDirectory(useDwarfDirectory) { assert(InstPrinter); if (IsVerboseAsm) InstPrinter->setCommentStream(CommentStream); } inline void EmitEOL() { // Dump Explicit Comments here. emitExplicitComments(); // If we don't have any comments, just emit a \n. if (!IsVerboseAsm) { OS << '\n'; return; } EmitCommentsAndEOL(); } void EmitSyntaxDirective() override; void EmitCommentsAndEOL(); /// isVerboseAsm - Return true if this streamer supports verbose assembly at /// all. bool isVerboseAsm() const override { return IsVerboseAsm; } /// hasRawTextSupport - We support EmitRawText. bool hasRawTextSupport() const override { return true; } /// AddComment - Add a comment that can be emitted to the generated .s /// file if applicable as a QoI issue to make the output of the compiler /// more readable. This only affects the MCAsmStreamer, and only when /// verbose assembly output is enabled. void AddComment(const Twine &T, bool EOL = true) override; /// AddEncodingComment - Add a comment showing the encoding of an instruction. /// If PrintSchedInfo - is true then the comment sched:[x:y] should // be added to output if it's being supported by target void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &, bool PrintSchedInfo); /// GetCommentOS - Return a raw_ostream that comments can be written to. /// Unlike AddComment, you are required to terminate comments with \n if you /// use this method. raw_ostream &GetCommentOS() override { if (!IsVerboseAsm) return nulls(); // Discard comments unless in verbose asm mode. return CommentStream; } void emitRawComment(const Twine &T, bool TabPrefix = true) override; void addExplicitComment(const Twine &T) override; void emitExplicitComments() override; /// AddBlankLine - Emit a blank line to a .s file to pretty it up. void AddBlankLine() override { EmitEOL(); } /// @name MCStreamer Interface /// @{ void ChangeSection(MCSection *Section, const MCExpr *Subsection) override; void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override; void EmitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc()) override; void EmitAssemblerFlag(MCAssemblerFlag Flag) override; void EmitLinkerOptions(ArrayRef Options) override; void EmitDataRegion(MCDataRegionType Kind) override; void EmitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor, unsigned Update) override; void EmitBuildVersion(unsigned Platform, unsigned Major, unsigned Minor, unsigned Update) override; void EmitThumbFunc(MCSymbol *Func) override; void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override; void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override; bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override; void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override; void BeginCOFFSymbolDef(const MCSymbol *Symbol) override; void EmitCOFFSymbolStorageClass(int StorageClass) override; void EmitCOFFSymbolType(int Type) override; void EndCOFFSymbolDef() override; void EmitCOFFSafeSEH(MCSymbol const *Symbol) override; void EmitCOFFSectionIndex(MCSymbol const *Symbol) override; void EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) override; void emitELFSize(MCSymbol *Symbol, const MCExpr *Value) override; void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) override; /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol. /// /// @param Symbol - The common symbol to emit. /// @param Size - The size of the common symbol. /// @param ByteAlignment - The alignment of the common symbol in bytes. void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) override; void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr, uint64_t Size = 0, unsigned ByteAlignment = 0) override; void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment = 0) override; void EmitBinaryData(StringRef Data) override; void EmitBytes(StringRef Data) override; void EmitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc = SMLoc()) override; void EmitIntValue(uint64_t Value, unsigned Size) override; void EmitULEB128Value(const MCExpr *Value) override; void EmitSLEB128Value(const MCExpr *Value) override; void EmitDTPRel32Value(const MCExpr *Value) override; void EmitDTPRel64Value(const MCExpr *Value) override; void EmitTPRel32Value(const MCExpr *Value) override; void EmitTPRel64Value(const MCExpr *Value) override; void EmitGPRel64Value(const MCExpr *Value) override; void EmitGPRel32Value(const MCExpr *Value) override; - - void emitFill(uint64_t NumBytes, uint8_t FillValue) override; - void emitFill(const MCExpr &NumBytes, uint64_t FillValue, SMLoc Loc = SMLoc()) override; void emitFill(uint64_t NumValues, int64_t Size, int64_t Expr) override; void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr, SMLoc Loc = SMLoc()) override; void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0, unsigned ValueSize = 1, unsigned MaxBytesToEmit = 0) override; void EmitCodeAlignment(unsigned ByteAlignment, unsigned MaxBytesToEmit = 0) override; void emitValueToOffset(const MCExpr *Offset, unsigned char Value, SMLoc Loc) override; void EmitFileDirective(StringRef Filename) override; unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory, StringRef Filename, unsigned CUID = 0) override; void EmitDwarfLocDirective(unsigned FileNo, unsigned Line, unsigned Column, unsigned Flags, unsigned Isa, unsigned Discriminator, StringRef FileName) override; MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override; bool EmitCVFileDirective(unsigned FileNo, StringRef Filename, ArrayRef Checksum, unsigned ChecksumKind) override; bool EmitCVFuncIdDirective(unsigned FuncId) override; bool EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc, unsigned IAFile, unsigned IALine, unsigned IACol, SMLoc Loc) override; void EmitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line, unsigned Column, bool PrologueEnd, bool IsStmt, StringRef FileName, SMLoc Loc) override; void EmitCVLinetableDirective(unsigned FunctionId, const MCSymbol *FnStart, const MCSymbol *FnEnd) override; void EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId, unsigned SourceFileId, unsigned SourceLineNum, const MCSymbol *FnStartSym, const MCSymbol *FnEndSym) override; void EmitCVDefRangeDirective( ArrayRef> Ranges, StringRef FixedSizePortion) override; void EmitCVStringTableDirective() override; void EmitCVFileChecksumsDirective() override; void EmitCVFileChecksumOffsetDirective(unsigned FileNo) override; void EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) override; void EmitIdent(StringRef IdentString) override; void EmitCFISections(bool EH, bool Debug) override; void EmitCFIDefCfa(int64_t Register, int64_t Offset) override; void EmitCFIDefCfaOffset(int64_t Offset) override; void EmitCFIDefCfaRegister(int64_t Register) override; void EmitCFIOffset(int64_t Register, int64_t Offset) override; void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override; void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) override; void EmitCFIRememberState() override; void EmitCFIRestoreState() override; void EmitCFIRestore(int64_t Register) override; void EmitCFISameValue(int64_t Register) override; void EmitCFIRelOffset(int64_t Register, int64_t Offset) override; void EmitCFIAdjustCfaOffset(int64_t Adjustment) override; void EmitCFIEscape(StringRef Values) override; void EmitCFIGnuArgsSize(int64_t Size) override; void EmitCFISignalFrame() override; void EmitCFIUndefined(int64_t Register) override; void EmitCFIRegister(int64_t Register1, int64_t Register2) override; void EmitCFIWindowSave() override; void EmitCFIReturnColumn(int64_t Register) override; void EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) override; void EmitWinCFIEndProc(SMLoc Loc) override; void EmitWinCFIStartChained(SMLoc Loc) override; void EmitWinCFIEndChained(SMLoc Loc) override; void EmitWinCFIPushReg(unsigned Register, SMLoc Loc) override; void EmitWinCFISetFrame(unsigned Register, unsigned Offset, SMLoc Loc) override; void EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) override; void EmitWinCFISaveReg(unsigned Register, unsigned Offset, SMLoc Loc) override; void EmitWinCFISaveXMM(unsigned Register, unsigned Offset, SMLoc Loc) override; void EmitWinCFIPushFrame(bool Code, SMLoc Loc) override; void EmitWinCFIEndProlog(SMLoc Loc) override; void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except, SMLoc Loc) override; void EmitWinEHHandlerData(SMLoc Loc) override; void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI, bool PrintSchedInfo) override; void EmitBundleAlignMode(unsigned AlignPow2) override; void EmitBundleLock(bool AlignToEnd) override; void EmitBundleUnlock() override; bool EmitRelocDirective(const MCExpr &Offset, StringRef Name, const MCExpr *Expr, SMLoc Loc) override; /// EmitRawText - If this file is backed by an assembly streamer, this dumps /// the specified string in the output .s file. This capability is /// indicated by the hasRawTextSupport() predicate. void EmitRawTextImpl(StringRef String) override; void FinishImpl() override; }; } // end anonymous namespace. /// AddComment - Add a comment that can be emitted to the generated .s /// file if applicable as a QoI issue to make the output of the compiler /// more readable. This only affects the MCAsmStreamer, and only when /// verbose assembly output is enabled. /// By deafult EOL is set to true so that each comment goes on its own line. void MCAsmStreamer::AddComment(const Twine &T, bool EOL) { if (!IsVerboseAsm) return; T.toVector(CommentToEmit); if (EOL) CommentToEmit.push_back('\n'); // Place comment in a new line. } void MCAsmStreamer::EmitCommentsAndEOL() { if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) { OS << '\n'; return; } StringRef Comments = CommentToEmit; assert(Comments.back() == '\n' && "Comment array not newline terminated"); do { // Emit a line of comments. OS.PadToColumn(MAI->getCommentColumn()); size_t Position = Comments.find('\n'); OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n'; Comments = Comments.substr(Position+1); } while (!Comments.empty()); CommentToEmit.clear(); } static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) { assert(Bytes > 0 && Bytes <= 8 && "Invalid size!"); return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8)); } void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) { if (TabPrefix) OS << '\t'; OS << MAI->getCommentString() << T; EmitEOL(); } void MCAsmStreamer::addExplicitComment(const Twine &T) { StringRef c = T.getSingleStringRef(); if (c.equals(StringRef(MAI->getSeparatorString()))) return; if (c.startswith(StringRef("//"))) { ExplicitCommentToEmit.append("\t"); ExplicitCommentToEmit.append(MAI->getCommentString()); // drop // ExplicitCommentToEmit.append(c.slice(2, c.size()).str()); } else if (c.startswith(StringRef("/*"))) { size_t p = 2, len = c.size() - 2; // emit each line in comment as separate newline. do { size_t newp = std::min(len, c.find_first_of("\r\n", p)); ExplicitCommentToEmit.append("\t"); ExplicitCommentToEmit.append(MAI->getCommentString()); ExplicitCommentToEmit.append(c.slice(p, newp).str()); // If we have another line in this comment add line if (newp < len) ExplicitCommentToEmit.append("\n"); p = newp + 1; } while (p < len); } else if (c.startswith(StringRef(MAI->getCommentString()))) { ExplicitCommentToEmit.append("\t"); ExplicitCommentToEmit.append(c.str()); } else if (c.front() == '#') { ExplicitCommentToEmit.append("\t"); ExplicitCommentToEmit.append(MAI->getCommentString()); ExplicitCommentToEmit.append(c.slice(1, c.size()).str()); } else assert(false && "Unexpected Assembly Comment"); // full line comments immediately output if (c.back() == '\n') emitExplicitComments(); } void MCAsmStreamer::emitExplicitComments() { StringRef Comments = ExplicitCommentToEmit; if (!Comments.empty()) OS << Comments; ExplicitCommentToEmit.clear(); } void MCAsmStreamer::ChangeSection(MCSection *Section, const MCExpr *Subsection) { assert(Section && "Cannot switch to a null section!"); if (MCTargetStreamer *TS = getTargetStreamer()) { TS->changeSection(getCurrentSectionOnly(), Section, Subsection, OS); } else { Section->PrintSwitchToSection( *MAI, getContext().getObjectFileInfo()->getTargetTriple(), OS, Subsection); } } void MCAsmStreamer::EmitLabel(MCSymbol *Symbol, SMLoc Loc) { MCStreamer::EmitLabel(Symbol, Loc); Symbol->print(OS, MAI); OS << MAI->getLabelSuffix(); EmitEOL(); } void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) { StringRef str = MCLOHIdToName(Kind); #ifndef NDEBUG int NbArgs = MCLOHIdToNbArgs(Kind); assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!"); assert(str != "" && "Invalid LOH name"); #endif OS << "\t" << MCLOHDirectiveName() << " " << str << "\t"; bool IsFirst = true; for (const MCSymbol *Arg : Args) { if (!IsFirst) OS << ", "; IsFirst = false; Arg->print(OS, MAI); } EmitEOL(); } void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) { switch (Flag) { case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break; case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break; case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break; case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break; case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break; } EmitEOL(); } void MCAsmStreamer::EmitLinkerOptions(ArrayRef Options) { assert(!Options.empty() && "At least one option is required!"); OS << "\t.linker_option \"" << Options[0] << '"'; for (ArrayRef::iterator it = Options.begin() + 1, ie = Options.end(); it != ie; ++it) { OS << ", " << '"' << *it << '"'; } EmitEOL(); } void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) { if (!MAI->doesSupportDataRegionDirectives()) return; switch (Kind) { case MCDR_DataRegion: OS << "\t.data_region"; break; case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break; case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break; case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break; case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break; } EmitEOL(); } static const char *getVersionMinDirective(MCVersionMinType Type) { switch (Type) { case MCVM_WatchOSVersionMin: return ".watchos_version_min"; case MCVM_TvOSVersionMin: return ".tvos_version_min"; case MCVM_IOSVersionMin: return ".ios_version_min"; case MCVM_OSXVersionMin: return ".macosx_version_min"; } llvm_unreachable("Invalid MC version min type"); } void MCAsmStreamer::EmitVersionMin(MCVersionMinType Type, unsigned Major, unsigned Minor, unsigned Update) { OS << '\t' << getVersionMinDirective(Type) << ' ' << Major << ", " << Minor; if (Update) OS << ", " << Update; EmitEOL(); } static const char *getPlatformName(MachO::PlatformType Type) { switch (Type) { case MachO::PLATFORM_MACOS: return "macos"; case MachO::PLATFORM_IOS: return "ios"; case MachO::PLATFORM_TVOS: return "tvos"; case MachO::PLATFORM_WATCHOS: return "watchos"; case MachO::PLATFORM_BRIDGEOS: return "bridgeos"; } llvm_unreachable("Invalid Mach-O platform type"); } void MCAsmStreamer::EmitBuildVersion(unsigned Platform, unsigned Major, unsigned Minor, unsigned Update) { const char *PlatformName = getPlatformName((MachO::PlatformType)Platform); OS << "\t.build_version " << PlatformName << ", " << Major << ", " << Minor; if (Update) OS << ", " << Update; EmitEOL(); } void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) { // This needs to emit to a temporary string to get properly quoted // MCSymbols when they have spaces in them. OS << "\t.thumb_func"; // Only Mach-O hasSubsectionsViaSymbols() if (MAI->hasSubsectionsViaSymbols()) { OS << '\t'; Func->print(OS, MAI); } EmitEOL(); } void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) { Symbol->print(OS, MAI); OS << " = "; Value->print(OS, MAI); EmitEOL(); MCStreamer::EmitAssignment(Symbol, Value); } void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) { OS << ".weakref "; Alias->print(OS, MAI); OS << ", "; Symbol->print(OS, MAI); EmitEOL(); } bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) { switch (Attribute) { case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute"); case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object if (!MAI->hasDotTypeDotSizeDirective()) return false; // Symbol attribute not supported OS << "\t.type\t"; Symbol->print(OS, MAI); OS << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%'); switch (Attribute) { default: return false; case MCSA_ELF_TypeFunction: OS << "function"; break; case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break; case MCSA_ELF_TypeObject: OS << "object"; break; case MCSA_ELF_TypeTLS: OS << "tls_object"; break; case MCSA_ELF_TypeCommon: OS << "common"; break; case MCSA_ELF_TypeNoType: OS << "no_type"; break; case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break; } EmitEOL(); return true; case MCSA_Global: // .globl/.global OS << MAI->getGlobalDirective(); break; case MCSA_Hidden: OS << "\t.hidden\t"; break; case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break; case MCSA_Internal: OS << "\t.internal\t"; break; case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break; case MCSA_Local: OS << "\t.local\t"; break; case MCSA_NoDeadStrip: if (!MAI->hasNoDeadStrip()) return false; OS << "\t.no_dead_strip\t"; break; case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break; case MCSA_AltEntry: OS << "\t.alt_entry\t"; break; case MCSA_PrivateExtern: OS << "\t.private_extern\t"; break; case MCSA_Protected: OS << "\t.protected\t"; break; case MCSA_Reference: OS << "\t.reference\t"; break; case MCSA_Weak: OS << MAI->getWeakDirective(); break; case MCSA_WeakDefinition: OS << "\t.weak_definition\t"; break; // .weak_reference case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break; case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break; } Symbol->print(OS, MAI); EmitEOL(); return true; } void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) { OS << ".desc" << ' '; Symbol->print(OS, MAI); OS << ',' << DescValue; EmitEOL(); } void MCAsmStreamer::EmitSyntaxDirective() { if (MAI->getAssemblerDialect() == 1) { OS << "\t.intel_syntax noprefix"; EmitEOL(); } // FIXME: Currently emit unprefix'ed registers. // The intel_syntax directive has one optional argument // with may have a value of prefix or noprefix. } void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) { OS << "\t.def\t "; Symbol->print(OS, MAI); OS << ';'; EmitEOL(); } void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) { OS << "\t.scl\t" << StorageClass << ';'; EmitEOL(); } void MCAsmStreamer::EmitCOFFSymbolType (int Type) { OS << "\t.type\t" << Type << ';'; EmitEOL(); } void MCAsmStreamer::EndCOFFSymbolDef() { OS << "\t.endef"; EmitEOL(); } void MCAsmStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) { OS << "\t.safeseh\t"; Symbol->print(OS, MAI); EmitEOL(); } void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) { OS << "\t.secidx\t"; Symbol->print(OS, MAI); EmitEOL(); } void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) { OS << "\t.secrel32\t"; Symbol->print(OS, MAI); if (Offset != 0) OS << '+' << Offset; EmitEOL(); } void MCAsmStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) { assert(MAI->hasDotTypeDotSizeDirective()); OS << "\t.size\t"; Symbol->print(OS, MAI); OS << ", "; Value->print(OS, MAI); EmitEOL(); } void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) { OS << "\t.comm\t"; Symbol->print(OS, MAI); OS << ',' << Size; if (ByteAlignment != 0) { if (MAI->getCOMMDirectiveAlignmentIsInBytes()) OS << ',' << ByteAlignment; else OS << ',' << Log2_32(ByteAlignment); } EmitEOL(); } /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol. /// /// @param Symbol - The common symbol to emit. /// @param Size - The size of the common symbol. void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlign) { OS << "\t.lcomm\t"; Symbol->print(OS, MAI); OS << ',' << Size; if (ByteAlign > 1) { switch (MAI->getLCOMMDirectiveAlignmentType()) { case LCOMM::NoAlignment: llvm_unreachable("alignment not supported on .lcomm!"); case LCOMM::ByteAlignment: OS << ',' << ByteAlign; break; case LCOMM::Log2Alignment: assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2"); OS << ',' << Log2_32(ByteAlign); break; } } EmitEOL(); } void MCAsmStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) { if (Symbol) AssignFragment(Symbol, &Section->getDummyFragment()); // Note: a .zerofill directive does not switch sections. OS << ".zerofill "; // This is a mach-o specific directive. const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section); OS << MOSection->getSegmentName() << "," << MOSection->getSectionName(); if (Symbol) { OS << ','; Symbol->print(OS, MAI); OS << ',' << Size; if (ByteAlignment != 0) OS << ',' << Log2_32(ByteAlignment); } EmitEOL(); } // .tbss sym, size, align // This depends that the symbol has already been mangled from the original, // e.g. _a. void MCAsmStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) { AssignFragment(Symbol, &Section->getDummyFragment()); assert(Symbol && "Symbol shouldn't be NULL!"); // Instead of using the Section we'll just use the shortcut. // This is a mach-o specific directive and section. OS << ".tbss "; Symbol->print(OS, MAI); OS << ", " << Size; // Output align if we have it. We default to 1 so don't bother printing // that. if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment); EmitEOL(); } static inline char toOctal(int X) { return (X&7)+'0'; } static void PrintQuotedString(StringRef Data, raw_ostream &OS) { OS << '"'; for (unsigned i = 0, e = Data.size(); i != e; ++i) { unsigned char C = Data[i]; if (C == '"' || C == '\\') { OS << '\\' << (char)C; continue; } if (isprint((unsigned char)C)) { OS << (char)C; continue; } switch (C) { case '\b': OS << "\\b"; break; case '\f': OS << "\\f"; break; case '\n': OS << "\\n"; break; case '\r': OS << "\\r"; break; case '\t': OS << "\\t"; break; default: OS << '\\'; OS << toOctal(C >> 6); OS << toOctal(C >> 3); OS << toOctal(C >> 0); break; } } OS << '"'; } void MCAsmStreamer::EmitBytes(StringRef Data) { assert(getCurrentSectionOnly() && "Cannot emit contents before setting section!"); if (Data.empty()) return; // If only single byte is provided or no ascii or asciz directives is // supported, emit as vector of 8bits data. if (Data.size() == 1 || !(MAI->getAscizDirective() || MAI->getAsciiDirective())) { const char *Directive = MAI->getData8bitsDirective(); for (const unsigned char C : Data.bytes()) { OS << Directive << (unsigned)C; EmitEOL(); } return; } // If the data ends with 0 and the target supports .asciz, use it, otherwise // use .ascii if (MAI->getAscizDirective() && Data.back() == 0) { OS << MAI->getAscizDirective(); Data = Data.substr(0, Data.size()-1); } else { OS << MAI->getAsciiDirective(); } PrintQuotedString(Data, OS); EmitEOL(); } void MCAsmStreamer::EmitBinaryData(StringRef Data) { // This is binary data. Print it in a grid of hex bytes for readability. const size_t Cols = 4; for (size_t I = 0, EI = alignTo(Data.size(), Cols); I < EI; I += Cols) { size_t J = I, EJ = std::min(I + Cols, Data.size()); assert(EJ > 0); OS << MAI->getData8bitsDirective(); for (; J < EJ - 1; ++J) OS << format("0x%02x", uint8_t(Data[J])) << ", "; OS << format("0x%02x", uint8_t(Data[J])); EmitEOL(); } } void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) { EmitValue(MCConstantExpr::create(Value, getContext()), Size); } void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc) { assert(Size <= 8 && "Invalid size"); assert(getCurrentSectionOnly() && "Cannot emit contents before setting section!"); const char *Directive = nullptr; switch (Size) { default: break; case 1: Directive = MAI->getData8bitsDirective(); break; case 2: Directive = MAI->getData16bitsDirective(); break; case 4: Directive = MAI->getData32bitsDirective(); break; case 8: Directive = MAI->getData64bitsDirective(); break; } if (!Directive) { int64_t IntValue; if (!Value->evaluateAsAbsolute(IntValue)) report_fatal_error("Don't know how to emit this value."); // We couldn't handle the requested integer size so we fallback by breaking // the request down into several, smaller, integers. // Since sizes greater or equal to "Size" are invalid, we use the greatest // power of 2 that is less than "Size" as our largest piece of granularity. bool IsLittleEndian = MAI->isLittleEndian(); for (unsigned Emitted = 0; Emitted != Size;) { unsigned Remaining = Size - Emitted; // The size of our partial emission must be a power of two less than // Size. unsigned EmissionSize = PowerOf2Floor(std::min(Remaining, Size - 1)); // Calculate the byte offset of our partial emission taking into account // the endianness of the target. unsigned ByteOffset = IsLittleEndian ? Emitted : (Remaining - EmissionSize); uint64_t ValueToEmit = IntValue >> (ByteOffset * 8); // We truncate our partial emission to fit within the bounds of the // emission domain. This produces nicer output and silences potential // truncation warnings when round tripping through another assembler. uint64_t Shift = 64 - EmissionSize * 8; assert(Shift < static_cast( std::numeric_limits::digits) && "undefined behavior"); ValueToEmit &= ~0ULL >> Shift; EmitIntValue(ValueToEmit, EmissionSize); Emitted += EmissionSize; } return; } assert(Directive && "Invalid size for machine code value!"); OS << Directive; if (MCTargetStreamer *TS = getTargetStreamer()) { TS->emitValue(Value); } else { Value->print(OS, MAI); EmitEOL(); } } void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) { int64_t IntValue; if (Value->evaluateAsAbsolute(IntValue)) { EmitULEB128IntValue(IntValue); return; } OS << ".uleb128 "; Value->print(OS, MAI); EmitEOL(); } void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) { int64_t IntValue; if (Value->evaluateAsAbsolute(IntValue)) { EmitSLEB128IntValue(IntValue); return; } OS << ".sleb128 "; Value->print(OS, MAI); EmitEOL(); } void MCAsmStreamer::EmitDTPRel64Value(const MCExpr *Value) { assert(MAI->getDTPRel64Directive() != nullptr); OS << MAI->getDTPRel64Directive(); Value->print(OS, MAI); EmitEOL(); } void MCAsmStreamer::EmitDTPRel32Value(const MCExpr *Value) { assert(MAI->getDTPRel32Directive() != nullptr); OS << MAI->getDTPRel32Directive(); Value->print(OS, MAI); EmitEOL(); } void MCAsmStreamer::EmitTPRel64Value(const MCExpr *Value) { assert(MAI->getTPRel64Directive() != nullptr); OS << MAI->getTPRel64Directive(); Value->print(OS, MAI); EmitEOL(); } void MCAsmStreamer::EmitTPRel32Value(const MCExpr *Value) { assert(MAI->getTPRel32Directive() != nullptr); OS << MAI->getTPRel32Directive(); Value->print(OS, MAI); EmitEOL(); } void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) { assert(MAI->getGPRel64Directive() != nullptr); OS << MAI->getGPRel64Directive(); Value->print(OS, MAI); EmitEOL(); } void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) { assert(MAI->getGPRel32Directive() != nullptr); OS << MAI->getGPRel32Directive(); Value->print(OS, MAI); EmitEOL(); } -/// emitFill - Emit NumBytes bytes worth of the value specified by -/// FillValue. This implements directives such as '.space'. -void MCAsmStreamer::emitFill(uint64_t NumBytes, uint8_t FillValue) { - if (NumBytes == 0) return; - - const MCExpr *E = MCConstantExpr::create(NumBytes, getContext()); - emitFill(*E, FillValue); -} - void MCAsmStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue, SMLoc Loc) { + int64_t IntNumBytes; + if (NumBytes.evaluateAsAbsolute(IntNumBytes) && IntNumBytes == 0) + return; + if (const char *ZeroDirective = MAI->getZeroDirective()) { // FIXME: Emit location directives OS << ZeroDirective; NumBytes.print(OS, MAI); if (FillValue != 0) OS << ',' << (int)FillValue; EmitEOL(); return; } MCStreamer::emitFill(NumBytes, FillValue); } void MCAsmStreamer::emitFill(uint64_t NumValues, int64_t Size, int64_t Expr) { if (NumValues == 0) return; const MCExpr *E = MCConstantExpr::create(NumValues, getContext()); emitFill(*E, Size, Expr); } void MCAsmStreamer::emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr, SMLoc Loc) { // FIXME: Emit location directives OS << "\t.fill\t"; NumValues.print(OS, MAI); OS << ", " << Size << ", 0x"; OS.write_hex(truncateToSize(Expr, 4)); EmitEOL(); } void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value, unsigned ValueSize, unsigned MaxBytesToEmit) { // Some assemblers don't support non-power of two alignments, so we always // emit alignments as a power of two if possible. if (isPowerOf2_32(ByteAlignment)) { switch (ValueSize) { default: llvm_unreachable("Invalid size for machine code value!"); case 1: OS << "\t.p2align\t"; break; case 2: OS << ".p2alignw "; break; case 4: OS << ".p2alignl "; break; case 8: llvm_unreachable("Unsupported alignment size!"); } OS << Log2_32(ByteAlignment); if (Value || MaxBytesToEmit) { OS << ", 0x"; OS.write_hex(truncateToSize(Value, ValueSize)); if (MaxBytesToEmit) OS << ", " << MaxBytesToEmit; } EmitEOL(); return; } // Non-power of two alignment. This is not widely supported by assemblers. // FIXME: Parameterize this based on MAI. switch (ValueSize) { default: llvm_unreachable("Invalid size for machine code value!"); case 1: OS << ".balign"; break; case 2: OS << ".balignw"; break; case 4: OS << ".balignl"; break; case 8: llvm_unreachable("Unsupported alignment size!"); } OS << ' ' << ByteAlignment; OS << ", " << truncateToSize(Value, ValueSize); if (MaxBytesToEmit) OS << ", " << MaxBytesToEmit; EmitEOL(); } void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment, unsigned MaxBytesToEmit) { // Emit with a text fill value. EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(), 1, MaxBytesToEmit); } void MCAsmStreamer::emitValueToOffset(const MCExpr *Offset, unsigned char Value, SMLoc Loc) { // FIXME: Verify that Offset is associated with the current section. OS << ".org "; Offset->print(OS, MAI); OS << ", " << (unsigned)Value; EmitEOL(); } void MCAsmStreamer::EmitFileDirective(StringRef Filename) { assert(MAI->hasSingleParameterDotFile()); OS << "\t.file\t"; PrintQuotedString(Filename, OS); EmitEOL(); } unsigned MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Directory, StringRef Filename, unsigned CUID) { assert(CUID == 0); MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID); unsigned NumFiles = Table.getMCDwarfFiles().size(); FileNo = Table.getFile(Directory, Filename, FileNo); if (FileNo == 0) return 0; if (NumFiles == Table.getMCDwarfFiles().size()) return FileNo; SmallString<128> FullPathName; if (!UseDwarfDirectory && !Directory.empty()) { if (sys::path::is_absolute(Filename)) Directory = ""; else { FullPathName = Directory; sys::path::append(FullPathName, Filename); Directory = ""; Filename = FullPathName; } } SmallString<128> Str; raw_svector_ostream OS1(Str); OS1 << "\t.file\t" << FileNo << ' '; if (!Directory.empty()) { PrintQuotedString(Directory, OS1); OS1 << ' '; } PrintQuotedString(Filename, OS1); if (MCTargetStreamer *TS = getTargetStreamer()) { TS->emitDwarfFileDirective(OS1.str()); } else { EmitRawText(OS1.str()); } return FileNo; } void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line, unsigned Column, unsigned Flags, unsigned Isa, unsigned Discriminator, StringRef FileName) { OS << "\t.loc\t" << FileNo << " " << Line << " " << Column; if (Flags & DWARF2_FLAG_BASIC_BLOCK) OS << " basic_block"; if (Flags & DWARF2_FLAG_PROLOGUE_END) OS << " prologue_end"; if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN) OS << " epilogue_begin"; unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags(); if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) { OS << " is_stmt "; if (Flags & DWARF2_FLAG_IS_STMT) OS << "1"; else OS << "0"; } if (Isa) OS << " isa " << Isa; if (Discriminator) OS << " discriminator " << Discriminator; if (IsVerboseAsm) { OS.PadToColumn(MAI->getCommentColumn()); OS << MAI->getCommentString() << ' ' << FileName << ':' << Line << ':' << Column; } EmitEOL(); this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags, Isa, Discriminator, FileName); } MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) { // Always use the zeroth line table, since asm syntax only supports one line // table for now. return MCStreamer::getDwarfLineTableSymbol(0); } bool MCAsmStreamer::EmitCVFileDirective(unsigned FileNo, StringRef Filename, ArrayRef Checksum, unsigned ChecksumKind) { if (!getContext().getCVContext().addFile(*this, FileNo, Filename, Checksum, ChecksumKind)) return false; OS << "\t.cv_file\t" << FileNo << ' '; PrintQuotedString(Filename, OS); if (!ChecksumKind) { EmitEOL(); return true; } OS << ' '; PrintQuotedString(toHex(Checksum), OS); OS << ' ' << ChecksumKind; EmitEOL(); return true; } bool MCAsmStreamer::EmitCVFuncIdDirective(unsigned FuncId) { OS << "\t.cv_func_id " << FuncId << '\n'; return MCStreamer::EmitCVFuncIdDirective(FuncId); } bool MCAsmStreamer::EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc, unsigned IAFile, unsigned IALine, unsigned IACol, SMLoc Loc) { OS << "\t.cv_inline_site_id " << FunctionId << " within " << IAFunc << " inlined_at " << IAFile << ' ' << IALine << ' ' << IACol << '\n'; return MCStreamer::EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile, IALine, IACol, Loc); } void MCAsmStreamer::EmitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line, unsigned Column, bool PrologueEnd, bool IsStmt, StringRef FileName, SMLoc Loc) { OS << "\t.cv_loc\t" << FunctionId << " " << FileNo << " " << Line << " " << Column; if (PrologueEnd) OS << " prologue_end"; unsigned OldIsStmt = getContext().getCVContext().getCurrentCVLoc().isStmt(); if (IsStmt != OldIsStmt) { OS << " is_stmt "; if (IsStmt) OS << "1"; else OS << "0"; } if (IsVerboseAsm) { OS.PadToColumn(MAI->getCommentColumn()); OS << MAI->getCommentString() << ' ' << FileName << ':' << Line << ':' << Column; } EmitEOL(); this->MCStreamer::EmitCVLocDirective(FunctionId, FileNo, Line, Column, PrologueEnd, IsStmt, FileName, Loc); } void MCAsmStreamer::EmitCVLinetableDirective(unsigned FunctionId, const MCSymbol *FnStart, const MCSymbol *FnEnd) { OS << "\t.cv_linetable\t" << FunctionId << ", "; FnStart->print(OS, MAI); OS << ", "; FnEnd->print(OS, MAI); EmitEOL(); this->MCStreamer::EmitCVLinetableDirective(FunctionId, FnStart, FnEnd); } void MCAsmStreamer::EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId, unsigned SourceFileId, unsigned SourceLineNum, const MCSymbol *FnStartSym, const MCSymbol *FnEndSym) { OS << "\t.cv_inline_linetable\t" << PrimaryFunctionId << ' ' << SourceFileId << ' ' << SourceLineNum << ' '; FnStartSym->print(OS, MAI); OS << ' '; FnEndSym->print(OS, MAI); EmitEOL(); this->MCStreamer::EmitCVInlineLinetableDirective( PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym); } void MCAsmStreamer::EmitCVDefRangeDirective( ArrayRef> Ranges, StringRef FixedSizePortion) { OS << "\t.cv_def_range\t"; for (std::pair Range : Ranges) { OS << ' '; Range.first->print(OS, MAI); OS << ' '; Range.second->print(OS, MAI); } OS << ", "; PrintQuotedString(FixedSizePortion, OS); EmitEOL(); this->MCStreamer::EmitCVDefRangeDirective(Ranges, FixedSizePortion); } void MCAsmStreamer::EmitCVStringTableDirective() { OS << "\t.cv_stringtable"; EmitEOL(); } void MCAsmStreamer::EmitCVFileChecksumsDirective() { OS << "\t.cv_filechecksums"; EmitEOL(); } void MCAsmStreamer::EmitCVFileChecksumOffsetDirective(unsigned FileNo) { OS << "\t.cv_filechecksumoffset\t" << FileNo; EmitEOL(); } void MCAsmStreamer::EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) { OS << "\t.cv_fpo_data\t"; ProcSym->print(OS, MAI); EmitEOL(); } void MCAsmStreamer::EmitIdent(StringRef IdentString) { assert(MAI->hasIdentDirective() && ".ident directive not supported"); OS << "\t.ident\t"; PrintQuotedString(IdentString, OS); EmitEOL(); } void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) { MCStreamer::EmitCFISections(EH, Debug); OS << "\t.cfi_sections "; if (EH) { OS << ".eh_frame"; if (Debug) OS << ", .debug_frame"; } else if (Debug) { OS << ".debug_frame"; } EmitEOL(); } void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) { OS << "\t.cfi_startproc"; if (Frame.IsSimple) OS << " simple"; EmitEOL(); } void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) { MCStreamer::EmitCFIEndProcImpl(Frame); OS << "\t.cfi_endproc"; EmitEOL(); } void MCAsmStreamer::EmitRegisterName(int64_t Register) { if (!MAI->useDwarfRegNumForCFI()) { // User .cfi_* directives can use arbitrary DWARF register numbers, not // just ones that map to LLVM register numbers and have known names. // Fall back to using the original number directly if no name is known. const MCRegisterInfo *MRI = getContext().getRegisterInfo(); int LLVMRegister = MRI->getLLVMRegNumFromEH(Register); if (LLVMRegister != -1) { InstPrinter->printRegName(OS, LLVMRegister); return; } } OS << Register; } void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) { MCStreamer::EmitCFIDefCfa(Register, Offset); OS << "\t.cfi_def_cfa "; EmitRegisterName(Register); OS << ", " << Offset; EmitEOL(); } void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) { MCStreamer::EmitCFIDefCfaOffset(Offset); OS << "\t.cfi_def_cfa_offset " << Offset; EmitEOL(); } static void PrintCFIEscape(llvm::formatted_raw_ostream &OS, StringRef Values) { OS << "\t.cfi_escape "; if (!Values.empty()) { size_t e = Values.size() - 1; for (size_t i = 0; i < e; ++i) OS << format("0x%02x", uint8_t(Values[i])) << ", "; OS << format("0x%02x", uint8_t(Values[e])); } } void MCAsmStreamer::EmitCFIEscape(StringRef Values) { MCStreamer::EmitCFIEscape(Values); PrintCFIEscape(OS, Values); EmitEOL(); } void MCAsmStreamer::EmitCFIGnuArgsSize(int64_t Size) { MCStreamer::EmitCFIGnuArgsSize(Size); uint8_t Buffer[16] = { dwarf::DW_CFA_GNU_args_size }; unsigned Len = encodeULEB128(Size, Buffer + 1) + 1; PrintCFIEscape(OS, StringRef((const char *)&Buffer[0], Len)); EmitEOL(); } void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) { MCStreamer::EmitCFIDefCfaRegister(Register); OS << "\t.cfi_def_cfa_register "; EmitRegisterName(Register); EmitEOL(); } void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) { this->MCStreamer::EmitCFIOffset(Register, Offset); OS << "\t.cfi_offset "; EmitRegisterName(Register); OS << ", " << Offset; EmitEOL(); } void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) { MCStreamer::EmitCFIPersonality(Sym, Encoding); OS << "\t.cfi_personality " << Encoding << ", "; Sym->print(OS, MAI); EmitEOL(); } void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) { MCStreamer::EmitCFILsda(Sym, Encoding); OS << "\t.cfi_lsda " << Encoding << ", "; Sym->print(OS, MAI); EmitEOL(); } void MCAsmStreamer::EmitCFIRememberState() { MCStreamer::EmitCFIRememberState(); OS << "\t.cfi_remember_state"; EmitEOL(); } void MCAsmStreamer::EmitCFIRestoreState() { MCStreamer::EmitCFIRestoreState(); OS << "\t.cfi_restore_state"; EmitEOL(); } void MCAsmStreamer::EmitCFIRestore(int64_t Register) { MCStreamer::EmitCFIRestore(Register); OS << "\t.cfi_restore "; EmitRegisterName(Register); EmitEOL(); } void MCAsmStreamer::EmitCFISameValue(int64_t Register) { MCStreamer::EmitCFISameValue(Register); OS << "\t.cfi_same_value "; EmitRegisterName(Register); EmitEOL(); } void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) { MCStreamer::EmitCFIRelOffset(Register, Offset); OS << "\t.cfi_rel_offset "; EmitRegisterName(Register); OS << ", " << Offset; EmitEOL(); } void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) { MCStreamer::EmitCFIAdjustCfaOffset(Adjustment); OS << "\t.cfi_adjust_cfa_offset " << Adjustment; EmitEOL(); } void MCAsmStreamer::EmitCFISignalFrame() { MCStreamer::EmitCFISignalFrame(); OS << "\t.cfi_signal_frame"; EmitEOL(); } void MCAsmStreamer::EmitCFIUndefined(int64_t Register) { MCStreamer::EmitCFIUndefined(Register); OS << "\t.cfi_undefined " << Register; EmitEOL(); } void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) { MCStreamer::EmitCFIRegister(Register1, Register2); OS << "\t.cfi_register " << Register1 << ", " << Register2; EmitEOL(); } void MCAsmStreamer::EmitCFIWindowSave() { MCStreamer::EmitCFIWindowSave(); OS << "\t.cfi_window_save"; EmitEOL(); } void MCAsmStreamer::EmitCFIReturnColumn(int64_t Register) { MCStreamer::EmitCFIReturnColumn(Register); OS << "\t.cfi_return_column " << Register; EmitEOL(); } void MCAsmStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) { MCStreamer::EmitWinCFIStartProc(Symbol, Loc); OS << ".seh_proc "; Symbol->print(OS, MAI); EmitEOL(); } void MCAsmStreamer::EmitWinCFIEndProc(SMLoc Loc) { MCStreamer::EmitWinCFIEndProc(Loc); OS << "\t.seh_endproc"; EmitEOL(); } void MCAsmStreamer::EmitWinCFIStartChained(SMLoc Loc) { MCStreamer::EmitWinCFIStartChained(Loc); OS << "\t.seh_startchained"; EmitEOL(); } void MCAsmStreamer::EmitWinCFIEndChained(SMLoc Loc) { MCStreamer::EmitWinCFIEndChained(Loc); OS << "\t.seh_endchained"; EmitEOL(); } void MCAsmStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except, SMLoc Loc) { MCStreamer::EmitWinEHHandler(Sym, Unwind, Except, Loc); OS << "\t.seh_handler "; Sym->print(OS, MAI); if (Unwind) OS << ", @unwind"; if (Except) OS << ", @except"; EmitEOL(); } void MCAsmStreamer::EmitWinEHHandlerData(SMLoc Loc) { MCStreamer::EmitWinEHHandlerData(Loc); // Switch sections. Don't call SwitchSection directly, because that will // cause the section switch to be visible in the emitted assembly. // We only do this so the section switch that terminates the handler // data block is visible. WinEH::FrameInfo *CurFrame = getCurrentWinFrameInfo(); MCSection *TextSec = &CurFrame->Function->getSection(); MCSection *XData = getAssociatedXDataSection(TextSec); SwitchSectionNoChange(XData); OS << "\t.seh_handlerdata"; EmitEOL(); } void MCAsmStreamer::EmitWinCFIPushReg(unsigned Register, SMLoc Loc) { MCStreamer::EmitWinCFIPushReg(Register, Loc); OS << "\t.seh_pushreg " << Register; EmitEOL(); } void MCAsmStreamer::EmitWinCFISetFrame(unsigned Register, unsigned Offset, SMLoc Loc) { MCStreamer::EmitWinCFISetFrame(Register, Offset, Loc); OS << "\t.seh_setframe " << Register << ", " << Offset; EmitEOL(); } void MCAsmStreamer::EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) { MCStreamer::EmitWinCFIAllocStack(Size, Loc); OS << "\t.seh_stackalloc " << Size; EmitEOL(); } void MCAsmStreamer::EmitWinCFISaveReg(unsigned Register, unsigned Offset, SMLoc Loc) { MCStreamer::EmitWinCFISaveReg(Register, Offset, Loc); OS << "\t.seh_savereg " << Register << ", " << Offset; EmitEOL(); } void MCAsmStreamer::EmitWinCFISaveXMM(unsigned Register, unsigned Offset, SMLoc Loc) { MCStreamer::EmitWinCFISaveXMM(Register, Offset, Loc); OS << "\t.seh_savexmm " << Register << ", " << Offset; EmitEOL(); } void MCAsmStreamer::EmitWinCFIPushFrame(bool Code, SMLoc Loc) { MCStreamer::EmitWinCFIPushFrame(Code, Loc); OS << "\t.seh_pushframe"; if (Code) OS << " @code"; EmitEOL(); } void MCAsmStreamer::EmitWinCFIEndProlog(SMLoc Loc) { MCStreamer::EmitWinCFIEndProlog(Loc); OS << "\t.seh_endprologue"; EmitEOL(); } void MCAsmStreamer::AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &STI, bool PrintSchedInfo) { raw_ostream &OS = GetCommentOS(); SmallString<256> Code; SmallVector Fixups; raw_svector_ostream VecOS(Code); Emitter->encodeInstruction(Inst, VecOS, Fixups, STI); // If we are showing fixups, create symbolic markers in the encoded // representation. We do this by making a per-bit map to the fixup item index, // then trying to display it as nicely as possible. SmallVector FixupMap; FixupMap.resize(Code.size() * 8); for (unsigned i = 0, e = Code.size() * 8; i != e; ++i) FixupMap[i] = 0; for (unsigned i = 0, e = Fixups.size(); i != e; ++i) { MCFixup &F = Fixups[i]; const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind()); for (unsigned j = 0; j != Info.TargetSize; ++j) { unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j; assert(Index < Code.size() * 8 && "Invalid offset in fixup!"); FixupMap[Index] = 1 + i; } } // FIXME: Note the fixup comments for Thumb2 are completely bogus since the // high order halfword of a 32-bit Thumb2 instruction is emitted first. OS << "encoding: ["; for (unsigned i = 0, e = Code.size(); i != e; ++i) { if (i) OS << ','; // See if all bits are the same map entry. uint8_t MapEntry = FixupMap[i * 8 + 0]; for (unsigned j = 1; j != 8; ++j) { if (FixupMap[i * 8 + j] == MapEntry) continue; MapEntry = uint8_t(~0U); break; } if (MapEntry != uint8_t(~0U)) { if (MapEntry == 0) { OS << format("0x%02x", uint8_t(Code[i])); } else { if (Code[i]) { // FIXME: Some of the 8 bits require fix up. OS << format("0x%02x", uint8_t(Code[i])) << '\'' << char('A' + MapEntry - 1) << '\''; } else OS << char('A' + MapEntry - 1); } } else { // Otherwise, write out in binary. OS << "0b"; for (unsigned j = 8; j--;) { unsigned Bit = (Code[i] >> j) & 1; unsigned FixupBit; if (MAI->isLittleEndian()) FixupBit = i * 8 + j; else FixupBit = i * 8 + (7-j); if (uint8_t MapEntry = FixupMap[FixupBit]) { assert(Bit == 0 && "Encoder wrote into fixed up bit!"); OS << char('A' + MapEntry - 1); } else OS << Bit; } } } OS << "]"; // If we are not going to add fixup or schedule comments after this point // then we have to end the current comment line with "\n". if (Fixups.size() || !PrintSchedInfo) OS << "\n"; for (unsigned i = 0, e = Fixups.size(); i != e; ++i) { MCFixup &F = Fixups[i]; const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind()); OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset() << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n"; } } void MCAsmStreamer::EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI, bool PrintSchedInfo) { assert(getCurrentSectionOnly() && "Cannot emit contents before setting section!"); // Show the encoding in a comment if we have a code emitter. if (Emitter) AddEncodingComment(Inst, STI, PrintSchedInfo); // Show the MCInst if enabled. if (ShowInst) { if (PrintSchedInfo) GetCommentOS() << "\n"; Inst.dump_pretty(GetCommentOS(), InstPrinter.get(), "\n "); GetCommentOS() << "\n"; } if(getTargetStreamer()) getTargetStreamer()->prettyPrintAsm(*InstPrinter, OS, Inst, STI); else InstPrinter->printInst(&Inst, OS, "", STI); if (PrintSchedInfo) { std::string SI = STI.getSchedInfoStr(Inst); if (!SI.empty()) GetCommentOS() << SI; } StringRef Comments = CommentToEmit; if (Comments.size() && Comments.back() != '\n') GetCommentOS() << "\n"; EmitEOL(); } void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) { OS << "\t.bundle_align_mode " << AlignPow2; EmitEOL(); } void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) { OS << "\t.bundle_lock"; if (AlignToEnd) OS << " align_to_end"; EmitEOL(); } void MCAsmStreamer::EmitBundleUnlock() { OS << "\t.bundle_unlock"; EmitEOL(); } bool MCAsmStreamer::EmitRelocDirective(const MCExpr &Offset, StringRef Name, const MCExpr *Expr, SMLoc) { OS << "\t.reloc "; Offset.print(OS, MAI); OS << ", " << Name; if (Expr) { OS << ", "; Expr->print(OS, MAI); } EmitEOL(); return false; } /// EmitRawText - If this file is backed by an assembly streamer, this dumps /// the specified string in the output .s file. This capability is /// indicated by the hasRawTextSupport() predicate. void MCAsmStreamer::EmitRawTextImpl(StringRef String) { if (!String.empty() && String.back() == '\n') String = String.substr(0, String.size()-1); OS << String; EmitEOL(); } void MCAsmStreamer::FinishImpl() { // If we are generating dwarf for assembly source files dump out the sections. if (getContext().getGenDwarfForAssembly()) MCGenDwarfInfo::Emit(this); // Emit the label for the line table, if requested - since the rest of the // line table will be defined by .loc/.file directives, and not emitted // directly, the label is the only work required here. auto &Tables = getContext().getMCDwarfLineTables(); if (!Tables.empty()) { assert(Tables.size() == 1 && "asm output only supports one line table"); if (auto *Label = Tables.begin()->second.getLabel()) { SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection()); EmitLabel(Label); } } } MCStreamer *llvm::createAsmStreamer(MCContext &Context, std::unique_ptr OS, bool isVerboseAsm, bool useDwarfDirectory, MCInstPrinter *IP, MCCodeEmitter *CE, MCAsmBackend *MAB, bool ShowInst) { return new MCAsmStreamer(Context, std::move(OS), isVerboseAsm, useDwarfDirectory, IP, CE, MAB, ShowInst); } Index: head/contrib/llvm/lib/MC/MCObjectStreamer.cpp =================================================================== --- head/contrib/llvm/lib/MC/MCObjectStreamer.cpp (revision 328593) +++ head/contrib/llvm/lib/MC/MCObjectStreamer.cpp (revision 328594) @@ -1,636 +1,632 @@ //===- lib/MC/MCObjectStreamer.cpp - Object File MCStreamer Interface -----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/MC/MCObjectStreamer.h" #include "llvm/ADT/STLExtras.h" #include "llvm/MC/MCAsmBackend.h" #include "llvm/MC/MCAssembler.h" #include "llvm/MC/MCCodeEmitter.h" #include "llvm/MC/MCCodeView.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCDwarf.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCObjectWriter.h" #include "llvm/MC/MCSection.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/SourceMgr.h" using namespace llvm; MCObjectStreamer::MCObjectStreamer(MCContext &Context, std::unique_ptr TAB, raw_pwrite_stream &OS, std::unique_ptr Emitter) : MCStreamer(Context), ObjectWriter(TAB->createObjectWriter(OS)), TAB(std::move(TAB)), Emitter(std::move(Emitter)), Assembler(llvm::make_unique(Context, *this->TAB, *this->Emitter, *ObjectWriter)), EmitEHFrame(true), EmitDebugFrame(false) {} MCObjectStreamer::~MCObjectStreamer() {} void MCObjectStreamer::flushPendingLabels(MCFragment *F, uint64_t FOffset) { if (PendingLabels.empty()) return; if (!F) { F = new MCDataFragment(); MCSection *CurSection = getCurrentSectionOnly(); CurSection->getFragmentList().insert(CurInsertionPoint, F); F->setParent(CurSection); } for (MCSymbol *Sym : PendingLabels) { Sym->setFragment(F); Sym->setOffset(FOffset); } PendingLabels.clear(); } void MCObjectStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo, unsigned Size) { // If not assigned to the same (valid) fragment, fallback. if (!Hi->getFragment() || Hi->getFragment() != Lo->getFragment() || Hi->isVariable() || Lo->isVariable()) { MCStreamer::emitAbsoluteSymbolDiff(Hi, Lo, Size); return; } EmitIntValue(Hi->getOffset() - Lo->getOffset(), Size); } void MCObjectStreamer::reset() { if (Assembler) Assembler->reset(); CurInsertionPoint = MCSection::iterator(); EmitEHFrame = true; EmitDebugFrame = false; PendingLabels.clear(); MCStreamer::reset(); } void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) { if (!getNumFrameInfos()) return; if (EmitEHFrame) MCDwarfFrameEmitter::Emit(*this, MAB, true); if (EmitDebugFrame) MCDwarfFrameEmitter::Emit(*this, MAB, false); } MCFragment *MCObjectStreamer::getCurrentFragment() const { assert(getCurrentSectionOnly() && "No current section!"); if (CurInsertionPoint != getCurrentSectionOnly()->getFragmentList().begin()) return &*std::prev(CurInsertionPoint); return nullptr; } MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() { MCDataFragment *F = dyn_cast_or_null(getCurrentFragment()); // When bundling is enabled, we don't want to add data to a fragment that // already has instructions (see MCELFStreamer::EmitInstToData for details) if (!F || (Assembler->isBundlingEnabled() && !Assembler->getRelaxAll() && F->hasInstructions())) { F = new MCDataFragment(); insert(F); } return F; } MCPaddingFragment *MCObjectStreamer::getOrCreatePaddingFragment() { MCPaddingFragment *F = dyn_cast_or_null(getCurrentFragment()); if (!F) { F = new MCPaddingFragment(); insert(F); } return F; } void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) { Assembler->registerSymbol(Sym); } void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) { MCStreamer::EmitCFISections(EH, Debug); EmitEHFrame = EH; EmitDebugFrame = Debug; } void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc) { MCStreamer::EmitValueImpl(Value, Size, Loc); MCDataFragment *DF = getOrCreateDataFragment(); flushPendingLabels(DF, DF->getContents().size()); MCCVLineEntry::Make(this); MCDwarfLineEntry::Make(this, getCurrentSectionOnly()); // Avoid fixups when possible. int64_t AbsValue; if (Value->evaluateAsAbsolute(AbsValue, getAssembler())) { if (!isUIntN(8 * Size, AbsValue) && !isIntN(8 * Size, AbsValue)) { getContext().reportError( Loc, "value evaluated as " + Twine(AbsValue) + " is out of range."); return; } EmitIntValue(AbsValue, Size); return; } DF->getFixups().push_back( MCFixup::create(DF->getContents().size(), Value, MCFixup::getKindForSize(Size, false), Loc)); DF->getContents().resize(DF->getContents().size() + Size, 0); } MCSymbol *MCObjectStreamer::EmitCFILabel() { MCSymbol *Label = getContext().createTempSymbol("cfi", true); EmitLabel(Label); return Label; } void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) { // We need to create a local symbol to avoid relocations. Frame.Begin = getContext().createTempSymbol(); EmitLabel(Frame.Begin); } void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) { Frame.End = getContext().createTempSymbol(); EmitLabel(Frame.End); } void MCObjectStreamer::EmitLabel(MCSymbol *Symbol, SMLoc Loc) { MCStreamer::EmitLabel(Symbol, Loc); getAssembler().registerSymbol(*Symbol); // If there is a current fragment, mark the symbol as pointing into it. // Otherwise queue the label and set its fragment pointer when we emit the // next fragment. auto *F = dyn_cast_or_null(getCurrentFragment()); if (F && !(getAssembler().isBundlingEnabled() && getAssembler().getRelaxAll())) { Symbol->setFragment(F); Symbol->setOffset(F->getContents().size()); } else { PendingLabels.push_back(Symbol); } } void MCObjectStreamer::EmitLabel(MCSymbol *Symbol, SMLoc Loc, MCFragment *F) { MCStreamer::EmitLabel(Symbol, Loc); getAssembler().registerSymbol(*Symbol); auto *DF = dyn_cast_or_null(F); if (DF) Symbol->setFragment(F); else PendingLabels.push_back(Symbol); } void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) { int64_t IntValue; if (Value->evaluateAsAbsolute(IntValue, getAssembler())) { EmitULEB128IntValue(IntValue); return; } insert(new MCLEBFragment(*Value, false)); } void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) { int64_t IntValue; if (Value->evaluateAsAbsolute(IntValue, getAssembler())) { EmitSLEB128IntValue(IntValue); return; } insert(new MCLEBFragment(*Value, true)); } void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) { report_fatal_error("This file format doesn't support weak aliases."); } void MCObjectStreamer::ChangeSection(MCSection *Section, const MCExpr *Subsection) { changeSectionImpl(Section, Subsection); } bool MCObjectStreamer::changeSectionImpl(MCSection *Section, const MCExpr *Subsection) { assert(Section && "Cannot switch to a null section!"); flushPendingLabels(nullptr); getContext().clearDwarfLocSeen(); bool Created = getAssembler().registerSection(*Section); int64_t IntSubsection = 0; if (Subsection && !Subsection->evaluateAsAbsolute(IntSubsection, getAssembler())) report_fatal_error("Cannot evaluate subsection number"); if (IntSubsection < 0 || IntSubsection > 8192) report_fatal_error("Subsection number out of range"); CurInsertionPoint = Section->getSubsectionInsertionPoint(unsigned(IntSubsection)); return Created; } void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) { getAssembler().registerSymbol(*Symbol); MCStreamer::EmitAssignment(Symbol, Value); } bool MCObjectStreamer::mayHaveInstructions(MCSection &Sec) const { return Sec.hasInstructions(); } void MCObjectStreamer::EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI, bool) { getAssembler().getBackend().handleCodePaddingInstructionBegin(Inst); EmitInstructionImpl(Inst, STI); getAssembler().getBackend().handleCodePaddingInstructionEnd(Inst); } void MCObjectStreamer::EmitInstructionImpl(const MCInst &Inst, const MCSubtargetInfo &STI) { MCStreamer::EmitInstruction(Inst, STI); MCSection *Sec = getCurrentSectionOnly(); Sec->setHasInstructions(true); // Now that a machine instruction has been assembled into this section, make // a line entry for any .loc directive that has been seen. MCCVLineEntry::Make(this); MCDwarfLineEntry::Make(this, getCurrentSectionOnly()); // If this instruction doesn't need relaxation, just emit it as data. MCAssembler &Assembler = getAssembler(); if (!Assembler.getBackend().mayNeedRelaxation(Inst)) { EmitInstToData(Inst, STI); return; } // Otherwise, relax and emit it as data if either: // - The RelaxAll flag was passed // - Bundling is enabled and this instruction is inside a bundle-locked // group. We want to emit all such instructions into the same data // fragment. if (Assembler.getRelaxAll() || (Assembler.isBundlingEnabled() && Sec->isBundleLocked())) { MCInst Relaxed; getAssembler().getBackend().relaxInstruction(Inst, STI, Relaxed); while (getAssembler().getBackend().mayNeedRelaxation(Relaxed)) getAssembler().getBackend().relaxInstruction(Relaxed, STI, Relaxed); EmitInstToData(Relaxed, STI); return; } // Otherwise emit to a separate fragment. EmitInstToFragment(Inst, STI); } void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst, const MCSubtargetInfo &STI) { if (getAssembler().getRelaxAll() && getAssembler().isBundlingEnabled()) llvm_unreachable("All instructions should have already been relaxed"); // Always create a new, separate fragment here, because its size can change // during relaxation. MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI); insert(IF); SmallString<128> Code; raw_svector_ostream VecOS(Code); getAssembler().getEmitter().encodeInstruction(Inst, VecOS, IF->getFixups(), STI); IF->getContents().append(Code.begin(), Code.end()); } #ifndef NDEBUG static const char *const BundlingNotImplementedMsg = "Aligned bundling is not implemented for this object format"; #endif void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) { llvm_unreachable(BundlingNotImplementedMsg); } void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) { llvm_unreachable(BundlingNotImplementedMsg); } void MCObjectStreamer::EmitBundleUnlock() { llvm_unreachable(BundlingNotImplementedMsg); } void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line, unsigned Column, unsigned Flags, unsigned Isa, unsigned Discriminator, StringRef FileName) { // In case we see two .loc directives in a row, make sure the // first one gets a line entry. MCDwarfLineEntry::Make(this, getCurrentSectionOnly()); this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags, Isa, Discriminator, FileName); } static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A, const MCSymbol *B) { MCContext &Context = OS.getContext(); MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; const MCExpr *ARef = MCSymbolRefExpr::create(A, Variant, Context); const MCExpr *BRef = MCSymbolRefExpr::create(B, Variant, Context); const MCExpr *AddrDelta = MCBinaryExpr::create(MCBinaryExpr::Sub, ARef, BRef, Context); return AddrDelta; } static void emitDwarfSetLineAddr(MCObjectStreamer &OS, MCDwarfLineTableParams Params, int64_t LineDelta, const MCSymbol *Label, int PointerSize) { // emit the sequence to set the address OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1); OS.EmitULEB128IntValue(PointerSize + 1); OS.EmitIntValue(dwarf::DW_LNE_set_address, 1); OS.EmitSymbolValue(Label, PointerSize); // emit the sequence for the LineDelta (from 1) and a zero address delta. MCDwarfLineAddr::Emit(&OS, Params, LineDelta, 0); } void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta, const MCSymbol *LastLabel, const MCSymbol *Label, unsigned PointerSize) { if (!LastLabel) { emitDwarfSetLineAddr(*this, Assembler->getDWARFLinetableParams(), LineDelta, Label, PointerSize); return; } const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel); int64_t Res; if (AddrDelta->evaluateAsAbsolute(Res, getAssembler())) { MCDwarfLineAddr::Emit(this, Assembler->getDWARFLinetableParams(), LineDelta, Res); return; } insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta)); } void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel, const MCSymbol *Label) { const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel); int64_t Res; if (AddrDelta->evaluateAsAbsolute(Res, getAssembler())) { MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res); return; } insert(new MCDwarfCallFrameFragment(*AddrDelta)); } void MCObjectStreamer::EmitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line, unsigned Column, bool PrologueEnd, bool IsStmt, StringRef FileName, SMLoc Loc) { // In case we see two .cv_loc directives in a row, make sure the // first one gets a line entry. MCCVLineEntry::Make(this); this->MCStreamer::EmitCVLocDirective(FunctionId, FileNo, Line, Column, PrologueEnd, IsStmt, FileName, Loc); } void MCObjectStreamer::EmitCVLinetableDirective(unsigned FunctionId, const MCSymbol *Begin, const MCSymbol *End) { getContext().getCVContext().emitLineTableForFunction(*this, FunctionId, Begin, End); this->MCStreamer::EmitCVLinetableDirective(FunctionId, Begin, End); } void MCObjectStreamer::EmitCVInlineLinetableDirective( unsigned PrimaryFunctionId, unsigned SourceFileId, unsigned SourceLineNum, const MCSymbol *FnStartSym, const MCSymbol *FnEndSym) { getContext().getCVContext().emitInlineLineTableForFunction( *this, PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym); this->MCStreamer::EmitCVInlineLinetableDirective( PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym); } void MCObjectStreamer::EmitCVDefRangeDirective( ArrayRef> Ranges, StringRef FixedSizePortion) { getContext().getCVContext().emitDefRange(*this, Ranges, FixedSizePortion); this->MCStreamer::EmitCVDefRangeDirective(Ranges, FixedSizePortion); } void MCObjectStreamer::EmitCVStringTableDirective() { getContext().getCVContext().emitStringTable(*this); } void MCObjectStreamer::EmitCVFileChecksumsDirective() { getContext().getCVContext().emitFileChecksums(*this); } void MCObjectStreamer::EmitCVFileChecksumOffsetDirective(unsigned FileNo) { getContext().getCVContext().emitFileChecksumOffset(*this, FileNo); } void MCObjectStreamer::EmitBytes(StringRef Data) { MCCVLineEntry::Make(this); MCDwarfLineEntry::Make(this, getCurrentSectionOnly()); MCDataFragment *DF = getOrCreateDataFragment(); flushPendingLabels(DF, DF->getContents().size()); DF->getContents().append(Data.begin(), Data.end()); } void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value, unsigned ValueSize, unsigned MaxBytesToEmit) { if (MaxBytesToEmit == 0) MaxBytesToEmit = ByteAlignment; insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit)); // Update the maximum alignment on the current section if necessary. MCSection *CurSec = getCurrentSectionOnly(); if (ByteAlignment > CurSec->getAlignment()) CurSec->setAlignment(ByteAlignment); } void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment, unsigned MaxBytesToEmit) { EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit); cast(getCurrentFragment())->setEmitNops(true); } void MCObjectStreamer::emitValueToOffset(const MCExpr *Offset, unsigned char Value, SMLoc Loc) { insert(new MCOrgFragment(*Offset, Value, Loc)); } void MCObjectStreamer::EmitCodePaddingBasicBlockStart( const MCCodePaddingContext &Context) { getAssembler().getBackend().handleCodePaddingBasicBlockStart(this, Context); } void MCObjectStreamer::EmitCodePaddingBasicBlockEnd( const MCCodePaddingContext &Context) { getAssembler().getBackend().handleCodePaddingBasicBlockEnd(Context); } // Associate DTPRel32 fixup with data and resize data area void MCObjectStreamer::EmitDTPRel32Value(const MCExpr *Value) { MCDataFragment *DF = getOrCreateDataFragment(); flushPendingLabels(DF, DF->getContents().size()); DF->getFixups().push_back(MCFixup::create(DF->getContents().size(), Value, FK_DTPRel_4)); DF->getContents().resize(DF->getContents().size() + 4, 0); } // Associate DTPRel64 fixup with data and resize data area void MCObjectStreamer::EmitDTPRel64Value(const MCExpr *Value) { MCDataFragment *DF = getOrCreateDataFragment(); flushPendingLabels(DF, DF->getContents().size()); DF->getFixups().push_back(MCFixup::create(DF->getContents().size(), Value, FK_DTPRel_8)); DF->getContents().resize(DF->getContents().size() + 8, 0); } // Associate TPRel32 fixup with data and resize data area void MCObjectStreamer::EmitTPRel32Value(const MCExpr *Value) { MCDataFragment *DF = getOrCreateDataFragment(); flushPendingLabels(DF, DF->getContents().size()); DF->getFixups().push_back(MCFixup::create(DF->getContents().size(), Value, FK_TPRel_4)); DF->getContents().resize(DF->getContents().size() + 4, 0); } // Associate TPRel64 fixup with data and resize data area void MCObjectStreamer::EmitTPRel64Value(const MCExpr *Value) { MCDataFragment *DF = getOrCreateDataFragment(); flushPendingLabels(DF, DF->getContents().size()); DF->getFixups().push_back(MCFixup::create(DF->getContents().size(), Value, FK_TPRel_8)); DF->getContents().resize(DF->getContents().size() + 8, 0); } // Associate GPRel32 fixup with data and resize data area void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) { MCDataFragment *DF = getOrCreateDataFragment(); flushPendingLabels(DF, DF->getContents().size()); DF->getFixups().push_back( MCFixup::create(DF->getContents().size(), Value, FK_GPRel_4)); DF->getContents().resize(DF->getContents().size() + 4, 0); } // Associate GPRel64 fixup with data and resize data area void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) { MCDataFragment *DF = getOrCreateDataFragment(); flushPendingLabels(DF, DF->getContents().size()); DF->getFixups().push_back( MCFixup::create(DF->getContents().size(), Value, FK_GPRel_4)); DF->getContents().resize(DF->getContents().size() + 8, 0); } bool MCObjectStreamer::EmitRelocDirective(const MCExpr &Offset, StringRef Name, const MCExpr *Expr, SMLoc Loc) { int64_t OffsetValue; if (!Offset.evaluateAsAbsolute(OffsetValue)) llvm_unreachable("Offset is not absolute"); if (OffsetValue < 0) llvm_unreachable("Offset is negative"); MCDataFragment *DF = getOrCreateDataFragment(); flushPendingLabels(DF, DF->getContents().size()); Optional MaybeKind = Assembler->getBackend().getFixupKind(Name); if (!MaybeKind.hasValue()) return true; MCFixupKind Kind = *MaybeKind; if (Expr == nullptr) Expr = MCSymbolRefExpr::create(getContext().createTempSymbol(), getContext()); DF->getFixups().push_back(MCFixup::create(OffsetValue, Expr, Kind, Loc)); return false; } -void MCObjectStreamer::emitFill(uint64_t NumBytes, uint8_t FillValue) { - assert(getCurrentSectionOnly() && "need a section"); - insert(new MCFillFragment(FillValue, NumBytes)); -} - void MCObjectStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue, SMLoc Loc) { MCDataFragment *DF = getOrCreateDataFragment(); flushPendingLabels(DF, DF->getContents().size()); int64_t IntNumBytes; if (!NumBytes.evaluateAsAbsolute(IntNumBytes, getAssembler())) { getContext().reportError(Loc, "expected absolute expression"); return; } - if (IntNumBytes <= 0) { + if (IntNumBytes < 0) { getContext().reportError(Loc, "invalid number of bytes"); return; } - emitFill(IntNumBytes, FillValue); + assert(getCurrentSectionOnly() && "need a section"); + insert(new MCFillFragment(FillValue, IntNumBytes)); } void MCObjectStreamer::emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr, SMLoc Loc) { int64_t IntNumValues; if (!NumValues.evaluateAsAbsolute(IntNumValues, getAssembler())) { getContext().reportError(Loc, "expected absolute expression"); return; } if (IntNumValues < 0) { getContext().getSourceManager()->PrintMessage( Loc, SourceMgr::DK_Warning, "'.fill' directive with negative repeat count has no effect"); return; } MCStreamer::emitFill(IntNumValues, Size, Expr); } void MCObjectStreamer::EmitFileDirective(StringRef Filename) { getAssembler().addFileName(Filename); } void MCObjectStreamer::FinishImpl() { // If we are generating dwarf for assembly source files dump out the sections. if (getContext().getGenDwarfForAssembly()) MCGenDwarfInfo::Emit(this); // Dump out the dwarf file & directory tables and line tables. MCDwarfLineTable::Emit(this, getAssembler().getDWARFLinetableParams()); flushPendingLabels(nullptr); getAssembler().Finish(); } Index: head/contrib/llvm/lib/MC/MCStreamer.cpp =================================================================== --- head/contrib/llvm/lib/MC/MCStreamer.cpp (revision 328593) +++ head/contrib/llvm/lib/MC/MCStreamer.cpp (revision 328594) @@ -1,1012 +1,1011 @@ //===- lib/MC/MCStreamer.cpp - Streaming Machine Code Output --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/MC/MCStreamer.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/BinaryFormat/COFF.h" #include "llvm/MC/MCAsmBackend.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCCodeView.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCDwarf.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCInstPrinter.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCSection.h" #include "llvm/MC/MCSectionCOFF.h" #include "llvm/MC/MCSymbol.h" #include "llvm/MC/MCWin64EH.h" #include "llvm/MC/MCWinEH.h" #include "llvm/Support/Casting.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/LEB128.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" #include #include #include #include using namespace llvm; MCTargetStreamer::MCTargetStreamer(MCStreamer &S) : Streamer(S) { S.setTargetStreamer(this); } // Pin the vtables to this file. MCTargetStreamer::~MCTargetStreamer() = default; void MCTargetStreamer::emitLabel(MCSymbol *Symbol) {} void MCTargetStreamer::finish() {} void MCTargetStreamer::changeSection(const MCSection *CurSection, MCSection *Section, const MCExpr *Subsection, raw_ostream &OS) { Section->PrintSwitchToSection( *Streamer.getContext().getAsmInfo(), Streamer.getContext().getObjectFileInfo()->getTargetTriple(), OS, Subsection); } void MCTargetStreamer::emitDwarfFileDirective(StringRef Directive) { Streamer.EmitRawText(Directive); } void MCTargetStreamer::emitValue(const MCExpr *Value) { SmallString<128> Str; raw_svector_ostream OS(Str); Value->print(OS, Streamer.getContext().getAsmInfo()); Streamer.EmitRawText(OS.str()); } void MCTargetStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {} MCStreamer::MCStreamer(MCContext &Ctx) : Context(Ctx), CurrentWinFrameInfo(nullptr) { SectionStack.push_back(std::pair()); } MCStreamer::~MCStreamer() {} void MCStreamer::reset() { DwarfFrameInfos.clear(); CurrentWinFrameInfo = nullptr; WinFrameInfos.clear(); SymbolOrdering.clear(); SectionStack.clear(); SectionStack.push_back(std::pair()); } raw_ostream &MCStreamer::GetCommentOS() { // By default, discard comments. return nulls(); } void MCStreamer::emitRawComment(const Twine &T, bool TabPrefix) {} void MCStreamer::addExplicitComment(const Twine &T) {} void MCStreamer::emitExplicitComments() {} void MCStreamer::generateCompactUnwindEncodings(MCAsmBackend *MAB) { for (auto &FI : DwarfFrameInfos) FI.CompactUnwindEncoding = (MAB ? MAB->generateCompactUnwindEncoding(FI.Instructions) : 0); } /// EmitIntValue - Special case of EmitValue that avoids the client having to /// pass in a MCExpr for constant integers. void MCStreamer::EmitIntValue(uint64_t Value, unsigned Size) { assert(1 <= Size && Size <= 8 && "Invalid size"); assert((isUIntN(8 * Size, Value) || isIntN(8 * Size, Value)) && "Invalid size"); char buf[8]; const bool isLittleEndian = Context.getAsmInfo()->isLittleEndian(); for (unsigned i = 0; i != Size; ++i) { unsigned index = isLittleEndian ? i : (Size - i - 1); buf[i] = uint8_t(Value >> (index * 8)); } EmitBytes(StringRef(buf, Size)); } /// EmitULEB128Value - Special case of EmitULEB128Value that avoids the /// client having to pass in a MCExpr for constant integers. void MCStreamer::EmitPaddedULEB128IntValue(uint64_t Value, unsigned PadTo) { SmallString<128> Tmp; raw_svector_ostream OSE(Tmp); encodeULEB128(Value, OSE, PadTo); EmitBytes(OSE.str()); } void MCStreamer::EmitULEB128IntValue(uint64_t Value) { EmitPaddedULEB128IntValue(Value, 0); } /// EmitSLEB128Value - Special case of EmitSLEB128Value that avoids the /// client having to pass in a MCExpr for constant integers. void MCStreamer::EmitSLEB128IntValue(int64_t Value) { SmallString<128> Tmp; raw_svector_ostream OSE(Tmp); encodeSLEB128(Value, OSE); EmitBytes(OSE.str()); } void MCStreamer::EmitValue(const MCExpr *Value, unsigned Size, SMLoc Loc) { EmitValueImpl(Value, Size, Loc); } void MCStreamer::EmitSymbolValue(const MCSymbol *Sym, unsigned Size, bool IsSectionRelative) { assert((!IsSectionRelative || Size == 4) && "SectionRelative value requires 4-bytes"); if (!IsSectionRelative) EmitValueImpl(MCSymbolRefExpr::create(Sym, getContext()), Size); else EmitCOFFSecRel32(Sym, /*Offset=*/0); } void MCStreamer::EmitDTPRel64Value(const MCExpr *Value) { report_fatal_error("unsupported directive in streamer"); } void MCStreamer::EmitDTPRel32Value(const MCExpr *Value) { report_fatal_error("unsupported directive in streamer"); } void MCStreamer::EmitTPRel64Value(const MCExpr *Value) { report_fatal_error("unsupported directive in streamer"); } void MCStreamer::EmitTPRel32Value(const MCExpr *Value) { report_fatal_error("unsupported directive in streamer"); } void MCStreamer::EmitGPRel64Value(const MCExpr *Value) { report_fatal_error("unsupported directive in streamer"); } void MCStreamer::EmitGPRel32Value(const MCExpr *Value) { report_fatal_error("unsupported directive in streamer"); } /// Emit NumBytes bytes worth of the value specified by FillValue. /// This implements directives such as '.space'. void MCStreamer::emitFill(uint64_t NumBytes, uint8_t FillValue) { - for (uint64_t i = 0, e = NumBytes; i != e; ++i) - EmitIntValue(FillValue, 1); + emitFill(*MCConstantExpr::create(NumBytes, getContext()), FillValue); } void MCStreamer::emitFill(uint64_t NumValues, int64_t Size, int64_t Expr) { int64_t NonZeroSize = Size > 4 ? 4 : Size; Expr &= ~0ULL >> (64 - NonZeroSize * 8); for (uint64_t i = 0, e = NumValues; i != e; ++i) { EmitIntValue(Expr, NonZeroSize); if (NonZeroSize < Size) EmitIntValue(0, Size - NonZeroSize); } } /// The implementation in this class just redirects to emitFill. void MCStreamer::EmitZeros(uint64_t NumBytes) { emitFill(NumBytes, 0); } unsigned MCStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Directory, StringRef Filename, unsigned CUID) { return getContext().getDwarfFile(Directory, Filename, FileNo, CUID); } void MCStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line, unsigned Column, unsigned Flags, unsigned Isa, unsigned Discriminator, StringRef FileName) { getContext().setCurrentDwarfLoc(FileNo, Line, Column, Flags, Isa, Discriminator); } MCSymbol *MCStreamer::getDwarfLineTableSymbol(unsigned CUID) { MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID); if (!Table.getLabel()) { StringRef Prefix = Context.getAsmInfo()->getPrivateGlobalPrefix(); Table.setLabel( Context.getOrCreateSymbol(Prefix + "line_table_start" + Twine(CUID))); } return Table.getLabel(); } bool MCStreamer::hasUnfinishedDwarfFrameInfo() { return !DwarfFrameInfos.empty() && !DwarfFrameInfos.back().End; } MCDwarfFrameInfo *MCStreamer::getCurrentDwarfFrameInfo() { if (!hasUnfinishedDwarfFrameInfo()) { getContext().reportError(SMLoc(), "this directive must appear between " ".cfi_startproc and .cfi_endproc " "directives"); return nullptr; } return &DwarfFrameInfos.back(); } bool MCStreamer::EmitCVFileDirective(unsigned FileNo, StringRef Filename, ArrayRef Checksum, unsigned ChecksumKind) { return getContext().getCVContext().addFile(*this, FileNo, Filename, Checksum, ChecksumKind); } bool MCStreamer::EmitCVFuncIdDirective(unsigned FunctionId) { return getContext().getCVContext().recordFunctionId(FunctionId); } bool MCStreamer::EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc, unsigned IAFile, unsigned IALine, unsigned IACol, SMLoc Loc) { if (getContext().getCVContext().getCVFunctionInfo(IAFunc) == nullptr) { getContext().reportError(Loc, "parent function id not introduced by " ".cv_func_id or .cv_inline_site_id"); return true; } return getContext().getCVContext().recordInlinedCallSiteId( FunctionId, IAFunc, IAFile, IALine, IACol); } void MCStreamer::EmitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line, unsigned Column, bool PrologueEnd, bool IsStmt, StringRef FileName, SMLoc Loc) { CodeViewContext &CVC = getContext().getCVContext(); MCCVFunctionInfo *FI = CVC.getCVFunctionInfo(FunctionId); if (!FI) return getContext().reportError( Loc, "function id not introduced by .cv_func_id or .cv_inline_site_id"); // Track the section if (FI->Section == nullptr) FI->Section = getCurrentSectionOnly(); else if (FI->Section != getCurrentSectionOnly()) return getContext().reportError( Loc, "all .cv_loc directives for a function must be in the same section"); CVC.setCurrentCVLoc(FunctionId, FileNo, Line, Column, PrologueEnd, IsStmt); } void MCStreamer::EmitCVLinetableDirective(unsigned FunctionId, const MCSymbol *Begin, const MCSymbol *End) {} void MCStreamer::EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId, unsigned SourceFileId, unsigned SourceLineNum, const MCSymbol *FnStartSym, const MCSymbol *FnEndSym) {} void MCStreamer::EmitCVDefRangeDirective( ArrayRef> Ranges, StringRef FixedSizePortion) {} void MCStreamer::EmitEHSymAttributes(const MCSymbol *Symbol, MCSymbol *EHSymbol) { } void MCStreamer::InitSections(bool NoExecStack) { SwitchSection(getContext().getObjectFileInfo()->getTextSection()); } void MCStreamer::AssignFragment(MCSymbol *Symbol, MCFragment *Fragment) { assert(Fragment); Symbol->setFragment(Fragment); // As we emit symbols into a section, track the order so that they can // be sorted upon later. Zero is reserved to mean 'unemitted'. SymbolOrdering[Symbol] = 1 + SymbolOrdering.size(); } void MCStreamer::EmitLabel(MCSymbol *Symbol, SMLoc Loc) { Symbol->redefineIfPossible(); if (!Symbol->isUndefined() || Symbol->isVariable()) return getContext().reportError(Loc, "invalid symbol redefinition"); assert(!Symbol->isVariable() && "Cannot emit a variable symbol!"); assert(getCurrentSectionOnly() && "Cannot emit before setting section!"); assert(!Symbol->getFragment() && "Unexpected fragment on symbol data!"); assert(Symbol->isUndefined() && "Cannot define a symbol twice!"); Symbol->setFragment(&getCurrentSectionOnly()->getDummyFragment()); MCTargetStreamer *TS = getTargetStreamer(); if (TS) TS->emitLabel(Symbol); } void MCStreamer::EmitCFISections(bool EH, bool Debug) { assert(EH || Debug); } void MCStreamer::EmitCFIStartProc(bool IsSimple) { if (hasUnfinishedDwarfFrameInfo()) getContext().reportError( SMLoc(), "starting new .cfi frame before finishing the previous one"); MCDwarfFrameInfo Frame; Frame.IsSimple = IsSimple; EmitCFIStartProcImpl(Frame); const MCAsmInfo* MAI = Context.getAsmInfo(); if (MAI) { for (const MCCFIInstruction& Inst : MAI->getInitialFrameState()) { if (Inst.getOperation() == MCCFIInstruction::OpDefCfa || Inst.getOperation() == MCCFIInstruction::OpDefCfaRegister) { Frame.CurrentCfaRegister = Inst.getRegister(); } } } DwarfFrameInfos.push_back(Frame); } void MCStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) { } void MCStreamer::EmitCFIEndProc() { MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; EmitCFIEndProcImpl(*CurFrame); } void MCStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) { // Put a dummy non-null value in Frame.End to mark that this frame has been // closed. Frame.End = (MCSymbol *)1; } MCSymbol *MCStreamer::EmitCFILabel() { // Return a dummy non-null value so that label fields appear filled in when // generating textual assembly. return (MCSymbol *)1; } void MCStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) { MCSymbol *Label = EmitCFILabel(); MCCFIInstruction Instruction = MCCFIInstruction::createDefCfa(Label, Register, Offset); MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->Instructions.push_back(Instruction); CurFrame->CurrentCfaRegister = static_cast(Register); } void MCStreamer::EmitCFIDefCfaOffset(int64_t Offset) { MCSymbol *Label = EmitCFILabel(); MCCFIInstruction Instruction = MCCFIInstruction::createDefCfaOffset(Label, Offset); MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->Instructions.push_back(Instruction); } void MCStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) { MCSymbol *Label = EmitCFILabel(); MCCFIInstruction Instruction = MCCFIInstruction::createAdjustCfaOffset(Label, Adjustment); MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->Instructions.push_back(Instruction); } void MCStreamer::EmitCFIDefCfaRegister(int64_t Register) { MCSymbol *Label = EmitCFILabel(); MCCFIInstruction Instruction = MCCFIInstruction::createDefCfaRegister(Label, Register); MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->Instructions.push_back(Instruction); CurFrame->CurrentCfaRegister = static_cast(Register); } void MCStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) { MCSymbol *Label = EmitCFILabel(); MCCFIInstruction Instruction = MCCFIInstruction::createOffset(Label, Register, Offset); MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->Instructions.push_back(Instruction); } void MCStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) { MCSymbol *Label = EmitCFILabel(); MCCFIInstruction Instruction = MCCFIInstruction::createRelOffset(Label, Register, Offset); MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->Instructions.push_back(Instruction); } void MCStreamer::EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) { MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->Personality = Sym; CurFrame->PersonalityEncoding = Encoding; } void MCStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) { MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->Lsda = Sym; CurFrame->LsdaEncoding = Encoding; } void MCStreamer::EmitCFIRememberState() { MCSymbol *Label = EmitCFILabel(); MCCFIInstruction Instruction = MCCFIInstruction::createRememberState(Label); MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->Instructions.push_back(Instruction); } void MCStreamer::EmitCFIRestoreState() { // FIXME: Error if there is no matching cfi_remember_state. MCSymbol *Label = EmitCFILabel(); MCCFIInstruction Instruction = MCCFIInstruction::createRestoreState(Label); MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->Instructions.push_back(Instruction); } void MCStreamer::EmitCFISameValue(int64_t Register) { MCSymbol *Label = EmitCFILabel(); MCCFIInstruction Instruction = MCCFIInstruction::createSameValue(Label, Register); MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->Instructions.push_back(Instruction); } void MCStreamer::EmitCFIRestore(int64_t Register) { MCSymbol *Label = EmitCFILabel(); MCCFIInstruction Instruction = MCCFIInstruction::createRestore(Label, Register); MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->Instructions.push_back(Instruction); } void MCStreamer::EmitCFIEscape(StringRef Values) { MCSymbol *Label = EmitCFILabel(); MCCFIInstruction Instruction = MCCFIInstruction::createEscape(Label, Values); MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->Instructions.push_back(Instruction); } void MCStreamer::EmitCFIGnuArgsSize(int64_t Size) { MCSymbol *Label = EmitCFILabel(); MCCFIInstruction Instruction = MCCFIInstruction::createGnuArgsSize(Label, Size); MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->Instructions.push_back(Instruction); } void MCStreamer::EmitCFISignalFrame() { MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->IsSignalFrame = true; } void MCStreamer::EmitCFIUndefined(int64_t Register) { MCSymbol *Label = EmitCFILabel(); MCCFIInstruction Instruction = MCCFIInstruction::createUndefined(Label, Register); MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->Instructions.push_back(Instruction); } void MCStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) { MCSymbol *Label = EmitCFILabel(); MCCFIInstruction Instruction = MCCFIInstruction::createRegister(Label, Register1, Register2); MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->Instructions.push_back(Instruction); } void MCStreamer::EmitCFIWindowSave() { MCSymbol *Label = EmitCFILabel(); MCCFIInstruction Instruction = MCCFIInstruction::createWindowSave(Label); MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->Instructions.push_back(Instruction); } void MCStreamer::EmitCFIReturnColumn(int64_t Register) { MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo(); if (!CurFrame) return; CurFrame->RAReg = Register; } WinEH::FrameInfo *MCStreamer::EnsureValidWinFrameInfo(SMLoc Loc) { const MCAsmInfo *MAI = Context.getAsmInfo(); if (!MAI->usesWindowsCFI()) { getContext().reportError( Loc, ".seh_* directives are not supported on this target"); return nullptr; } if (!CurrentWinFrameInfo || CurrentWinFrameInfo->End) { getContext().reportError( Loc, ".seh_ directive must appear within an active frame"); return nullptr; } return CurrentWinFrameInfo; } void MCStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) { const MCAsmInfo *MAI = Context.getAsmInfo(); if (!MAI->usesWindowsCFI()) return getContext().reportError( Loc, ".seh_* directives are not supported on this target"); if (CurrentWinFrameInfo && !CurrentWinFrameInfo->End) getContext().reportError( Loc, "Starting a function before ending the previous one!"); MCSymbol *StartProc = EmitCFILabel(); WinFrameInfos.emplace_back( llvm::make_unique(Symbol, StartProc)); CurrentWinFrameInfo = WinFrameInfos.back().get(); CurrentWinFrameInfo->TextSection = getCurrentSectionOnly(); } void MCStreamer::EmitWinCFIEndProc(SMLoc Loc) { WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc); if (!CurFrame) return; if (CurFrame->ChainedParent) getContext().reportError(Loc, "Not all chained regions terminated!"); MCSymbol *Label = EmitCFILabel(); CurFrame->End = Label; } void MCStreamer::EmitWinCFIStartChained(SMLoc Loc) { WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc); if (!CurFrame) return; MCSymbol *StartProc = EmitCFILabel(); WinFrameInfos.emplace_back(llvm::make_unique( CurFrame->Function, StartProc, CurFrame)); CurrentWinFrameInfo = WinFrameInfos.back().get(); CurrentWinFrameInfo->TextSection = getCurrentSectionOnly(); } void MCStreamer::EmitWinCFIEndChained(SMLoc Loc) { WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc); if (!CurFrame) return; if (!CurFrame->ChainedParent) return getContext().reportError( Loc, "End of a chained region outside a chained region!"); MCSymbol *Label = EmitCFILabel(); CurFrame->End = Label; CurrentWinFrameInfo = const_cast(CurFrame->ChainedParent); } void MCStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except, SMLoc Loc) { WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc); if (!CurFrame) return; if (CurFrame->ChainedParent) return getContext().reportError( Loc, "Chained unwind areas can't have handlers!"); CurFrame->ExceptionHandler = Sym; if (!Except && !Unwind) getContext().reportError(Loc, "Don't know what kind of handler this is!"); if (Unwind) CurFrame->HandlesUnwind = true; if (Except) CurFrame->HandlesExceptions = true; } void MCStreamer::EmitWinEHHandlerData(SMLoc Loc) { WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc); if (!CurFrame) return; if (CurFrame->ChainedParent) getContext().reportError(Loc, "Chained unwind areas can't have handlers!"); } static MCSection *getWinCFISection(MCContext &Context, unsigned *NextWinCFIID, MCSection *MainCFISec, const MCSection *TextSec) { // If this is the main .text section, use the main unwind info section. if (TextSec == Context.getObjectFileInfo()->getTextSection()) return MainCFISec; const auto *TextSecCOFF = cast(TextSec); unsigned UniqueID = TextSecCOFF->getOrAssignWinCFISectionID(NextWinCFIID); // If this section is COMDAT, this unwind section should be COMDAT associative // with its group. const MCSymbol *KeySym = nullptr; if (TextSecCOFF->getCharacteristics() & COFF::IMAGE_SCN_LNK_COMDAT) KeySym = TextSecCOFF->getCOMDATSymbol(); return Context.getAssociativeCOFFSection(cast(MainCFISec), KeySym, UniqueID); } MCSection *MCStreamer::getAssociatedPDataSection(const MCSection *TextSec) { return getWinCFISection(getContext(), &NextWinCFIID, getContext().getObjectFileInfo()->getPDataSection(), TextSec); } MCSection *MCStreamer::getAssociatedXDataSection(const MCSection *TextSec) { return getWinCFISection(getContext(), &NextWinCFIID, getContext().getObjectFileInfo()->getXDataSection(), TextSec); } void MCStreamer::EmitSyntaxDirective() {} void MCStreamer::EmitWinCFIPushReg(unsigned Register, SMLoc Loc) { WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc); if (!CurFrame) return; MCSymbol *Label = EmitCFILabel(); WinEH::Instruction Inst = Win64EH::Instruction::PushNonVol(Label, Register); CurFrame->Instructions.push_back(Inst); } void MCStreamer::EmitWinCFISetFrame(unsigned Register, unsigned Offset, SMLoc Loc) { WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc); if (!CurFrame) return; if (CurFrame->LastFrameInst >= 0) return getContext().reportError( Loc, "frame register and offset can be set at most once"); if (Offset & 0x0F) return getContext().reportError(Loc, "offset is not a multiple of 16"); if (Offset > 240) return getContext().reportError( Loc, "frame offset must be less than or equal to 240"); MCSymbol *Label = EmitCFILabel(); WinEH::Instruction Inst = Win64EH::Instruction::SetFPReg(Label, Register, Offset); CurFrame->LastFrameInst = CurFrame->Instructions.size(); CurFrame->Instructions.push_back(Inst); } void MCStreamer::EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) { WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc); if (!CurFrame) return; if (Size == 0) return getContext().reportError(Loc, "stack allocation size must be non-zero"); if (Size & 7) return getContext().reportError( Loc, "stack allocation size is not a multiple of 8"); MCSymbol *Label = EmitCFILabel(); WinEH::Instruction Inst = Win64EH::Instruction::Alloc(Label, Size); CurFrame->Instructions.push_back(Inst); } void MCStreamer::EmitWinCFISaveReg(unsigned Register, unsigned Offset, SMLoc Loc) { WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc); if (!CurFrame) return; if (Offset & 7) return getContext().reportError( Loc, "register save offset is not 8 byte aligned"); MCSymbol *Label = EmitCFILabel(); WinEH::Instruction Inst = Win64EH::Instruction::SaveNonVol(Label, Register, Offset); CurFrame->Instructions.push_back(Inst); } void MCStreamer::EmitWinCFISaveXMM(unsigned Register, unsigned Offset, SMLoc Loc) { WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc); if (!CurFrame) return; if (Offset & 0x0F) return getContext().reportError(Loc, "offset is not a multiple of 16"); MCSymbol *Label = EmitCFILabel(); WinEH::Instruction Inst = Win64EH::Instruction::SaveXMM(Label, Register, Offset); CurFrame->Instructions.push_back(Inst); } void MCStreamer::EmitWinCFIPushFrame(bool Code, SMLoc Loc) { WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc); if (!CurFrame) return; if (!CurFrame->Instructions.empty()) return getContext().reportError( Loc, "If present, PushMachFrame must be the first UOP"); MCSymbol *Label = EmitCFILabel(); WinEH::Instruction Inst = Win64EH::Instruction::PushMachFrame(Label, Code); CurFrame->Instructions.push_back(Inst); } void MCStreamer::EmitWinCFIEndProlog(SMLoc Loc) { WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc); if (!CurFrame) return; MCSymbol *Label = EmitCFILabel(); CurFrame->PrologEnd = Label; } void MCStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) { } void MCStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) { } void MCStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {} /// EmitRawText - If this file is backed by an assembly streamer, this dumps /// the specified string in the output .s file. This capability is /// indicated by the hasRawTextSupport() predicate. void MCStreamer::EmitRawTextImpl(StringRef String) { errs() << "EmitRawText called on an MCStreamer that doesn't support it, " " something must not be fully mc'ized\n"; abort(); } void MCStreamer::EmitRawText(const Twine &T) { SmallString<128> Str; EmitRawTextImpl(T.toStringRef(Str)); } void MCStreamer::EmitWindowsUnwindTables() { } void MCStreamer::Finish() { if (!DwarfFrameInfos.empty() && !DwarfFrameInfos.back().End) getContext().reportError(SMLoc(), "Unfinished frame!"); if (!WinFrameInfos.empty() && !WinFrameInfos.back()->End) getContext().reportError(SMLoc(), "Unfinished frame!"); MCTargetStreamer *TS = getTargetStreamer(); if (TS) TS->finish(); FinishImpl(); } void MCStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) { visitUsedExpr(*Value); Symbol->setVariableValue(Value); MCTargetStreamer *TS = getTargetStreamer(); if (TS) TS->emitAssignment(Symbol, Value); } void MCTargetStreamer::prettyPrintAsm(MCInstPrinter &InstPrinter, raw_ostream &OS, const MCInst &Inst, const MCSubtargetInfo &STI) { InstPrinter.printInst(&Inst, OS, "", STI); } void MCStreamer::visitUsedSymbol(const MCSymbol &Sym) { } void MCStreamer::visitUsedExpr(const MCExpr &Expr) { switch (Expr.getKind()) { case MCExpr::Target: cast(Expr).visitUsedExpr(*this); break; case MCExpr::Constant: break; case MCExpr::Binary: { const MCBinaryExpr &BE = cast(Expr); visitUsedExpr(*BE.getLHS()); visitUsedExpr(*BE.getRHS()); break; } case MCExpr::SymbolRef: visitUsedSymbol(cast(Expr).getSymbol()); break; case MCExpr::Unary: visitUsedExpr(*cast(Expr).getSubExpr()); break; } } void MCStreamer::EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI, bool) { // Scan for values. for (unsigned i = Inst.getNumOperands(); i--;) if (Inst.getOperand(i).isExpr()) visitUsedExpr(*Inst.getOperand(i).getExpr()); } void MCStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo, unsigned Size) { // Get the Hi-Lo expression. const MCExpr *Diff = MCBinaryExpr::createSub(MCSymbolRefExpr::create(Hi, Context), MCSymbolRefExpr::create(Lo, Context), Context); const MCAsmInfo *MAI = Context.getAsmInfo(); if (!MAI->doesSetDirectiveSuppressReloc()) { EmitValue(Diff, Size); return; } // Otherwise, emit with .set (aka assignment). MCSymbol *SetLabel = Context.createTempSymbol("set", true); EmitAssignment(SetLabel, Diff); EmitSymbolValue(SetLabel, Size); } void MCStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {} void MCStreamer::EmitThumbFunc(MCSymbol *Func) {} void MCStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {} void MCStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) { llvm_unreachable("this directive only supported on COFF targets"); } void MCStreamer::EndCOFFSymbolDef() { llvm_unreachable("this directive only supported on COFF targets"); } void MCStreamer::EmitFileDirective(StringRef Filename) {} void MCStreamer::EmitCOFFSymbolStorageClass(int StorageClass) { llvm_unreachable("this directive only supported on COFF targets"); } void MCStreamer::EmitCOFFSymbolType(int Type) { llvm_unreachable("this directive only supported on COFF targets"); } void MCStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {} void MCStreamer::emitELFSymverDirective(MCSymbol *Alias, const MCSymbol *Aliasee) {} void MCStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) {} void MCStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) {} void MCStreamer::ChangeSection(MCSection *, const MCExpr *) {} void MCStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {} void MCStreamer::EmitBytes(StringRef Data) {} void MCStreamer::EmitBinaryData(StringRef Data) { EmitBytes(Data); } void MCStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc) { visitUsedExpr(*Value); } void MCStreamer::EmitULEB128Value(const MCExpr *Value) {} void MCStreamer::EmitSLEB128Value(const MCExpr *Value) {} void MCStreamer::emitFill(const MCExpr &NumBytes, uint64_t Value, SMLoc Loc) {} void MCStreamer::emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr, SMLoc Loc) {} void MCStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value, unsigned ValueSize, unsigned MaxBytesToEmit) {} void MCStreamer::EmitCodeAlignment(unsigned ByteAlignment, unsigned MaxBytesToEmit) {} void MCStreamer::emitValueToOffset(const MCExpr *Offset, unsigned char Value, SMLoc Loc) {} void MCStreamer::EmitBundleAlignMode(unsigned AlignPow2) {} void MCStreamer::EmitBundleLock(bool AlignToEnd) {} void MCStreamer::FinishImpl() {} void MCStreamer::EmitBundleUnlock() {} void MCStreamer::SwitchSection(MCSection *Section, const MCExpr *Subsection) { assert(Section && "Cannot switch to a null section!"); MCSectionSubPair curSection = SectionStack.back().first; SectionStack.back().second = curSection; if (MCSectionSubPair(Section, Subsection) != curSection) { ChangeSection(Section, Subsection); SectionStack.back().first = MCSectionSubPair(Section, Subsection); assert(!Section->hasEnded() && "Section already ended"); MCSymbol *Sym = Section->getBeginSymbol(); if (Sym && !Sym->isInSection()) EmitLabel(Sym); } } MCSymbol *MCStreamer::endSection(MCSection *Section) { // TODO: keep track of the last subsection so that this symbol appears in the // correct place. MCSymbol *Sym = Section->getEndSymbol(Context); if (Sym->isInSection()) return Sym; SwitchSection(Section); EmitLabel(Sym); return Sym; } void MCStreamer::EmitVersionForTarget(const Triple &Target) { if (!Target.isOSBinFormatMachO() || !Target.isOSDarwin()) return; // Do we even know the version? if (Target.getOSMajorVersion() == 0) return; unsigned Major; unsigned Minor; unsigned Update; MCVersionMinType VersionType; if (Target.isWatchOS()) { VersionType = MCVM_WatchOSVersionMin; Target.getWatchOSVersion(Major, Minor, Update); } else if (Target.isTvOS()) { VersionType = MCVM_TvOSVersionMin; Target.getiOSVersion(Major, Minor, Update); } else if (Target.isMacOSX()) { VersionType = MCVM_OSXVersionMin; if (!Target.getMacOSXVersion(Major, Minor, Update)) Major = 0; } else { VersionType = MCVM_IOSVersionMin; Target.getiOSVersion(Major, Minor, Update); } if (Major != 0) EmitVersionMin(VersionType, Major, Minor, Update); }