diff --git a/llvm/include/llvm/ADT/Triple.h b/llvm/include/llvm/ADT/Triple.h index 33a53a5a..05fbeb69 100644 --- a/llvm/include/llvm/ADT/Triple.h +++ b/llvm/include/llvm/ADT/Triple.h @@ -183,13 +183,6 @@ class Triple { CoreCLR, LastEnvironmentType = CoreCLR }; - enum ObjectFormatType { - UnknownObjectFormat, - - COFF, - ELF, - MachO, - }; private: std::string Data; @@ -209,16 +202,13 @@ class Triple { /// The parsed Environment type. EnvironmentType Environment; - /// The object format type. - ObjectFormatType ObjectFormat; - public: /// @name Constructors /// @{ /// Default constructor is the same as an empty string and leaves all /// triple fields unknown. - Triple() : Data(), Arch(), Vendor(), OS(), Environment(), ObjectFormat() {} + Triple() : Data(), Arch(), Vendor(), OS(), Environment() {} explicit Triple(const Twine &Str); Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr); @@ -228,8 +218,7 @@ class Triple { bool operator==(const Triple &Other) const { return Arch == Other.Arch && SubArch == Other.SubArch && Vendor == Other.Vendor && OS == Other.OS && - Environment == Other.Environment && - ObjectFormat == Other.ObjectFormat; + Environment == Other.Environment; } /// @} @@ -279,9 +268,6 @@ class Triple { void getEnvironmentVersion(unsigned &Major, unsigned &Minor, unsigned &Micro) const; - /// getFormat - Get the object format for this triple. - ObjectFormatType getObjectFormat() const { return ObjectFormat; } - /// getOSVersion - Parse the version number from the OS name component of the /// triple, if present. /// @@ -519,21 +505,6 @@ class Triple { return getOS() == Triple::Linux; } - /// Tests whether the OS uses the ELF binary format. - bool isOSBinFormatELF() const { - return getObjectFormat() == Triple::ELF; - } - - /// Tests whether the OS uses the COFF binary format. - bool isOSBinFormatCOFF() const { - return getObjectFormat() == Triple::COFF; - } - - /// Tests whether the environment is MachO. - bool isOSBinFormatMachO() const { - return getObjectFormat() == Triple::MachO; - } - /// Tests whether the target is the PS4 CPU bool isPS4CPU() const { return getArch() == Triple::x86_64 && @@ -575,9 +546,6 @@ class Triple { /// to a known type. void setEnvironment(EnvironmentType Kind); - /// setObjectFormat - Set the object file format - void setObjectFormat(ObjectFormatType Kind); - /// setTriple - Set all components to the new triple \p Str. void setTriple(const Twine &Str); diff --git a/llvm/include/llvm/MC/MCAsmInfo.h b/llvm/include/llvm/MC/MCAsmInfo.h index 0b6613ae..7b8ff70e 100644 --- a/llvm/include/llvm/MC/MCAsmInfo.h +++ b/llvm/include/llvm/MC/MCAsmInfo.h @@ -74,18 +74,6 @@ class MCAsmInfo { /// True if target stack grow up. Default is false. bool StackGrowsUp; - /// True if this target has the MachO .subsections_via_symbols directive. - /// Default is false. - bool HasSubsectionsViaSymbols; - - /// True if this is a MachO target that supports the macho-specific .zerofill - /// directive for emitting BSS Symbols. Default is false. - bool HasMachoZeroFillDirective; - - /// True if this is a MachO target that supports the macho-specific .tbss - /// directive for emitting thread local BSS Symbols. Default is false. - bool HasMachoTBSSDirective; - /// True if the compiler should emit a ".reference .constructors_used" or /// ".reference .destructors_used" directive after the static ctor/dtor /// list. This directive is only emitted in Static relocation model. Default @@ -276,10 +264,6 @@ class MCAsmInfo { /// Defaults to false. bool HasIdentDirective; - /// True if this target supports the MachO .no_dead_strip directive. Defaults - /// to false. - bool HasNoDeadStrip; - /// Used to declare a global as being a weak symbol. Defaults to ".weak". const char *WeakDirective; @@ -378,8 +362,6 @@ class MCAsmInfo { /// True if target stack grow up. bool isStackGrowthDirectionUp() const { return StackGrowsUp; } - bool hasSubsectionsViaSymbols() const { return HasSubsectionsViaSymbols; } - // Data directive accessors. const char *getData8bitsDirective() const { return Data8bitsDirective; } @@ -437,8 +419,6 @@ class MCAsmInfo { // Accessors. - bool hasMachoZeroFillDirective() const { return HasMachoZeroFillDirective; } - bool hasMachoTBSSDirective() const { return HasMachoTBSSDirective; } bool hasStaticCtorDtorReferenceInStaticMode() const { return HasStaticCtorDtorReferenceInStaticMode; } @@ -499,7 +479,6 @@ class MCAsmInfo { bool hasDotTypeDotSizeDirective() const { return HasDotTypeDotSizeDirective; } bool hasSingleParameterDotFile() const { return HasSingleParameterDotFile; } bool hasIdentDirective() const { return HasIdentDirective; } - bool hasNoDeadStrip() const { return HasNoDeadStrip; } const char *getWeakDirective() const { return WeakDirective; } const char *getWeakRefDirective() const { return WeakRefDirective; } bool hasWeakDefDirective() const { return HasWeakDefDirective; } diff --git a/llvm/include/llvm/MC/MCAsmInfoCOFF.h b/llvm/include/llvm/MC/MCAsmInfoCOFF.h deleted file mode 100644 index 6dbc1bb4..00000000 --- a/llvm/include/llvm/MC/MCAsmInfoCOFF.h +++ /dev/null @@ -1,33 +0,0 @@ -//===-- MCAsmInfoCOFF.h - COFF asm properties -------------------*- 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_MCASMINFOCOFF_H -#define LLVM_MC_MCASMINFOCOFF_H - -#include "llvm/MC/MCAsmInfo.h" - -namespace llvm { - class MCAsmInfoCOFF : public MCAsmInfo { - protected: - explicit MCAsmInfoCOFF(); - }; - - class MCAsmInfoMicrosoft : public MCAsmInfoCOFF { - protected: - explicit MCAsmInfoMicrosoft(); - }; - - class MCAsmInfoGNUCOFF : public MCAsmInfoCOFF { - protected: - explicit MCAsmInfoGNUCOFF(); - }; -} - - -#endif // LLVM_MC_MCASMINFOCOFF_H diff --git a/llvm/include/llvm/MC/MCAsmInfoDarwin.h b/llvm/include/llvm/MC/MCAsmInfoDarwin.h deleted file mode 100644 index d587c3ce..00000000 --- a/llvm/include/llvm/MC/MCAsmInfoDarwin.h +++ /dev/null @@ -1,29 +0,0 @@ -//===---- MCAsmInfoDarwin.h - Darwin asm properties -------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines target asm properties related what form asm statements -// should take in general on Darwin-based targets -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_MC_MCASMINFODARWIN_H -#define LLVM_MC_MCASMINFODARWIN_H - -#include "llvm/MC/MCAsmInfo.h" - -namespace llvm { - class MCAsmInfoDarwin : public MCAsmInfo { - public: - explicit MCAsmInfoDarwin(); - bool isSectionAtomizableBySymbols(const MCSection &Section) const override; - }; -} - - -#endif // LLVM_MC_MCASMINFODARWIN_H diff --git a/llvm/include/llvm/MC/MCContext.h b/llvm/include/llvm/MC/MCContext.h index e74e592b..55487756 100644 --- a/llvm/include/llvm/MC/MCContext.h +++ b/llvm/include/llvm/MC/MCContext.h @@ -40,9 +40,7 @@ namespace llvm { class MCRegisterInfo; class MCLineSection; class SMLoc; - class MCSectionMachO; class MCSectionELF; - class MCSectionCOFF; /// Context object for machine code objects. This class owns all of the /// sections that it creates. @@ -73,9 +71,7 @@ namespace llvm { /// objects. BumpPtrAllocator Allocator; - SpecificBumpPtrAllocator COFFAllocator; SpecificBumpPtrAllocator ELFAllocator; - SpecificBumpPtrAllocator MachOAllocator; /// Bindings of names to symbols. SymbolTable Symbols; @@ -191,26 +187,7 @@ namespace llvm { } }; - struct COFFSectionKey { - std::string SectionName; - StringRef GroupName; - int SelectionKey; - COFFSectionKey(StringRef SectionName, StringRef GroupName, - int SelectionKey) - : SectionName(SectionName), GroupName(GroupName), - SelectionKey(SelectionKey) {} - bool operator<(const COFFSectionKey &Other) const { - if (SectionName != Other.SectionName) - return SectionName < Other.SectionName; - if (GroupName != Other.GroupName) - return GroupName < Other.GroupName; - return SelectionKey < Other.SelectionKey; - } - }; - - StringMap MachOUniquingMap; std::map ELFUniquingMap; - std::map COFFUniquingMap; StringMap ELFRelSecNames; SpecificBumpPtrAllocator MCSubtargetAllocator; @@ -313,20 +290,6 @@ namespace llvm { /// \name Section Management /// @{ - /// Return the MCSection for the specified mach-o section. This requires - /// the operands to be valid. - MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section, - unsigned TypeAndAttributes, - unsigned Reserved2, SectionKind K, - const char *BeginSymName = nullptr); - - MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section, - unsigned TypeAndAttributes, SectionKind K, - const char *BeginSymName = nullptr) { - return getMachOSection(Segment, Section, TypeAndAttributes, 0, K, - BeginSymName); - } - MCSectionELF *getELFSection(StringRef Section, unsigned Type, unsigned Flags) { return getELFSection(Section, Type, Flags, nullptr); @@ -377,24 +340,6 @@ namespace llvm { MCSectionELF *createELFGroupSection(const MCSymbolELF *Group); - MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics, - SectionKind Kind, StringRef COMDATSymName, - int Selection, - const char *BeginSymName = nullptr); - - MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics, - SectionKind Kind, - const char *BeginSymName = nullptr); - - MCSectionCOFF *getCOFFSection(StringRef Section); - - /// Gets or creates a section equivalent to Sec that is associated with the - /// section containing KeySym. For example, to create a debug info section - /// associated with an inline function, pass the normal debug info section - /// as Sec and the function symbol as KeySym. - MCSectionCOFF *getAssociativeCOFFSection(MCSectionCOFF *Sec, - const MCSymbol *KeySym); - // Create and save a copy of STI and return a reference to the copy. MCSubtargetInfo &getSubtargetCopy(const MCSubtargetInfo &STI); diff --git a/llvm/include/llvm/MC/MCELFStreamer.h b/llvm/include/llvm/MC/MCELFStreamer.h index f5f5e686..0195518b 100644 --- a/llvm/include/llvm/MC/MCELFStreamer.h +++ b/llvm/include/llvm/MC/MCELFStreamer.h @@ -53,10 +53,6 @@ class MCELFStreamer : public MCObjectStreamer { void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override; void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) override; - void BeginCOFFSymbolDef(const MCSymbol *Symbol) override; - void EmitCOFFSymbolStorageClass(int StorageClass) override; - void EmitCOFFSymbolType(int Type) override; - void EndCOFFSymbolDef() override; void emitELFSize(MCSymbolELF *Symbol, const MCExpr *Value) override; diff --git a/llvm/include/llvm/MC/MCExpr.h b/llvm/include/llvm/MC/MCExpr.h index 755e67d0..739b2ce4 100644 --- a/llvm/include/llvm/MC/MCExpr.h +++ b/llvm/include/llvm/MC/MCExpr.h @@ -278,8 +278,6 @@ class MCSymbolRefExpr : public MCExpr { VK_Mips_PCREL_HI16, VK_Mips_PCREL_LO16, - VK_COFF_IMGREL32, // symbol@imgrel (image-relative) - VK_Hexagon_PCREL, VK_Hexagon_LO16, VK_Hexagon_HI16, @@ -304,9 +302,6 @@ class MCSymbolRefExpr : public MCExpr { /// Specifies how the variant kind should be printed. const unsigned UseParensForSymbolVariant : 1; - // FIXME: Remove this bit. - const unsigned HasSubsectionsViaSymbols : 1; - /// The symbol being referenced. const MCSymbol *Symbol; @@ -336,8 +331,6 @@ class MCSymbolRefExpr : public MCExpr { void printVariantKind(raw_ostream &OS) const; - bool hasSubsectionsViaSymbols() const { return HasSubsectionsViaSymbols; } - /// @} /// \name Static Utility Functions /// @{ diff --git a/llvm/include/llvm/MC/MCObjectFileInfo.h b/llvm/include/llvm/MC/MCObjectFileInfo.h index 1598f528..3b85dc95 100644 --- a/llvm/include/llvm/MC/MCObjectFileInfo.h +++ b/llvm/include/llvm/MC/MCObjectFileInfo.h @@ -125,21 +125,18 @@ class MCObjectFileInfo { /// Section for newer gnu pubtypes. MCSection *DwarfGnuPubTypesSection; - MCSection *COFFDebugSymbolsSection; - MCSection *COFFDebugTypesSection; - /// Extra TLS Variable Data section. /// /// If the target needs to put additional information for a TLS variable, /// it'll go here. MCSection *TLSExtraDataSection; - /// Section directive for Thread Local data. ELF, MachO and COFF. + /// Section directive for Thread Local data. ELF. MCSection *TLSDataSection; // Defaults to ".tdata". /// Section directive for Thread Local uninitialized data. /// - /// Null if this target doesn't support a BSS section. ELF and MachO only. + /// Null if this target doesn't support a BSS section. ELF only. MCSection *TLSBSSSection; // Defaults to ".tbss". /// StackMap section. @@ -184,12 +181,6 @@ class MCObjectFileInfo { MCSection *LazySymbolPointerSection; MCSection *NonLazySymbolPointerSection; - /// COFF specific sections. - MCSection *DrectveSection; - MCSection *PDataSection; - MCSection *XDataSection; - MCSection *SXDataSection; - public: void InitMCObjectFileInfo(const Triple &TT, MCContext &ctx); @@ -266,13 +257,6 @@ class MCObjectFileInfo { MCSection *getDwarfCUIndexSection() const { return DwarfCUIndexSection; } MCSection *getDwarfTUIndexSection() const { return DwarfTUIndexSection; } - MCSection *getCOFFDebugSymbolsSection() const { - return COFFDebugSymbolsSection; - } - MCSection *getCOFFDebugTypesSection() const { - return COFFDebugTypesSection; - } - MCSection *getTLSExtraDataSection() const { return TLSExtraDataSection; } const MCSection *getTLSDataSection() const { return TLSDataSection; } @@ -324,17 +308,11 @@ class MCObjectFileInfo { return NonLazySymbolPointerSection; } - // COFF specific sections. - MCSection *getDrectveSection() const { return DrectveSection; } - MCSection *getPDataSection() const { return PDataSection; } - MCSection *getXDataSection() const { return XDataSection; } - MCSection *getSXDataSection() const { return SXDataSection; } - MCSection *getEHFrameSection() { return EHFrameSection; } - enum Environment { IsMachO, IsELF, IsCOFF }; + enum Environment { IsELF }; Environment getObjectFileType() const { return Env; } private: @@ -342,9 +320,7 @@ class MCObjectFileInfo { MCContext *Ctx; Triple TT; - void initMachOMCObjectFileInfo(Triple T); void initELFMCObjectFileInfo(Triple T); - void initCOFFMCObjectFileInfo(Triple T); public: const Triple &getTargetTriple() const { return TT; } diff --git a/llvm/include/llvm/MC/MCSection.h b/llvm/include/llvm/MC/MCSection.h index 09a98929..86c97315 100644 --- a/llvm/include/llvm/MC/MCSection.h +++ b/llvm/include/llvm/MC/MCSection.h @@ -48,7 +48,7 @@ struct ilist_node_traits { /// current translation unit. The MCContext class uniques and creates these. class MCSection { public: - enum SectionVariant { SV_COFF = 0, SV_ELF, SV_MachO }; + enum SectionVariant { SV_ELF = 0 }; /// \brief Express the state of bundle locked groups while emitting code. enum BundleLockStateType { diff --git a/llvm/include/llvm/MC/MCSectionCOFF.h b/llvm/include/llvm/MC/MCSectionCOFF.h deleted file mode 100644 index d94682c8..00000000 --- a/llvm/include/llvm/MC/MCSectionCOFF.h +++ /dev/null @@ -1,79 +0,0 @@ -//===- MCSectionCOFF.h - COFF Machine Code Sections -------------*- 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 MCSectionCOFF class. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_MC_MCSECTIONCOFF_H -#define LLVM_MC_MCSECTIONCOFF_H - -#include "llvm/ADT/StringRef.h" -#include "llvm/MC/MCSection.h" - -namespace llvm { -class MCSymbol; - -/// This represents a section on Windows -class MCSectionCOFF final : public MCSection { - // The memory for this string is stored in the same MCContext as *this. - StringRef SectionName; - - // FIXME: The following fields should not be mutable, but are for now so the - // asm parser can honor the .linkonce directive. - - /// This is the Characteristics field of a section, drawn from the enums - /// below. - mutable unsigned Characteristics; - - /// The COMDAT symbol of this section. Only valid if this is a COMDAT section. - /// Two COMDAT sections are merged if they have the same COMDAT symbol. - MCSymbol *COMDATSymbol; - - /// This is the Selection field for the section symbol, if it is a COMDAT - /// section (Characteristics & IMAGE_SCN_LNK_COMDAT) != 0 - mutable int Selection; - -private: - friend class MCContext; - MCSectionCOFF(StringRef Section, unsigned Characteristics, - MCSymbol *COMDATSymbol, int Selection, SectionKind K, - MCSymbol *Begin) - : MCSection(SV_COFF, K, Begin), SectionName(Section), - Characteristics(Characteristics), COMDATSymbol(COMDATSymbol), - Selection(Selection) { - assert((Characteristics & 0x00F00000) == 0 && - "alignment must not be set upon section creation"); - } - -public: - ~MCSectionCOFF(); - - /// Decides whether a '.section' directive should be printed before the - /// section name - bool ShouldOmitSectionDirective(StringRef Name, const MCAsmInfo &MAI) const; - - StringRef getSectionName() const { return SectionName; } - unsigned getCharacteristics() const { return Characteristics; } - MCSymbol *getCOMDATSymbol() const { return COMDATSymbol; } - int getSelection() const { return Selection; } - - void setSelection(int Selection) const; - - void PrintSwitchToSection(const MCAsmInfo &MAI, raw_ostream &OS, - const MCExpr *Subsection) const override; - bool UseCodeAlign() const override; - bool isVirtualSection() const override; - - static bool classof(const MCSection *S) { return S->getVariant() == SV_COFF; } -}; - -} // end namespace llvm - -#endif diff --git a/llvm/include/llvm/MC/MCSectionMachO.h b/llvm/include/llvm/MC/MCSectionMachO.h deleted file mode 100644 index 658dfcda..00000000 --- a/llvm/include/llvm/MC/MCSectionMachO.h +++ /dev/null @@ -1,91 +0,0 @@ -//===- MCSectionMachO.h - MachO Machine Code Sections -----------*- 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 MCSectionMachO class. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_MC_MCSECTIONMACHO_H -#define LLVM_MC_MCSECTIONMACHO_H - -#include "llvm/ADT/StringRef.h" -#include "llvm/MC/MCSection.h" -#include "llvm/Support/MachO.h" - -namespace llvm { - -/// This represents a section on a Mach-O system (used by Mac OS X). On a Mac -/// system, these are also described in /usr/include/mach-o/loader.h. -class MCSectionMachO final : public MCSection { - char SegmentName[16]; // Not necessarily null terminated! - char SectionName[16]; // Not necessarily null terminated! - - /// This is the SECTION_TYPE and SECTION_ATTRIBUTES field of a section, drawn - /// from the enums below. - unsigned TypeAndAttributes; - - /// The 'reserved2' field of a section, used to represent the size of stubs, - /// for example. - unsigned Reserved2; - - MCSectionMachO(StringRef Segment, StringRef Section, unsigned TAA, - unsigned reserved2, SectionKind K, MCSymbol *Begin); - friend class MCContext; -public: - - StringRef getSegmentName() const { - // SegmentName is not necessarily null terminated! - if (SegmentName[15]) - return StringRef(SegmentName, 16); - return StringRef(SegmentName); - } - StringRef getSectionName() const { - // SectionName is not necessarily null terminated! - if (SectionName[15]) - return StringRef(SectionName, 16); - return StringRef(SectionName); - } - - unsigned getTypeAndAttributes() const { return TypeAndAttributes; } - unsigned getStubSize() const { return Reserved2; } - - MachO::SectionType getType() const { - return static_cast(TypeAndAttributes & - MachO::SECTION_TYPE); - } - bool hasAttribute(unsigned Value) const { - return (TypeAndAttributes & Value) != 0; - } - - /// Parse the section specifier indicated by "Spec". This is a string that can - /// appear after a .section directive in a mach-o flavored .s file. If - /// successful, this fills in the specified Out parameters and returns an - /// empty string. When an invalid section specifier is present, this returns - /// a string indicating the problem. If no TAA was parsed, TAA is not altered, - /// and TAAWasSet becomes false. - static std::string ParseSectionSpecifier(StringRef Spec, // In. - StringRef &Segment, // Out. - StringRef &Section, // Out. - unsigned &TAA, // Out. - bool &TAAParsed, // Out. - unsigned &StubSize); // Out. - - void PrintSwitchToSection(const MCAsmInfo &MAI, raw_ostream &OS, - const MCExpr *Subsection) const override; - bool UseCodeAlign() const override; - bool isVirtualSection() const override; - - static bool classof(const MCSection *S) { - return S->getVariant() == SV_MachO; - } -}; - -} // end namespace llvm - -#endif diff --git a/llvm/include/llvm/MC/MCStreamer.h b/llvm/include/llvm/MC/MCStreamer.h index e9d301ad..ea46ad63 100644 --- a/llvm/include/llvm/MC/MCStreamer.h +++ b/llvm/include/llvm/MC/MCStreamer.h @@ -425,36 +425,6 @@ class MCStreamer { /// \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); - /// \brief Emit an ELF .size directive. /// /// This corresponds to an assembler statement such as: diff --git a/llvm/include/llvm/MC/MCSymbol.h b/llvm/include/llvm/MC/MCSymbol.h index c51ecfcb..e6741146 100644 --- a/llvm/include/llvm/MC/MCSymbol.h +++ b/llvm/include/llvm/MC/MCSymbol.h @@ -42,9 +42,7 @@ class MCSymbol { /// class is actually one of the appropriate subclasses of MCSymbol. enum SymbolKind { SymbolKindUnset, - SymbolKindCOFF, SymbolKindELF, - SymbolKindMachO, }; /// A symbol can contain an Offset, or Value, or be Common, but never more @@ -277,10 +275,6 @@ class MCSymbol { bool isELF() const { return Kind == SymbolKindELF; } - bool isCOFF() const { return Kind == SymbolKindCOFF; } - - bool isMachO() const { return Kind == SymbolKindMachO; } - /// @} /// \name Variable Symbols /// @{ diff --git a/llvm/include/llvm/MC/MCSymbolCOFF.h b/llvm/include/llvm/MC/MCSymbolCOFF.h deleted file mode 100644 index 2172c679..00000000 --- a/llvm/include/llvm/MC/MCSymbolCOFF.h +++ /dev/null @@ -1,64 +0,0 @@ -//===- MCSymbolCOFF.h - ----------------------------------------*- 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_MCSYMBOLCOFF_H -#define LLVM_MC_MCSYMBOLCOFF_H - -#include "llvm/MC/MCSymbol.h" - -namespace llvm { -class MCSymbolCOFF : public MCSymbol { - - /// This corresponds to the e_type field of the COFF symbol. - mutable uint16_t Type; - - enum SymbolFlags : uint16_t { - SF_ClassMask = 0x00FF, - SF_ClassShift = 0, - - SF_WeakExternal = 0x0100, - SF_SafeSEH = 0x0200, - }; - -public: - MCSymbolCOFF(const StringMapEntry *Name, bool isTemporary) - : MCSymbol(SymbolKindCOFF, Name, isTemporary), Type(0) {} - - uint16_t getType() const { - return Type; - } - void setType(uint16_t Ty) const { - Type = Ty; - } - - uint16_t getClass() const { - return (getFlags() & SF_ClassMask) >> SF_ClassShift; - } - void setClass(uint16_t StorageClass) const { - modifyFlags(StorageClass << SF_ClassShift, SF_ClassMask); - } - - bool isWeakExternal() const { - return getFlags() & SF_WeakExternal; - } - void setIsWeakExternal() const { - modifyFlags(SF_WeakExternal, SF_WeakExternal); - } - - bool isSafeSEH() const { - return getFlags() & SF_SafeSEH; - } - void setIsSafeSEH() const { - modifyFlags(SF_SafeSEH, SF_SafeSEH); - } - - static bool classof(const MCSymbol *S) { return S->isCOFF(); } -}; -} - -#endif diff --git a/llvm/include/llvm/MC/MCSymbolMachO.h b/llvm/include/llvm/MC/MCSymbolMachO.h deleted file mode 100644 index 5b0321fe..00000000 --- a/llvm/include/llvm/MC/MCSymbolMachO.h +++ /dev/null @@ -1,123 +0,0 @@ -//===- MCSymbolMachO.h - ---------------------------------------*- 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_MCSYMBOLMACHO_H -#define LLVM_MC_MCSYMBOLMACHO_H - -#include "llvm/MC/MCSymbol.h" - -namespace llvm { -class MCSymbolMachO : public MCSymbol { - /// \brief We store the value for the 'desc' symbol field in the - /// lowest 16 bits of the implementation defined flags. - enum MachOSymbolFlags : uint16_t { // See . - SF_DescFlagsMask = 0xFFFF, - - // Reference type flags. - SF_ReferenceTypeMask = 0x0007, - SF_ReferenceTypeUndefinedNonLazy = 0x0000, - SF_ReferenceTypeUndefinedLazy = 0x0001, - SF_ReferenceTypeDefined = 0x0002, - SF_ReferenceTypePrivateDefined = 0x0003, - SF_ReferenceTypePrivateUndefinedNonLazy = 0x0004, - SF_ReferenceTypePrivateUndefinedLazy = 0x0005, - - // Other 'desc' flags. - SF_ThumbFunc = 0x0008, - SF_NoDeadStrip = 0x0020, - SF_WeakReference = 0x0040, - SF_WeakDefinition = 0x0080, - SF_SymbolResolver = 0x0100, - - // Common alignment - SF_CommonAlignmentMask = 0xF0FF, - SF_CommonAlignmentShift = 8 - }; - -public: - MCSymbolMachO(const StringMapEntry *Name, bool isTemporary) - : MCSymbol(SymbolKindMachO, Name, isTemporary) {} - - // Reference type methods. - - void clearReferenceType() const { - modifyFlags(0, SF_ReferenceTypeMask); - } - - void setReferenceTypeUndefinedLazy(bool Value) const { - modifyFlags(Value ? SF_ReferenceTypeUndefinedLazy : 0, - SF_ReferenceTypeUndefinedLazy); - } - - // Other 'desc' methods. - - void setThumbFunc() const { - modifyFlags(SF_ThumbFunc, SF_ThumbFunc); - } - - bool isNoDeadStrip() const { - return getFlags() & SF_NoDeadStrip; - } - void setNoDeadStrip() const { - modifyFlags(SF_NoDeadStrip, SF_NoDeadStrip); - } - - bool isWeakReference() const { - return getFlags() & SF_WeakReference; - } - void setWeakReference() const { - modifyFlags(SF_WeakReference, SF_WeakReference); - } - - bool isWeakDefinition() const { - return getFlags() & SF_WeakDefinition; - } - void setWeakDefinition() const { - modifyFlags(SF_WeakDefinition, SF_WeakDefinition); - } - - bool isSymbolResolver() const { - return getFlags() & SF_SymbolResolver; - } - void setSymbolResolver() const { - modifyFlags(SF_SymbolResolver, SF_SymbolResolver); - } - - void setDesc(unsigned Value) const { - assert(Value == (Value & SF_DescFlagsMask) && - "Invalid .desc value!"); - setFlags(Value & SF_DescFlagsMask); - } - - /// \brief Get the encoded value of the flags as they will be emitted in to - /// the MachO binary - uint16_t getEncodedFlags() const { - uint16_t Flags = getFlags(); - - // Common alignment is packed into the 'desc' bits. - if (isCommon()) { - if (unsigned Align = getCommonAlignment()) { - unsigned Log2Size = Log2_32(Align); - assert((1U << Log2Size) == Align && "Invalid 'common' alignment!"); - if (Log2Size > 15) - report_fatal_error("invalid 'common' alignment '" + - Twine(Align) + "' for '" + getName() + "'", - false); - Flags = (Flags & SF_CommonAlignmentMask) | - (Log2Size << SF_CommonAlignmentShift); - } - } - - return Flags; - } - - static bool classof(const MCSymbol *S) { return S->isMachO(); } -}; -} - -#endif diff --git a/llvm/include/llvm/MC/MCWinEH.h b/llvm/include/llvm/MC/MCWinEH.h index 723d7a39..68fa2b34 100644 --- a/llvm/include/llvm/MC/MCWinEH.h +++ b/llvm/include/llvm/MC/MCWinEH.h @@ -73,7 +73,7 @@ class UnwindEmitter { virtual ~UnwindEmitter() { } // - // This emits the unwind info sections (.pdata and .xdata in PE/COFF). + // This emits the unwind info sections (.pdata and .xdata in PE). // virtual void Emit(MCStreamer &Streamer) const = 0; virtual void EmitUnwindInfo(MCStreamer &Streamer, FrameInfo *FI) const = 0; diff --git a/llvm/include/llvm/MC/StringTableBuilder.h b/llvm/include/llvm/MC/StringTableBuilder.h index bf3cea7f..744d7539 100644 --- a/llvm/include/llvm/MC/StringTableBuilder.h +++ b/llvm/include/llvm/MC/StringTableBuilder.h @@ -19,7 +19,7 @@ namespace llvm { /// \brief Utility for building string tables with deduplicated suffixes. class StringTableBuilder { public: - enum Kind { ELF, WinCOFF, MachO, RAW }; + enum Kind { ELF, RAW }; private: SmallString<256> StringTable; diff --git a/llvm/include/llvm/Object/Binary.h b/llvm/include/llvm/Object/Binary.h index a0d11277..38b071c5 100644 --- a/llvm/include/llvm/Object/Binary.h +++ b/llvm/include/llvm/Object/Binary.h @@ -40,25 +40,17 @@ class Binary { enum { ID_Archive, - ID_MachOUniversalBinary, - ID_COFFImportFile, ID_IR, // LLVM IR ID_FunctionIndex, // Function summary index // Object and children. ID_StartObjects, - ID_COFF, ID_ELF32L, // ELF 32-bit, little endian ID_ELF32B, // ELF 32-bit, big endian ID_ELF64L, // ELF 64-bit, little endian ID_ELF64B, // ELF 64-bit, big endian - ID_MachO32L, // MachO 32-bit, little endian - ID_MachO32B, // MachO 32-bit, big endian - ID_MachO64L, // MachO 64-bit, little endian - ID_MachO64B, // MachO 64-bit, big endian - ID_EndObjects }; @@ -69,13 +61,6 @@ class Binary { return is64Bits ? ID_ELF64B : ID_ELF32B; } - static unsigned int getMachOType(bool isLE, bool is64Bits) { - if (isLE) - return is64Bits ? ID_MachO64L : ID_MachO32L; - else - return is64Bits ? ID_MachO64B : ID_MachO32B; - } - public: virtual ~Binary(); @@ -99,26 +84,10 @@ class Binary { return TypeID == ID_Archive; } - bool isMachOUniversalBinary() const { - return TypeID == ID_MachOUniversalBinary; - } - bool isELF() const { return TypeID >= ID_ELF32L && TypeID <= ID_ELF64B; } - bool isMachO() const { - return TypeID >= ID_MachO32L && TypeID <= ID_MachO64B; - } - - bool isCOFF() const { - return TypeID == ID_COFF; - } - - bool isCOFFImportFile() const { - return TypeID == ID_COFFImportFile; - } - bool isIR() const { return TypeID == ID_IR; } @@ -126,8 +95,7 @@ class Binary { bool isFunctionIndex() const { return TypeID == ID_FunctionIndex; } bool isLittleEndian() const { - return !(TypeID == ID_ELF32B || TypeID == ID_ELF64B || - TypeID == ID_MachO32B || TypeID == ID_MachO64B); + return !(TypeID == ID_ELF32B || TypeID == ID_ELF64B); } }; diff --git a/llvm/include/llvm/Object/COFF.h b/llvm/include/llvm/Object/COFF.h deleted file mode 100644 index 3e69c3e6..00000000 --- a/llvm/include/llvm/Object/COFF.h +++ /dev/null @@ -1,915 +0,0 @@ -//===- COFF.h - COFF object file implementation -----------------*- 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 COFFObjectFile class. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_OBJECT_COFF_H -#define LLVM_OBJECT_COFF_H - -#include "llvm/ADT/PointerUnion.h" -#include "llvm/Object/ObjectFile.h" -#include "llvm/Support/COFF.h" -#include "llvm/Support/Endian.h" -#include "llvm/Support/ErrorOr.h" - -namespace llvm { -template class ArrayRef; - -namespace object { -class ImportDirectoryEntryRef; -class DelayImportDirectoryEntryRef; -class ExportDirectoryEntryRef; -class ImportedSymbolRef; -class BaseRelocRef; -typedef content_iterator import_directory_iterator; -typedef content_iterator - delay_import_directory_iterator; -typedef content_iterator export_directory_iterator; -typedef content_iterator imported_symbol_iterator; -typedef content_iterator base_reloc_iterator; - -/// The DOS compatible header at the front of all PE/COFF executables. -struct dos_header { - char Magic[2]; - support::ulittle16_t UsedBytesInTheLastPage; - support::ulittle16_t FileSizeInPages; - support::ulittle16_t NumberOfRelocationItems; - support::ulittle16_t HeaderSizeInParagraphs; - support::ulittle16_t MinimumExtraParagraphs; - support::ulittle16_t MaximumExtraParagraphs; - support::ulittle16_t InitialRelativeSS; - support::ulittle16_t InitialSP; - support::ulittle16_t Checksum; - support::ulittle16_t InitialIP; - support::ulittle16_t InitialRelativeCS; - support::ulittle16_t AddressOfRelocationTable; - support::ulittle16_t OverlayNumber; - support::ulittle16_t Reserved[4]; - support::ulittle16_t OEMid; - support::ulittle16_t OEMinfo; - support::ulittle16_t Reserved2[10]; - support::ulittle32_t AddressOfNewExeHeader; -}; - -struct coff_file_header { - support::ulittle16_t Machine; - support::ulittle16_t NumberOfSections; - support::ulittle32_t TimeDateStamp; - support::ulittle32_t PointerToSymbolTable; - support::ulittle32_t NumberOfSymbols; - support::ulittle16_t SizeOfOptionalHeader; - support::ulittle16_t Characteristics; - - bool isImportLibrary() const { return NumberOfSections == 0xffff; } -}; - -struct coff_bigobj_file_header { - support::ulittle16_t Sig1; - support::ulittle16_t Sig2; - support::ulittle16_t Version; - support::ulittle16_t Machine; - support::ulittle32_t TimeDateStamp; - uint8_t UUID[16]; - support::ulittle32_t unused1; - support::ulittle32_t unused2; - support::ulittle32_t unused3; - support::ulittle32_t unused4; - support::ulittle32_t NumberOfSections; - support::ulittle32_t PointerToSymbolTable; - support::ulittle32_t NumberOfSymbols; -}; - -/// The 32-bit PE header that follows the COFF header. -struct pe32_header { - support::ulittle16_t Magic; - uint8_t MajorLinkerVersion; - uint8_t MinorLinkerVersion; - support::ulittle32_t SizeOfCode; - support::ulittle32_t SizeOfInitializedData; - support::ulittle32_t SizeOfUninitializedData; - support::ulittle32_t AddressOfEntryPoint; - support::ulittle32_t BaseOfCode; - support::ulittle32_t BaseOfData; - support::ulittle32_t ImageBase; - support::ulittle32_t SectionAlignment; - support::ulittle32_t FileAlignment; - support::ulittle16_t MajorOperatingSystemVersion; - support::ulittle16_t MinorOperatingSystemVersion; - support::ulittle16_t MajorImageVersion; - support::ulittle16_t MinorImageVersion; - support::ulittle16_t MajorSubsystemVersion; - support::ulittle16_t MinorSubsystemVersion; - support::ulittle32_t Win32VersionValue; - support::ulittle32_t SizeOfImage; - support::ulittle32_t SizeOfHeaders; - support::ulittle32_t CheckSum; - support::ulittle16_t Subsystem; - // FIXME: This should be DllCharacteristics. - support::ulittle16_t DLLCharacteristics; - support::ulittle32_t SizeOfStackReserve; - support::ulittle32_t SizeOfStackCommit; - support::ulittle32_t SizeOfHeapReserve; - support::ulittle32_t SizeOfHeapCommit; - support::ulittle32_t LoaderFlags; - // FIXME: This should be NumberOfRvaAndSizes. - support::ulittle32_t NumberOfRvaAndSize; -}; - -/// The 64-bit PE header that follows the COFF header. -struct pe32plus_header { - support::ulittle16_t Magic; - uint8_t MajorLinkerVersion; - uint8_t MinorLinkerVersion; - support::ulittle32_t SizeOfCode; - support::ulittle32_t SizeOfInitializedData; - support::ulittle32_t SizeOfUninitializedData; - support::ulittle32_t AddressOfEntryPoint; - support::ulittle32_t BaseOfCode; - support::ulittle64_t ImageBase; - support::ulittle32_t SectionAlignment; - support::ulittle32_t FileAlignment; - support::ulittle16_t MajorOperatingSystemVersion; - support::ulittle16_t MinorOperatingSystemVersion; - support::ulittle16_t MajorImageVersion; - support::ulittle16_t MinorImageVersion; - support::ulittle16_t MajorSubsystemVersion; - support::ulittle16_t MinorSubsystemVersion; - support::ulittle32_t Win32VersionValue; - support::ulittle32_t SizeOfImage; - support::ulittle32_t SizeOfHeaders; - support::ulittle32_t CheckSum; - support::ulittle16_t Subsystem; - support::ulittle16_t DLLCharacteristics; - support::ulittle64_t SizeOfStackReserve; - support::ulittle64_t SizeOfStackCommit; - support::ulittle64_t SizeOfHeapReserve; - support::ulittle64_t SizeOfHeapCommit; - support::ulittle32_t LoaderFlags; - support::ulittle32_t NumberOfRvaAndSize; -}; - -struct data_directory { - support::ulittle32_t RelativeVirtualAddress; - support::ulittle32_t Size; -}; - -struct import_directory_table_entry { - support::ulittle32_t ImportLookupTableRVA; - support::ulittle32_t TimeDateStamp; - support::ulittle32_t ForwarderChain; - support::ulittle32_t NameRVA; - support::ulittle32_t ImportAddressTableRVA; -}; - -template -struct import_lookup_table_entry { - IntTy Data; - - bool isOrdinal() const { return Data < 0; } - - uint16_t getOrdinal() const { - assert(isOrdinal() && "ILT entry is not an ordinal!"); - return Data & 0xFFFF; - } - - uint32_t getHintNameRVA() const { - assert(!isOrdinal() && "ILT entry is not a Hint/Name RVA!"); - return Data & 0xFFFFFFFF; - } -}; - -typedef import_lookup_table_entry - import_lookup_table_entry32; -typedef import_lookup_table_entry - import_lookup_table_entry64; - -struct delay_import_directory_table_entry { - // dumpbin reports this field as "Characteristics" instead of "Attributes". - support::ulittle32_t Attributes; - support::ulittle32_t Name; - support::ulittle32_t ModuleHandle; - support::ulittle32_t DelayImportAddressTable; - support::ulittle32_t DelayImportNameTable; - support::ulittle32_t BoundDelayImportTable; - support::ulittle32_t UnloadDelayImportTable; - support::ulittle32_t TimeStamp; -}; - -struct export_directory_table_entry { - support::ulittle32_t ExportFlags; - support::ulittle32_t TimeDateStamp; - support::ulittle16_t MajorVersion; - support::ulittle16_t MinorVersion; - support::ulittle32_t NameRVA; - support::ulittle32_t OrdinalBase; - support::ulittle32_t AddressTableEntries; - support::ulittle32_t NumberOfNamePointers; - support::ulittle32_t ExportAddressTableRVA; - support::ulittle32_t NamePointerRVA; - support::ulittle32_t OrdinalTableRVA; -}; - -union export_address_table_entry { - support::ulittle32_t ExportRVA; - support::ulittle32_t ForwarderRVA; -}; - -typedef support::ulittle32_t export_name_pointer_table_entry; -typedef support::ulittle16_t export_ordinal_table_entry; - -struct StringTableOffset { - support::ulittle32_t Zeroes; - support::ulittle32_t Offset; -}; - -template -struct coff_symbol { - union { - char ShortName[COFF::NameSize]; - StringTableOffset Offset; - } Name; - - support::ulittle32_t Value; - SectionNumberType SectionNumber; - - support::ulittle16_t Type; - - uint8_t StorageClass; - uint8_t NumberOfAuxSymbols; -}; - -typedef coff_symbol coff_symbol16; -typedef coff_symbol coff_symbol32; - -// Contains only common parts of coff_symbol16 and coff_symbol32. -struct coff_symbol_generic { - union { - char ShortName[COFF::NameSize]; - StringTableOffset Offset; - } Name; - support::ulittle32_t Value; -}; - -class COFFSymbolRef { -public: - COFFSymbolRef(const coff_symbol16 *CS) : CS16(CS), CS32(nullptr) {} - COFFSymbolRef(const coff_symbol32 *CS) : CS16(nullptr), CS32(CS) {} - COFFSymbolRef() : CS16(nullptr), CS32(nullptr) {} - - const void *getRawPtr() const { - return CS16 ? static_cast(CS16) : CS32; - } - - const coff_symbol_generic *getGeneric() const { - if (CS16) - return reinterpret_cast(CS16); - return reinterpret_cast(CS32); - } - - friend bool operator<(COFFSymbolRef A, COFFSymbolRef B) { - return A.getRawPtr() < B.getRawPtr(); - } - - bool isBigObj() const { - if (CS16) - return false; - if (CS32) - return true; - llvm_unreachable("COFFSymbolRef points to nothing!"); - } - - const char *getShortName() const { - return CS16 ? CS16->Name.ShortName : CS32->Name.ShortName; - } - - const StringTableOffset &getStringTableOffset() const { - assert(isSet() && "COFFSymbolRef points to nothing!"); - return CS16 ? CS16->Name.Offset : CS32->Name.Offset; - } - - uint32_t getValue() const { return CS16 ? CS16->Value : CS32->Value; } - - int32_t getSectionNumber() const { - assert(isSet() && "COFFSymbolRef points to nothing!"); - if (CS16) { - // Reserved sections are returned as negative numbers. - if (CS16->SectionNumber <= COFF::MaxNumberOfSections16) - return CS16->SectionNumber; - return static_cast(CS16->SectionNumber); - } - return static_cast(CS32->SectionNumber); - } - - uint16_t getType() const { - assert(isSet() && "COFFSymbolRef points to nothing!"); - return CS16 ? CS16->Type : CS32->Type; - } - - uint8_t getStorageClass() const { - assert(isSet() && "COFFSymbolRef points to nothing!"); - return CS16 ? CS16->StorageClass : CS32->StorageClass; - } - - uint8_t getNumberOfAuxSymbols() const { - assert(isSet() && "COFFSymbolRef points to nothing!"); - return CS16 ? CS16->NumberOfAuxSymbols : CS32->NumberOfAuxSymbols; - } - - uint8_t getBaseType() const { return getType() & 0x0F; } - - uint8_t getComplexType() const { - return (getType() & 0xF0) >> COFF::SCT_COMPLEX_TYPE_SHIFT; - } - - bool isAbsolute() const { - return getSectionNumber() == -1; - } - - bool isExternal() const { - return getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL; - } - - bool isCommon() const { - return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED && - getValue() != 0; - } - - bool isUndefined() const { - return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED && - getValue() == 0; - } - - bool isWeakExternal() const { - return getStorageClass() == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL; - } - - bool isFunctionDefinition() const { - return isExternal() && getBaseType() == COFF::IMAGE_SYM_TYPE_NULL && - getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION && - !COFF::isReservedSectionNumber(getSectionNumber()); - } - - bool isFunctionLineInfo() const { - return getStorageClass() == COFF::IMAGE_SYM_CLASS_FUNCTION; - } - - bool isAnyUndefined() const { - return isUndefined() || isWeakExternal(); - } - - bool isFileRecord() const { - return getStorageClass() == COFF::IMAGE_SYM_CLASS_FILE; - } - - bool isSection() const { - return getStorageClass() == COFF::IMAGE_SYM_CLASS_SECTION; - } - - bool isSectionDefinition() const { - // C++/CLI creates external ABS symbols for non-const appdomain globals. - // These are also followed by an auxiliary section definition. - bool isAppdomainGlobal = - getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL && - getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE; - bool isOrdinarySection = getStorageClass() == COFF::IMAGE_SYM_CLASS_STATIC; - if (!getNumberOfAuxSymbols()) - return false; - return isAppdomainGlobal || isOrdinarySection; - } - - bool isCLRToken() const { - return getStorageClass() == COFF::IMAGE_SYM_CLASS_CLR_TOKEN; - } - -private: - bool isSet() const { return CS16 || CS32; } - - const coff_symbol16 *CS16; - const coff_symbol32 *CS32; -}; - -struct coff_section { - char Name[COFF::NameSize]; - support::ulittle32_t VirtualSize; - support::ulittle32_t VirtualAddress; - support::ulittle32_t SizeOfRawData; - support::ulittle32_t PointerToRawData; - support::ulittle32_t PointerToRelocations; - support::ulittle32_t PointerToLinenumbers; - support::ulittle16_t NumberOfRelocations; - support::ulittle16_t NumberOfLinenumbers; - support::ulittle32_t Characteristics; - - // Returns true if the actual number of relocations is stored in - // VirtualAddress field of the first relocation table entry. - bool hasExtendedRelocations() const { - return (Characteristics & COFF::IMAGE_SCN_LNK_NRELOC_OVFL) && - NumberOfRelocations == UINT16_MAX; - } -}; - -struct coff_relocation { - support::ulittle32_t VirtualAddress; - support::ulittle32_t SymbolTableIndex; - support::ulittle16_t Type; -}; - -struct coff_aux_function_definition { - support::ulittle32_t TagIndex; - support::ulittle32_t TotalSize; - support::ulittle32_t PointerToLinenumber; - support::ulittle32_t PointerToNextFunction; -}; - -struct coff_aux_bf_and_ef_symbol { - char Unused1[4]; - support::ulittle16_t Linenumber; - char Unused2[6]; - support::ulittle32_t PointerToNextFunction; -}; - -struct coff_aux_weak_external { - support::ulittle32_t TagIndex; - support::ulittle32_t Characteristics; -}; - -struct coff_aux_section_definition { - support::ulittle32_t Length; - support::ulittle16_t NumberOfRelocations; - support::ulittle16_t NumberOfLinenumbers; - support::ulittle32_t CheckSum; - support::ulittle16_t NumberLowPart; - uint8_t Selection; - uint8_t Unused; - support::ulittle16_t NumberHighPart; - int32_t getNumber(bool IsBigObj) const { - uint32_t Number = static_cast(NumberLowPart); - if (IsBigObj) - Number |= static_cast(NumberHighPart) << 16; - return static_cast(Number); - } -}; - -struct coff_aux_clr_token { - uint8_t AuxType; - uint8_t Reserved; - support::ulittle32_t SymbolTableIndex; -}; - -struct coff_import_header { - support::ulittle16_t Sig1; - support::ulittle16_t Sig2; - support::ulittle16_t Version; - support::ulittle16_t Machine; - support::ulittle32_t TimeDateStamp; - support::ulittle32_t SizeOfData; - support::ulittle16_t OrdinalHint; - support::ulittle16_t TypeInfo; - int getType() const { return TypeInfo & 0x3; } - int getNameType() const { return (TypeInfo >> 2) & 0x7; } -}; - -struct coff_import_directory_table_entry { - support::ulittle32_t ImportLookupTableRVA; - support::ulittle32_t TimeDateStamp; - support::ulittle32_t ForwarderChain; - support::ulittle32_t NameRVA; - support::ulittle32_t ImportAddressTableRVA; -}; - -struct coff_load_configuration32 { - support::ulittle32_t Characteristics; - support::ulittle32_t TimeDateStamp; - support::ulittle16_t MajorVersion; - support::ulittle16_t MinorVersion; - support::ulittle32_t GlobalFlagsClear; - support::ulittle32_t GlobalFlagsSet; - support::ulittle32_t CriticalSectionDefaultTimeout; - support::ulittle32_t DeCommitFreeBlockThreshold; - support::ulittle32_t DeCommitTotalFreeThreshold; - support::ulittle32_t LockPrefixTable; - support::ulittle32_t MaximumAllocationSize; - support::ulittle32_t VirtualMemoryThreshold; - support::ulittle32_t ProcessAffinityMask; - support::ulittle32_t ProcessHeapFlags; - support::ulittle16_t CSDVersion; - support::ulittle16_t Reserved; - support::ulittle32_t EditList; - support::ulittle32_t SecurityCookie; - support::ulittle32_t SEHandlerTable; - support::ulittle32_t SEHandlerCount; -}; - -struct coff_load_configuration64 { - support::ulittle32_t Characteristics; - support::ulittle32_t TimeDateStamp; - support::ulittle16_t MajorVersion; - support::ulittle16_t MinorVersion; - support::ulittle32_t GlobalFlagsClear; - support::ulittle32_t GlobalFlagsSet; - support::ulittle32_t CriticalSectionDefaultTimeout; - support::ulittle32_t DeCommitFreeBlockThreshold; - support::ulittle32_t DeCommitTotalFreeThreshold; - support::ulittle32_t LockPrefixTable; - support::ulittle32_t MaximumAllocationSize; - support::ulittle32_t VirtualMemoryThreshold; - support::ulittle32_t ProcessAffinityMask; - support::ulittle32_t ProcessHeapFlags; - support::ulittle16_t CSDVersion; - support::ulittle16_t Reserved; - support::ulittle32_t EditList; - support::ulittle64_t SecurityCookie; - support::ulittle64_t SEHandlerTable; - support::ulittle64_t SEHandlerCount; -}; - -struct coff_runtime_function_x64 { - support::ulittle32_t BeginAddress; - support::ulittle32_t EndAddress; - support::ulittle32_t UnwindInformation; -}; - -struct coff_base_reloc_block_header { - support::ulittle32_t PageRVA; - support::ulittle32_t BlockSize; -}; - -struct coff_base_reloc_block_entry { - support::ulittle16_t Data; - int getType() const { return Data >> 12; } - int getOffset() const { return Data & ((1 << 12) - 1); } -}; - -class COFFObjectFile : public ObjectFile { -private: - friend class ImportDirectoryEntryRef; - friend class ExportDirectoryEntryRef; - const coff_file_header *COFFHeader; - const coff_bigobj_file_header *COFFBigObjHeader; - const pe32_header *PE32Header; - const pe32plus_header *PE32PlusHeader; - const data_directory *DataDirectory; - const coff_section *SectionTable; - const coff_symbol16 *SymbolTable16; - const coff_symbol32 *SymbolTable32; - const char *StringTable; - uint32_t StringTableSize; - const import_directory_table_entry *ImportDirectory; - uint32_t NumberOfImportDirectory; - const delay_import_directory_table_entry *DelayImportDirectory; - uint32_t NumberOfDelayImportDirectory; - const export_directory_table_entry *ExportDirectory; - const coff_base_reloc_block_header *BaseRelocHeader; - const coff_base_reloc_block_header *BaseRelocEnd; - - std::error_code getString(uint32_t offset, StringRef &Res) const; - - template - const coff_symbol_type *toSymb(DataRefImpl Symb) const; - const coff_section *toSec(DataRefImpl Sec) const; - const coff_relocation *toRel(DataRefImpl Rel) const; - - std::error_code initSymbolTablePtr(); - std::error_code initImportTablePtr(); - std::error_code initDelayImportTablePtr(); - std::error_code initExportTablePtr(); - std::error_code initBaseRelocPtr(); - -public: - uintptr_t getSymbolTable() const { - if (SymbolTable16) - return reinterpret_cast(SymbolTable16); - if (SymbolTable32) - return reinterpret_cast(SymbolTable32); - return uintptr_t(0); - } - uint16_t getMachine() const { - if (COFFHeader) - return COFFHeader->Machine; - if (COFFBigObjHeader) - return COFFBigObjHeader->Machine; - llvm_unreachable("no COFF header!"); - } - uint16_t getSizeOfOptionalHeader() const { - if (COFFHeader) - return COFFHeader->isImportLibrary() ? 0 - : COFFHeader->SizeOfOptionalHeader; - // bigobj doesn't have this field. - if (COFFBigObjHeader) - return 0; - llvm_unreachable("no COFF header!"); - } - uint16_t getCharacteristics() const { - if (COFFHeader) - return COFFHeader->isImportLibrary() ? 0 : COFFHeader->Characteristics; - // bigobj doesn't have characteristics to speak of, - // editbin will silently lie to you if you attempt to set any. - if (COFFBigObjHeader) - return 0; - llvm_unreachable("no COFF header!"); - } - uint32_t getTimeDateStamp() const { - if (COFFHeader) - return COFFHeader->TimeDateStamp; - if (COFFBigObjHeader) - return COFFBigObjHeader->TimeDateStamp; - llvm_unreachable("no COFF header!"); - } - uint32_t getNumberOfSections() const { - if (COFFHeader) - return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSections; - if (COFFBigObjHeader) - return COFFBigObjHeader->NumberOfSections; - llvm_unreachable("no COFF header!"); - } - uint32_t getPointerToSymbolTable() const { - if (COFFHeader) - return COFFHeader->isImportLibrary() ? 0 - : COFFHeader->PointerToSymbolTable; - if (COFFBigObjHeader) - return COFFBigObjHeader->PointerToSymbolTable; - llvm_unreachable("no COFF header!"); - } - uint32_t getNumberOfSymbols() const { - if (COFFHeader) - return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSymbols; - if (COFFBigObjHeader) - return COFFBigObjHeader->NumberOfSymbols; - llvm_unreachable("no COFF header!"); - } -protected: - void moveSymbolNext(DataRefImpl &Symb) const override; - ErrorOr getSymbolName(DataRefImpl Symb) const override; - ErrorOr getSymbolAddress(DataRefImpl Symb) const override; - uint64_t getSymbolValueImpl(DataRefImpl Symb) const override; - uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override; - uint32_t getSymbolFlags(DataRefImpl Symb) const override; - SymbolRef::Type getSymbolType(DataRefImpl Symb) const override; - ErrorOr getSymbolSection(DataRefImpl Symb) const override; - void moveSectionNext(DataRefImpl &Sec) const override; - std::error_code getSectionName(DataRefImpl Sec, - StringRef &Res) const override; - uint64_t getSectionAddress(DataRefImpl Sec) const override; - uint64_t getSectionSize(DataRefImpl Sec) const override; - std::error_code getSectionContents(DataRefImpl Sec, - StringRef &Res) const override; - uint64_t getSectionAlignment(DataRefImpl Sec) const override; - bool isSectionText(DataRefImpl Sec) const override; - bool isSectionData(DataRefImpl Sec) const override; - bool isSectionBSS(DataRefImpl Sec) const override; - bool isSectionVirtual(DataRefImpl Sec) const override; - relocation_iterator section_rel_begin(DataRefImpl Sec) const override; - relocation_iterator section_rel_end(DataRefImpl Sec) const override; - - void moveRelocationNext(DataRefImpl &Rel) const override; - uint64_t getRelocationOffset(DataRefImpl Rel) const override; - symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override; - uint64_t getRelocationType(DataRefImpl Rel) const override; - void getRelocationTypeName(DataRefImpl Rel, - SmallVectorImpl &Result) const override; - -public: - COFFObjectFile(MemoryBufferRef Object, std::error_code &EC); - basic_symbol_iterator symbol_begin_impl() const override; - basic_symbol_iterator symbol_end_impl() const override; - section_iterator section_begin() const override; - section_iterator section_end() const override; - - const coff_section *getCOFFSection(const SectionRef &Section) const; - COFFSymbolRef getCOFFSymbol(const DataRefImpl &Ref) const; - COFFSymbolRef getCOFFSymbol(const SymbolRef &Symbol) const; - const coff_relocation *getCOFFRelocation(const RelocationRef &Reloc) const; - unsigned getSectionID(SectionRef Sec) const; - unsigned getSymbolSectionID(SymbolRef Sym) const; - - uint8_t getBytesInAddress() const override; - StringRef getFileFormatName() const override; - unsigned getArch() const override; - - import_directory_iterator import_directory_begin() const; - import_directory_iterator import_directory_end() const; - delay_import_directory_iterator delay_import_directory_begin() const; - delay_import_directory_iterator delay_import_directory_end() const; - export_directory_iterator export_directory_begin() const; - export_directory_iterator export_directory_end() const; - base_reloc_iterator base_reloc_begin() const; - base_reloc_iterator base_reloc_end() const; - - iterator_range import_directories() const; - iterator_range - delay_import_directories() const; - iterator_range export_directories() const; - iterator_range base_relocs() const; - - const dos_header *getDOSHeader() const { - if (!PE32Header && !PE32PlusHeader) - return nullptr; - return reinterpret_cast(base()); - } - std::error_code getPE32Header(const pe32_header *&Res) const; - std::error_code getPE32PlusHeader(const pe32plus_header *&Res) const; - std::error_code getDataDirectory(uint32_t index, - const data_directory *&Res) const; - std::error_code getSection(int32_t index, const coff_section *&Res) const; - template - std::error_code getSymbol(uint32_t Index, - const coff_symbol_type *&Res) const { - if (Index >= getNumberOfSymbols()) - return object_error::parse_failed; - - Res = reinterpret_cast(getSymbolTable()) + Index; - return std::error_code(); - } - ErrorOr getSymbol(uint32_t index) const { - if (SymbolTable16) { - const coff_symbol16 *Symb = nullptr; - if (std::error_code EC = getSymbol(index, Symb)) - return EC; - return COFFSymbolRef(Symb); - } - if (SymbolTable32) { - const coff_symbol32 *Symb = nullptr; - if (std::error_code EC = getSymbol(index, Symb)) - return EC; - return COFFSymbolRef(Symb); - } - return object_error::parse_failed; - } - template - std::error_code getAuxSymbol(uint32_t index, const T *&Res) const { - ErrorOr s = getSymbol(index); - if (std::error_code EC = s.getError()) - return EC; - Res = reinterpret_cast(s->getRawPtr()); - return std::error_code(); - } - std::error_code getSymbolName(COFFSymbolRef Symbol, StringRef &Res) const; - std::error_code getSymbolName(const coff_symbol_generic *Symbol, - StringRef &Res) const; - - ArrayRef getSymbolAuxData(COFFSymbolRef Symbol) const; - - size_t getSymbolTableEntrySize() const { - if (COFFHeader) - return sizeof(coff_symbol16); - if (COFFBigObjHeader) - return sizeof(coff_symbol32); - llvm_unreachable("null symbol table pointer!"); - } - - iterator_range - getRelocations(const coff_section *Sec) const; - - std::error_code getSectionName(const coff_section *Sec, StringRef &Res) const; - uint64_t getSectionSize(const coff_section *Sec) const; - std::error_code getSectionContents(const coff_section *Sec, - ArrayRef &Res) const; - - uint64_t getImageBase() const; - std::error_code getVaPtr(uint64_t VA, uintptr_t &Res) const; - std::error_code getRvaPtr(uint32_t Rva, uintptr_t &Res) const; - std::error_code getHintName(uint32_t Rva, uint16_t &Hint, - StringRef &Name) const; - - bool isRelocatableObject() const override; - bool is64() const { return PE32PlusHeader; } - - static inline bool classof(const Binary *v) { return v->isCOFF(); } -}; - -// The iterator for the import directory table. -class ImportDirectoryEntryRef { -public: - ImportDirectoryEntryRef() : OwningObject(nullptr) {} - ImportDirectoryEntryRef(const import_directory_table_entry *Table, uint32_t I, - const COFFObjectFile *Owner) - : ImportTable(Table), Index(I), OwningObject(Owner) {} - - bool operator==(const ImportDirectoryEntryRef &Other) const; - void moveNext(); - - imported_symbol_iterator imported_symbol_begin() const; - imported_symbol_iterator imported_symbol_end() const; - iterator_range imported_symbols() const; - - std::error_code getName(StringRef &Result) const; - std::error_code getImportLookupTableRVA(uint32_t &Result) const; - std::error_code getImportAddressTableRVA(uint32_t &Result) const; - - std::error_code - getImportTableEntry(const import_directory_table_entry *&Result) const; - - std::error_code - getImportLookupEntry(const import_lookup_table_entry32 *&Result) const; - -private: - const import_directory_table_entry *ImportTable; - uint32_t Index; - const COFFObjectFile *OwningObject; -}; - -class DelayImportDirectoryEntryRef { -public: - DelayImportDirectoryEntryRef() : OwningObject(nullptr) {} - DelayImportDirectoryEntryRef(const delay_import_directory_table_entry *T, - uint32_t I, const COFFObjectFile *Owner) - : Table(T), Index(I), OwningObject(Owner) {} - - bool operator==(const DelayImportDirectoryEntryRef &Other) const; - void moveNext(); - - imported_symbol_iterator imported_symbol_begin() const; - imported_symbol_iterator imported_symbol_end() const; - iterator_range imported_symbols() const; - - std::error_code getName(StringRef &Result) const; - std::error_code getDelayImportTable( - const delay_import_directory_table_entry *&Result) const; - std::error_code getImportAddress(int AddrIndex, uint64_t &Result) const; - -private: - const delay_import_directory_table_entry *Table; - uint32_t Index; - const COFFObjectFile *OwningObject; -}; - -// The iterator for the export directory table entry. -class ExportDirectoryEntryRef { -public: - ExportDirectoryEntryRef() : OwningObject(nullptr) {} - ExportDirectoryEntryRef(const export_directory_table_entry *Table, uint32_t I, - const COFFObjectFile *Owner) - : ExportTable(Table), Index(I), OwningObject(Owner) {} - - bool operator==(const ExportDirectoryEntryRef &Other) const; - void moveNext(); - - std::error_code getDllName(StringRef &Result) const; - std::error_code getOrdinalBase(uint32_t &Result) const; - std::error_code getOrdinal(uint32_t &Result) const; - std::error_code getExportRVA(uint32_t &Result) const; - std::error_code getSymbolName(StringRef &Result) const; - - std::error_code isForwarder(bool &Result) const; - std::error_code getForwardTo(StringRef &Result) const; - -private: - const export_directory_table_entry *ExportTable; - uint32_t Index; - const COFFObjectFile *OwningObject; -}; - -class ImportedSymbolRef { -public: - ImportedSymbolRef() : OwningObject(nullptr) {} - ImportedSymbolRef(const import_lookup_table_entry32 *Entry, uint32_t I, - const COFFObjectFile *Owner) - : Entry32(Entry), Entry64(nullptr), Index(I), OwningObject(Owner) {} - ImportedSymbolRef(const import_lookup_table_entry64 *Entry, uint32_t I, - const COFFObjectFile *Owner) - : Entry32(nullptr), Entry64(Entry), Index(I), OwningObject(Owner) {} - - bool operator==(const ImportedSymbolRef &Other) const; - void moveNext(); - - std::error_code getSymbolName(StringRef &Result) const; - std::error_code getOrdinal(uint16_t &Result) const; - -private: - const import_lookup_table_entry32 *Entry32; - const import_lookup_table_entry64 *Entry64; - uint32_t Index; - const COFFObjectFile *OwningObject; -}; - -class BaseRelocRef { -public: - BaseRelocRef() : OwningObject(nullptr) {} - BaseRelocRef(const coff_base_reloc_block_header *Header, - const COFFObjectFile *Owner) - : Header(Header), Index(0), OwningObject(Owner) {} - - bool operator==(const BaseRelocRef &Other) const; - void moveNext(); - - std::error_code getType(uint8_t &Type) const; - std::error_code getRVA(uint32_t &Result) const; - -private: - const coff_base_reloc_block_header *Header; - uint32_t Index; - const COFFObjectFile *OwningObject; -}; - -} // end namespace object -} // end namespace llvm - -#endif diff --git a/llvm/include/llvm/Object/Error.h b/llvm/include/llvm/Object/Error.h index 0f79a6ed..fd35a845 100644 --- a/llvm/include/llvm/Object/Error.h +++ b/llvm/include/llvm/Object/Error.h @@ -31,9 +31,6 @@ enum class object_error { invalid_section_index, bitcode_section_not_found, elf_invalid_dynamic_table_size, - macho_small_load_command, - macho_load_segment_too_many_sections, - macho_load_segment_too_small, }; inline std::error_code make_error_code(object_error e) { diff --git a/llvm/include/llvm/Object/MachO.h b/llvm/include/llvm/Object/MachO.h deleted file mode 100644 index e02ce3b2..00000000 --- a/llvm/include/llvm/Object/MachO.h +++ /dev/null @@ -1,523 +0,0 @@ -//===- MachO.h - MachO object file implementation ---------------*- 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 MachOObjectFile class, which implement the ObjectFile -// interface for MachO files. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_OBJECT_MACHO_H -#define LLVM_OBJECT_MACHO_H - -#include "llvm/ADT/ArrayRef.h" -#include "llvm/ADT/SmallVector.h" -#include "llvm/ADT/Triple.h" -#include "llvm/Object/ObjectFile.h" -#include "llvm/Support/MachO.h" - -namespace llvm { -namespace object { - -/// DiceRef - This is a value type class that represents a single -/// data in code entry in the table in a Mach-O object file. -class DiceRef { - DataRefImpl DicePimpl; - const ObjectFile *OwningObject; - -public: - DiceRef() : OwningObject(nullptr) { } - - DiceRef(DataRefImpl DiceP, const ObjectFile *Owner); - - bool operator==(const DiceRef &Other) const; - bool operator<(const DiceRef &Other) const; - - void moveNext(); - - std::error_code getOffset(uint32_t &Result) const; - std::error_code getLength(uint16_t &Result) const; - std::error_code getKind(uint16_t &Result) const; - - DataRefImpl getRawDataRefImpl() const; - const ObjectFile *getObjectFile() const; -}; -typedef content_iterator dice_iterator; - -/// ExportEntry encapsulates the current-state-of-the-walk used when doing a -/// non-recursive walk of the trie data structure. This allows you to iterate -/// across all exported symbols using: -/// for (const llvm::object::ExportEntry &AnExport : Obj->exports()) { -/// } -class ExportEntry { -public: - ExportEntry(ArrayRef Trie); - - StringRef name() const; - uint64_t flags() const; - uint64_t address() const; - uint64_t other() const; - StringRef otherName() const; - uint32_t nodeOffset() const; - - bool operator==(const ExportEntry &) const; - - void moveNext(); - -private: - friend class MachOObjectFile; - void moveToFirst(); - void moveToEnd(); - uint64_t readULEB128(const uint8_t *&p); - void pushDownUntilBottom(); - void pushNode(uint64_t Offset); - - // Represents a node in the mach-o exports trie. - struct NodeState { - NodeState(const uint8_t *Ptr); - const uint8_t *Start; - const uint8_t *Current; - uint64_t Flags; - uint64_t Address; - uint64_t Other; - const char *ImportName; - unsigned ChildCount; - unsigned NextChildIndex; - unsigned ParentStringLength; - bool IsExportNode; - }; - - ArrayRef Trie; - SmallString<256> CumulativeString; - SmallVector Stack; - bool Malformed; - bool Done; -}; -typedef content_iterator export_iterator; - -/// MachORebaseEntry encapsulates the current state in the decompression of -/// rebasing opcodes. This allows you to iterate through the compressed table of -/// rebasing using: -/// for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) { -/// } -class MachORebaseEntry { -public: - MachORebaseEntry(ArrayRef opcodes, bool is64Bit); - - uint32_t segmentIndex() const; - uint64_t segmentOffset() const; - StringRef typeName() const; - - bool operator==(const MachORebaseEntry &) const; - - void moveNext(); - -private: - friend class MachOObjectFile; - void moveToFirst(); - void moveToEnd(); - uint64_t readULEB128(); - - ArrayRef Opcodes; - const uint8_t *Ptr; - uint64_t SegmentOffset; - uint32_t SegmentIndex; - uint64_t RemainingLoopCount; - uint64_t AdvanceAmount; - uint8_t RebaseType; - uint8_t PointerSize; - bool Malformed; - bool Done; -}; -typedef content_iterator rebase_iterator; - -/// MachOBindEntry encapsulates the current state in the decompression of -/// binding opcodes. This allows you to iterate through the compressed table of -/// bindings using: -/// for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) { -/// } -class MachOBindEntry { -public: - enum class Kind { Regular, Lazy, Weak }; - - MachOBindEntry(ArrayRef Opcodes, bool is64Bit, MachOBindEntry::Kind); - - uint32_t segmentIndex() const; - uint64_t segmentOffset() const; - StringRef typeName() const; - StringRef symbolName() const; - uint32_t flags() const; - int64_t addend() const; - int ordinal() const; - - bool operator==(const MachOBindEntry &) const; - - void moveNext(); - -private: - friend class MachOObjectFile; - void moveToFirst(); - void moveToEnd(); - uint64_t readULEB128(); - int64_t readSLEB128(); - - ArrayRef Opcodes; - const uint8_t *Ptr; - uint64_t SegmentOffset; - uint32_t SegmentIndex; - StringRef SymbolName; - int Ordinal; - uint32_t Flags; - int64_t Addend; - uint64_t RemainingLoopCount; - uint64_t AdvanceAmount; - uint8_t BindType; - uint8_t PointerSize; - Kind TableKind; - bool Malformed; - bool Done; -}; -typedef content_iterator bind_iterator; - -class MachOObjectFile : public ObjectFile { -public: - struct LoadCommandInfo { - const char *Ptr; // Where in memory the load command is. - MachO::load_command C; // The command itself. - }; - typedef SmallVector LoadCommandList; - typedef LoadCommandList::const_iterator load_command_iterator; - - MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits, - std::error_code &EC); - - void moveSymbolNext(DataRefImpl &Symb) const override; - - uint64_t getNValue(DataRefImpl Sym) const; - ErrorOr getSymbolName(DataRefImpl Symb) const override; - - // MachO specific. - std::error_code getIndirectName(DataRefImpl Symb, StringRef &Res) const; - unsigned getSectionType(SectionRef Sec) const; - - ErrorOr getSymbolAddress(DataRefImpl Symb) const override; - uint32_t getSymbolAlignment(DataRefImpl Symb) const override; - uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override; - SymbolRef::Type getSymbolType(DataRefImpl Symb) const override; - uint32_t getSymbolFlags(DataRefImpl Symb) const override; - ErrorOr getSymbolSection(DataRefImpl Symb) const override; - unsigned getSymbolSectionID(SymbolRef Symb) const; - unsigned getSectionID(SectionRef Sec) const; - - void moveSectionNext(DataRefImpl &Sec) const override; - std::error_code getSectionName(DataRefImpl Sec, - StringRef &Res) const override; - uint64_t getSectionAddress(DataRefImpl Sec) const override; - uint64_t getSectionSize(DataRefImpl Sec) const override; - std::error_code getSectionContents(DataRefImpl Sec, - StringRef &Res) const override; - uint64_t getSectionAlignment(DataRefImpl Sec) const override; - bool isSectionText(DataRefImpl Sec) const override; - bool isSectionData(DataRefImpl Sec) const override; - bool isSectionBSS(DataRefImpl Sec) const override; - bool isSectionVirtual(DataRefImpl Sec) const override; - relocation_iterator section_rel_begin(DataRefImpl Sec) const override; - relocation_iterator section_rel_end(DataRefImpl Sec) const override; - - void moveRelocationNext(DataRefImpl &Rel) const override; - uint64_t getRelocationOffset(DataRefImpl Rel) const override; - symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override; - section_iterator getRelocationSection(DataRefImpl Rel) const; - uint64_t getRelocationType(DataRefImpl Rel) const override; - void getRelocationTypeName(DataRefImpl Rel, - SmallVectorImpl &Result) const override; - uint8_t getRelocationLength(DataRefImpl Rel) const; - - // MachO specific. - std::error_code getLibraryShortNameByIndex(unsigned Index, StringRef &) const; - - section_iterator getRelocationRelocatedSection(relocation_iterator Rel) const; - - // TODO: Would be useful to have an iterator based version - // of the load command interface too. - - basic_symbol_iterator symbol_begin_impl() const override; - basic_symbol_iterator symbol_end_impl() const override; - - // MachO specific. - basic_symbol_iterator getSymbolByIndex(unsigned Index) const; - - section_iterator section_begin() const override; - section_iterator section_end() const override; - - uint8_t getBytesInAddress() const override; - - StringRef getFileFormatName() const override; - unsigned getArch() const override; - Triple getArch(const char **McpuDefault, Triple *ThumbTriple) const; - - relocation_iterator section_rel_begin(unsigned Index) const; - relocation_iterator section_rel_end(unsigned Index) const; - - dice_iterator begin_dices() const; - dice_iterator end_dices() const; - - load_command_iterator begin_load_commands() const; - load_command_iterator end_load_commands() const; - iterator_range load_commands() const; - - /// For use iterating over all exported symbols. - iterator_range exports() const; - - /// For use examining a trie not in a MachOObjectFile. - static iterator_range exports(ArrayRef Trie); - - /// For use iterating over all rebase table entries. - iterator_range rebaseTable() const; - - /// For use examining rebase opcodes not in a MachOObjectFile. - static iterator_range rebaseTable(ArrayRef Opcodes, - bool is64); - - /// For use iterating over all bind table entries. - iterator_range bindTable() const; - - /// For use iterating over all lazy bind table entries. - iterator_range lazyBindTable() const; - - /// For use iterating over all lazy bind table entries. - iterator_range weakBindTable() const; - - /// For use examining bind opcodes not in a MachOObjectFile. - static iterator_range bindTable(ArrayRef Opcodes, - bool is64, - MachOBindEntry::Kind); - - - // In a MachO file, sections have a segment name. This is used in the .o - // files. They have a single segment, but this field specifies which segment - // a section should be put in in the final object. - StringRef getSectionFinalSegmentName(DataRefImpl Sec) const; - - // Names are stored as 16 bytes. These returns the raw 16 bytes without - // interpreting them as a C string. - ArrayRef getSectionRawName(DataRefImpl Sec) const; - ArrayRef getSectionRawFinalSegmentName(DataRefImpl Sec) const; - - // MachO specific Info about relocations. - bool isRelocationScattered(const MachO::any_relocation_info &RE) const; - unsigned getPlainRelocationSymbolNum( - const MachO::any_relocation_info &RE) const; - bool getPlainRelocationExternal(const MachO::any_relocation_info &RE) const; - bool getScatteredRelocationScattered( - const MachO::any_relocation_info &RE) const; - uint32_t getScatteredRelocationValue( - const MachO::any_relocation_info &RE) const; - uint32_t getScatteredRelocationType( - const MachO::any_relocation_info &RE) const; - unsigned getAnyRelocationAddress(const MachO::any_relocation_info &RE) const; - unsigned getAnyRelocationPCRel(const MachO::any_relocation_info &RE) const; - unsigned getAnyRelocationLength(const MachO::any_relocation_info &RE) const; - unsigned getAnyRelocationType(const MachO::any_relocation_info &RE) const; - SectionRef getAnyRelocationSection(const MachO::any_relocation_info &RE) const; - - // MachO specific structures. - MachO::section getSection(DataRefImpl DRI) const; - MachO::section_64 getSection64(DataRefImpl DRI) const; - MachO::section getSection(const LoadCommandInfo &L, unsigned Index) const; - MachO::section_64 getSection64(const LoadCommandInfo &L,unsigned Index) const; - MachO::nlist getSymbolTableEntry(DataRefImpl DRI) const; - MachO::nlist_64 getSymbol64TableEntry(DataRefImpl DRI) const; - - MachO::linkedit_data_command - getLinkeditDataLoadCommand(const LoadCommandInfo &L) const; - MachO::segment_command - getSegmentLoadCommand(const LoadCommandInfo &L) const; - MachO::segment_command_64 - getSegment64LoadCommand(const LoadCommandInfo &L) const; - MachO::linker_option_command - getLinkerOptionLoadCommand(const LoadCommandInfo &L) const; - MachO::version_min_command - getVersionMinLoadCommand(const LoadCommandInfo &L) const; - MachO::dylib_command - getDylibIDLoadCommand(const LoadCommandInfo &L) const; - MachO::dyld_info_command - getDyldInfoLoadCommand(const LoadCommandInfo &L) const; - MachO::dylinker_command - getDylinkerCommand(const LoadCommandInfo &L) const; - MachO::uuid_command - getUuidCommand(const LoadCommandInfo &L) const; - MachO::rpath_command - getRpathCommand(const LoadCommandInfo &L) const; - MachO::source_version_command - getSourceVersionCommand(const LoadCommandInfo &L) const; - MachO::entry_point_command - getEntryPointCommand(const LoadCommandInfo &L) const; - MachO::encryption_info_command - getEncryptionInfoCommand(const LoadCommandInfo &L) const; - MachO::encryption_info_command_64 - getEncryptionInfoCommand64(const LoadCommandInfo &L) const; - MachO::sub_framework_command - getSubFrameworkCommand(const LoadCommandInfo &L) const; - MachO::sub_umbrella_command - getSubUmbrellaCommand(const LoadCommandInfo &L) const; - MachO::sub_library_command - getSubLibraryCommand(const LoadCommandInfo &L) const; - MachO::sub_client_command - getSubClientCommand(const LoadCommandInfo &L) const; - MachO::routines_command - getRoutinesCommand(const LoadCommandInfo &L) const; - MachO::routines_command_64 - getRoutinesCommand64(const LoadCommandInfo &L) const; - MachO::thread_command - getThreadCommand(const LoadCommandInfo &L) const; - - MachO::any_relocation_info getRelocation(DataRefImpl Rel) const; - MachO::data_in_code_entry getDice(DataRefImpl Rel) const; - const MachO::mach_header &getHeader() const; - const MachO::mach_header_64 &getHeader64() const; - uint32_t - getIndirectSymbolTableEntry(const MachO::dysymtab_command &DLC, - unsigned Index) const; - MachO::data_in_code_entry getDataInCodeTableEntry(uint32_t DataOffset, - unsigned Index) const; - MachO::symtab_command getSymtabLoadCommand() const; - MachO::dysymtab_command getDysymtabLoadCommand() const; - MachO::linkedit_data_command getDataInCodeLoadCommand() const; - MachO::linkedit_data_command getLinkOptHintsLoadCommand() const; - ArrayRef getDyldInfoRebaseOpcodes() const; - ArrayRef getDyldInfoBindOpcodes() const; - ArrayRef getDyldInfoWeakBindOpcodes() const; - ArrayRef getDyldInfoLazyBindOpcodes() const; - ArrayRef getDyldInfoExportsTrie() const; - ArrayRef getUuid() const; - - StringRef getStringTableData() const; - bool is64Bit() const; - void ReadULEB128s(uint64_t Index, SmallVectorImpl &Out) const; - - static StringRef guessLibraryShortName(StringRef Name, bool &isFramework, - StringRef &Suffix); - - static Triple::ArchType getArch(uint32_t CPUType); - static Triple getArch(uint32_t CPUType, uint32_t CPUSubType, - const char **McpuDefault = nullptr); - static Triple getThumbArch(uint32_t CPUType, uint32_t CPUSubType, - const char **McpuDefault = nullptr); - static Triple getArch(uint32_t CPUType, uint32_t CPUSubType, - const char **McpuDefault, Triple *ThumbTriple); - static bool isValidArch(StringRef ArchFlag); - static Triple getHostArch(); - - bool isRelocatableObject() const override; - - bool hasPageZeroSegment() const { return HasPageZeroSegment; } - - static bool classof(const Binary *v) { - return v->isMachO(); - } - - static uint32_t - getVersionMinMajor(MachO::version_min_command &C, bool SDK) { - uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version; - return (VersionOrSDK >> 16) & 0xffff; - } - - static uint32_t - getVersionMinMinor(MachO::version_min_command &C, bool SDK) { - uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version; - return (VersionOrSDK >> 8) & 0xff; - } - - static uint32_t - getVersionMinUpdate(MachO::version_min_command &C, bool SDK) { - uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version; - return VersionOrSDK & 0xff; - } - -private: - uint64_t getSymbolValueImpl(DataRefImpl Symb) const override; - - union { - MachO::mach_header_64 Header64; - MachO::mach_header Header; - }; - typedef SmallVector SectionList; - SectionList Sections; - typedef SmallVector LibraryList; - LibraryList Libraries; - LoadCommandList LoadCommands; - typedef SmallVector LibraryShortName; - mutable LibraryShortName LibrariesShortNames; - const char *SymtabLoadCmd; - const char *DysymtabLoadCmd; - const char *DataInCodeLoadCmd; - const char *LinkOptHintsLoadCmd; - const char *DyldInfoLoadCmd; - const char *UuidLoadCmd; - bool HasPageZeroSegment; -}; - -/// DiceRef -inline DiceRef::DiceRef(DataRefImpl DiceP, const ObjectFile *Owner) - : DicePimpl(DiceP) , OwningObject(Owner) {} - -inline bool DiceRef::operator==(const DiceRef &Other) const { - return DicePimpl == Other.DicePimpl; -} - -inline bool DiceRef::operator<(const DiceRef &Other) const { - return DicePimpl < Other.DicePimpl; -} - -inline void DiceRef::moveNext() { - const MachO::data_in_code_entry *P = - reinterpret_cast(DicePimpl.p); - DicePimpl.p = reinterpret_cast(P + 1); -} - -// Since a Mach-O data in code reference, a DiceRef, can only be created when -// the OwningObject ObjectFile is a MachOObjectFile a static_cast<> is used for -// the methods that get the values of the fields of the reference. - -inline std::error_code DiceRef::getOffset(uint32_t &Result) const { - const MachOObjectFile *MachOOF = - static_cast(OwningObject); - MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl); - Result = Dice.offset; - return std::error_code(); -} - -inline std::error_code DiceRef::getLength(uint16_t &Result) const { - const MachOObjectFile *MachOOF = - static_cast(OwningObject); - MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl); - Result = Dice.length; - return std::error_code(); -} - -inline std::error_code DiceRef::getKind(uint16_t &Result) const { - const MachOObjectFile *MachOOF = - static_cast(OwningObject); - MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl); - Result = Dice.kind; - return std::error_code(); -} - -inline DataRefImpl DiceRef::getRawDataRefImpl() const { - return DicePimpl; -} - -inline const ObjectFile *DiceRef::getObjectFile() const { - return OwningObject; -} - -} -} - -#endif diff --git a/llvm/include/llvm/Object/ObjectFile.h b/llvm/include/llvm/Object/ObjectFile.h index 22c3cf90..24620617 100644 --- a/llvm/include/llvm/Object/ObjectFile.h +++ b/llvm/include/llvm/Object/ObjectFile.h @@ -27,8 +27,6 @@ namespace llvm { namespace object { class ObjectFile; -class COFFObjectFile; -class MachOObjectFile; class SymbolRef; class symbol_iterator; @@ -287,14 +285,8 @@ class ObjectFile : public SymbolicFile { return v->isObject(); } - static ErrorOr> - createCOFFObjectFile(MemoryBufferRef Object); - static ErrorOr> createELFObjectFile(MemoryBufferRef Object); - - static ErrorOr> - createMachOObjectFile(MemoryBufferRef Object); }; // Inline function definitions. diff --git a/llvm/include/llvm/Support/COFF.h b/llvm/include/llvm/Support/COFF.h deleted file mode 100644 index 32bedbb2..00000000 --- a/llvm/include/llvm/Support/COFF.h +++ /dev/null @@ -1,670 +0,0 @@ -//===-- llvm/Support/COFF.h -------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file contains an definitions used in Windows COFF Files. -// -// Structures and enums defined within this file where created using -// information from Microsoft's publicly available PE/COFF format document: -// -// Microsoft Portable Executable and Common Object File Format Specification -// Revision 8.1 - February 15, 2008 -// -// As of 5/2/2010, hosted by Microsoft at: -// http://www.microsoft.com/whdc/system/platform/firmware/pecoff.mspx -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_SUPPORT_COFF_H -#define LLVM_SUPPORT_COFF_H - -#include "llvm/Support/DataTypes.h" -#include -#include - -namespace llvm { -namespace COFF { - - // The maximum number of sections that a COFF object can have (inclusive). - const int32_t MaxNumberOfSections16 = 65279; - - // The PE signature bytes that follows the DOS stub header. - static const char PEMagic[] = { 'P', 'E', '\0', '\0' }; - - static const char BigObjMagic[] = { - '\xc7', '\xa1', '\xba', '\xd1', '\xee', '\xba', '\xa9', '\x4b', - '\xaf', '\x20', '\xfa', '\xf6', '\x6a', '\xa4', '\xdc', '\xb8', - }; - - // Sizes in bytes of various things in the COFF format. - enum { - Header16Size = 20, - Header32Size = 56, - NameSize = 8, - Symbol16Size = 18, - Symbol32Size = 20, - SectionSize = 40, - RelocationSize = 10 - }; - - struct header { - uint16_t Machine; - int32_t NumberOfSections; - uint32_t TimeDateStamp; - uint32_t PointerToSymbolTable; - uint32_t NumberOfSymbols; - uint16_t SizeOfOptionalHeader; - uint16_t Characteristics; - }; - - struct BigObjHeader { - enum : uint16_t { MinBigObjectVersion = 2 }; - - uint16_t Sig1; ///< Must be IMAGE_FILE_MACHINE_UNKNOWN (0). - uint16_t Sig2; ///< Must be 0xFFFF. - uint16_t Version; - uint16_t Machine; - uint32_t TimeDateStamp; - uint8_t UUID[16]; - uint32_t unused1; - uint32_t unused2; - uint32_t unused3; - uint32_t unused4; - uint32_t NumberOfSections; - uint32_t PointerToSymbolTable; - uint32_t NumberOfSymbols; - }; - - enum MachineTypes { - MT_Invalid = 0xffff, - - IMAGE_FILE_MACHINE_UNKNOWN = 0x0, - IMAGE_FILE_MACHINE_AM33 = 0x13, - IMAGE_FILE_MACHINE_AMD64 = 0x8664, - IMAGE_FILE_MACHINE_ARM = 0x1C0, - IMAGE_FILE_MACHINE_ARMNT = 0x1C4, - IMAGE_FILE_MACHINE_ARM64 = 0xAA64, - IMAGE_FILE_MACHINE_EBC = 0xEBC, - IMAGE_FILE_MACHINE_I386 = 0x14C, - IMAGE_FILE_MACHINE_IA64 = 0x200, - IMAGE_FILE_MACHINE_M32R = 0x9041, - IMAGE_FILE_MACHINE_MIPS16 = 0x266, - IMAGE_FILE_MACHINE_MIPSFPU = 0x366, - IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466, - IMAGE_FILE_MACHINE_POWERPC = 0x1F0, - IMAGE_FILE_MACHINE_POWERPCFP = 0x1F1, - IMAGE_FILE_MACHINE_R4000 = 0x166, - IMAGE_FILE_MACHINE_SH3 = 0x1A2, - IMAGE_FILE_MACHINE_SH3DSP = 0x1A3, - IMAGE_FILE_MACHINE_SH4 = 0x1A6, - IMAGE_FILE_MACHINE_SH5 = 0x1A8, - IMAGE_FILE_MACHINE_THUMB = 0x1C2, - IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169 - }; - - enum Characteristics { - C_Invalid = 0, - - /// The file does not contain base relocations and must be loaded at its - /// preferred base. If this cannot be done, the loader will error. - IMAGE_FILE_RELOCS_STRIPPED = 0x0001, - /// The file is valid and can be run. - IMAGE_FILE_EXECUTABLE_IMAGE = 0x0002, - /// COFF line numbers have been stripped. This is deprecated and should be - /// 0. - IMAGE_FILE_LINE_NUMS_STRIPPED = 0x0004, - /// COFF symbol table entries for local symbols have been removed. This is - /// deprecated and should be 0. - IMAGE_FILE_LOCAL_SYMS_STRIPPED = 0x0008, - /// Aggressively trim working set. This is deprecated and must be 0. - IMAGE_FILE_AGGRESSIVE_WS_TRIM = 0x0010, - /// Image can handle > 2GiB addresses. - IMAGE_FILE_LARGE_ADDRESS_AWARE = 0x0020, - /// Little endian: the LSB precedes the MSB in memory. This is deprecated - /// and should be 0. - IMAGE_FILE_BYTES_REVERSED_LO = 0x0080, - /// Machine is based on a 32bit word architecture. - IMAGE_FILE_32BIT_MACHINE = 0x0100, - /// Debugging info has been removed. - IMAGE_FILE_DEBUG_STRIPPED = 0x0200, - /// If the image is on removable media, fully load it and copy it to swap. - IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP = 0x0400, - /// If the image is on network media, fully load it and copy it to swap. - IMAGE_FILE_NET_RUN_FROM_SWAP = 0x0800, - /// The image file is a system file, not a user program. - IMAGE_FILE_SYSTEM = 0x1000, - /// The image file is a DLL. - IMAGE_FILE_DLL = 0x2000, - /// This file should only be run on a uniprocessor machine. - IMAGE_FILE_UP_SYSTEM_ONLY = 0x4000, - /// Big endian: the MSB precedes the LSB in memory. This is deprecated - /// and should be 0. - IMAGE_FILE_BYTES_REVERSED_HI = 0x8000 - }; - - struct symbol { - char Name[NameSize]; - uint32_t Value; - int32_t SectionNumber; - uint16_t Type; - uint8_t StorageClass; - uint8_t NumberOfAuxSymbols; - }; - - enum SymbolSectionNumber : int32_t { - IMAGE_SYM_DEBUG = -2, - IMAGE_SYM_ABSOLUTE = -1, - IMAGE_SYM_UNDEFINED = 0 - }; - - /// Storage class tells where and what the symbol represents - enum SymbolStorageClass { - SSC_Invalid = 0xff, - - IMAGE_SYM_CLASS_END_OF_FUNCTION = -1, ///< Physical end of function - IMAGE_SYM_CLASS_NULL = 0, ///< No symbol - IMAGE_SYM_CLASS_AUTOMATIC = 1, ///< Stack variable - IMAGE_SYM_CLASS_EXTERNAL = 2, ///< External symbol - IMAGE_SYM_CLASS_STATIC = 3, ///< Static - IMAGE_SYM_CLASS_REGISTER = 4, ///< Register variable - IMAGE_SYM_CLASS_EXTERNAL_DEF = 5, ///< External definition - IMAGE_SYM_CLASS_LABEL = 6, ///< Label - IMAGE_SYM_CLASS_UNDEFINED_LABEL = 7, ///< Undefined label - IMAGE_SYM_CLASS_MEMBER_OF_STRUCT = 8, ///< Member of structure - IMAGE_SYM_CLASS_ARGUMENT = 9, ///< Function argument - IMAGE_SYM_CLASS_STRUCT_TAG = 10, ///< Structure tag - IMAGE_SYM_CLASS_MEMBER_OF_UNION = 11, ///< Member of union - IMAGE_SYM_CLASS_UNION_TAG = 12, ///< Union tag - IMAGE_SYM_CLASS_TYPE_DEFINITION = 13, ///< Type definition - IMAGE_SYM_CLASS_UNDEFINED_STATIC = 14, ///< Undefined static - IMAGE_SYM_CLASS_ENUM_TAG = 15, ///< Enumeration tag - IMAGE_SYM_CLASS_MEMBER_OF_ENUM = 16, ///< Member of enumeration - IMAGE_SYM_CLASS_REGISTER_PARAM = 17, ///< Register parameter - IMAGE_SYM_CLASS_BIT_FIELD = 18, ///< Bit field - /// ".bb" or ".eb" - beginning or end of block - IMAGE_SYM_CLASS_BLOCK = 100, - /// ".bf" or ".ef" - beginning or end of function - IMAGE_SYM_CLASS_FUNCTION = 101, - IMAGE_SYM_CLASS_END_OF_STRUCT = 102, ///< End of structure - IMAGE_SYM_CLASS_FILE = 103, ///< File name - /// Line number, reformatted as symbol - IMAGE_SYM_CLASS_SECTION = 104, - IMAGE_SYM_CLASS_WEAK_EXTERNAL = 105, ///< Duplicate tag - /// External symbol in dmert public lib - IMAGE_SYM_CLASS_CLR_TOKEN = 107 - }; - - enum SymbolBaseType { - IMAGE_SYM_TYPE_NULL = 0, ///< No type information or unknown base type. - IMAGE_SYM_TYPE_VOID = 1, ///< Used with void pointers and functions. - IMAGE_SYM_TYPE_CHAR = 2, ///< A character (signed byte). - IMAGE_SYM_TYPE_SHORT = 3, ///< A 2-byte signed integer. - IMAGE_SYM_TYPE_INT = 4, ///< A natural integer type on the target. - IMAGE_SYM_TYPE_LONG = 5, ///< A 4-byte signed integer. - IMAGE_SYM_TYPE_FLOAT = 6, ///< A 4-byte floating-point number. - IMAGE_SYM_TYPE_DOUBLE = 7, ///< An 8-byte floating-point number. - IMAGE_SYM_TYPE_STRUCT = 8, ///< A structure. - IMAGE_SYM_TYPE_UNION = 9, ///< An union. - IMAGE_SYM_TYPE_ENUM = 10, ///< An enumerated type. - IMAGE_SYM_TYPE_MOE = 11, ///< A member of enumeration (a specific value). - IMAGE_SYM_TYPE_BYTE = 12, ///< A byte; unsigned 1-byte integer. - IMAGE_SYM_TYPE_WORD = 13, ///< A word; unsigned 2-byte integer. - IMAGE_SYM_TYPE_UINT = 14, ///< An unsigned integer of natural size. - IMAGE_SYM_TYPE_DWORD = 15 ///< An unsigned 4-byte integer. - }; - - enum SymbolComplexType { - IMAGE_SYM_DTYPE_NULL = 0, ///< No complex type; simple scalar variable. - IMAGE_SYM_DTYPE_POINTER = 1, ///< A pointer to base type. - IMAGE_SYM_DTYPE_FUNCTION = 2, ///< A function that returns a base type. - IMAGE_SYM_DTYPE_ARRAY = 3, ///< An array of base type. - - /// Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT)) - SCT_COMPLEX_TYPE_SHIFT = 4 - }; - - enum AuxSymbolType { - IMAGE_AUX_SYMBOL_TYPE_TOKEN_DEF = 1 - }; - - struct section { - char Name[NameSize]; - uint32_t VirtualSize; - uint32_t VirtualAddress; - uint32_t SizeOfRawData; - uint32_t PointerToRawData; - uint32_t PointerToRelocations; - uint32_t PointerToLineNumbers; - uint16_t NumberOfRelocations; - uint16_t NumberOfLineNumbers; - uint32_t Characteristics; - }; - - enum SectionCharacteristics : uint32_t { - SC_Invalid = 0xffffffff, - - IMAGE_SCN_TYPE_NOLOAD = 0x00000002, - IMAGE_SCN_TYPE_NO_PAD = 0x00000008, - IMAGE_SCN_CNT_CODE = 0x00000020, - IMAGE_SCN_CNT_INITIALIZED_DATA = 0x00000040, - IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080, - IMAGE_SCN_LNK_OTHER = 0x00000100, - IMAGE_SCN_LNK_INFO = 0x00000200, - IMAGE_SCN_LNK_REMOVE = 0x00000800, - IMAGE_SCN_LNK_COMDAT = 0x00001000, - IMAGE_SCN_GPREL = 0x00008000, - IMAGE_SCN_MEM_PURGEABLE = 0x00020000, - IMAGE_SCN_MEM_16BIT = 0x00020000, - IMAGE_SCN_MEM_LOCKED = 0x00040000, - IMAGE_SCN_MEM_PRELOAD = 0x00080000, - IMAGE_SCN_ALIGN_1BYTES = 0x00100000, - IMAGE_SCN_ALIGN_2BYTES = 0x00200000, - IMAGE_SCN_ALIGN_4BYTES = 0x00300000, - IMAGE_SCN_ALIGN_8BYTES = 0x00400000, - IMAGE_SCN_ALIGN_16BYTES = 0x00500000, - IMAGE_SCN_ALIGN_32BYTES = 0x00600000, - IMAGE_SCN_ALIGN_64BYTES = 0x00700000, - IMAGE_SCN_ALIGN_128BYTES = 0x00800000, - IMAGE_SCN_ALIGN_256BYTES = 0x00900000, - IMAGE_SCN_ALIGN_512BYTES = 0x00A00000, - IMAGE_SCN_ALIGN_1024BYTES = 0x00B00000, - IMAGE_SCN_ALIGN_2048BYTES = 0x00C00000, - IMAGE_SCN_ALIGN_4096BYTES = 0x00D00000, - IMAGE_SCN_ALIGN_8192BYTES = 0x00E00000, - IMAGE_SCN_LNK_NRELOC_OVFL = 0x01000000, - IMAGE_SCN_MEM_DISCARDABLE = 0x02000000, - IMAGE_SCN_MEM_NOT_CACHED = 0x04000000, - IMAGE_SCN_MEM_NOT_PAGED = 0x08000000, - IMAGE_SCN_MEM_SHARED = 0x10000000, - IMAGE_SCN_MEM_EXECUTE = 0x20000000, - IMAGE_SCN_MEM_READ = 0x40000000, - IMAGE_SCN_MEM_WRITE = 0x80000000 - }; - - struct relocation { - uint32_t VirtualAddress; - uint32_t SymbolTableIndex; - uint16_t Type; - }; - - enum RelocationTypeI386 { - IMAGE_REL_I386_ABSOLUTE = 0x0000, - IMAGE_REL_I386_DIR16 = 0x0001, - IMAGE_REL_I386_REL16 = 0x0002, - IMAGE_REL_I386_DIR32 = 0x0006, - IMAGE_REL_I386_DIR32NB = 0x0007, - IMAGE_REL_I386_SEG12 = 0x0009, - IMAGE_REL_I386_SECTION = 0x000A, - IMAGE_REL_I386_SECREL = 0x000B, - IMAGE_REL_I386_TOKEN = 0x000C, - IMAGE_REL_I386_SECREL7 = 0x000D, - IMAGE_REL_I386_REL32 = 0x0014 - }; - - enum RelocationTypeAMD64 { - IMAGE_REL_AMD64_ABSOLUTE = 0x0000, - IMAGE_REL_AMD64_ADDR64 = 0x0001, - IMAGE_REL_AMD64_ADDR32 = 0x0002, - IMAGE_REL_AMD64_ADDR32NB = 0x0003, - IMAGE_REL_AMD64_REL32 = 0x0004, - IMAGE_REL_AMD64_REL32_1 = 0x0005, - IMAGE_REL_AMD64_REL32_2 = 0x0006, - IMAGE_REL_AMD64_REL32_3 = 0x0007, - IMAGE_REL_AMD64_REL32_4 = 0x0008, - IMAGE_REL_AMD64_REL32_5 = 0x0009, - IMAGE_REL_AMD64_SECTION = 0x000A, - IMAGE_REL_AMD64_SECREL = 0x000B, - IMAGE_REL_AMD64_SECREL7 = 0x000C, - IMAGE_REL_AMD64_TOKEN = 0x000D, - IMAGE_REL_AMD64_SREL32 = 0x000E, - IMAGE_REL_AMD64_PAIR = 0x000F, - IMAGE_REL_AMD64_SSPAN32 = 0x0010 - }; - - enum RelocationTypesARM { - IMAGE_REL_ARM_ABSOLUTE = 0x0000, - IMAGE_REL_ARM_ADDR32 = 0x0001, - IMAGE_REL_ARM_ADDR32NB = 0x0002, - IMAGE_REL_ARM_BRANCH24 = 0x0003, - IMAGE_REL_ARM_BRANCH11 = 0x0004, - IMAGE_REL_ARM_TOKEN = 0x0005, - IMAGE_REL_ARM_BLX24 = 0x0008, - IMAGE_REL_ARM_BLX11 = 0x0009, - IMAGE_REL_ARM_SECTION = 0x000E, - IMAGE_REL_ARM_SECREL = 0x000F, - IMAGE_REL_ARM_MOV32A = 0x0010, - IMAGE_REL_ARM_MOV32T = 0x0011, - IMAGE_REL_ARM_BRANCH20T = 0x0012, - IMAGE_REL_ARM_BRANCH24T = 0x0014, - IMAGE_REL_ARM_BLX23T = 0x0015 - }; - - enum COMDATType { - IMAGE_COMDAT_SELECT_NODUPLICATES = 1, - IMAGE_COMDAT_SELECT_ANY, - IMAGE_COMDAT_SELECT_SAME_SIZE, - IMAGE_COMDAT_SELECT_EXACT_MATCH, - IMAGE_COMDAT_SELECT_ASSOCIATIVE, - IMAGE_COMDAT_SELECT_LARGEST, - IMAGE_COMDAT_SELECT_NEWEST - }; - - // Auxiliary Symbol Formats - struct AuxiliaryFunctionDefinition { - uint32_t TagIndex; - uint32_t TotalSize; - uint32_t PointerToLinenumber; - uint32_t PointerToNextFunction; - char unused[2]; - }; - - struct AuxiliarybfAndefSymbol { - uint8_t unused1[4]; - uint16_t Linenumber; - uint8_t unused2[6]; - uint32_t PointerToNextFunction; - uint8_t unused3[2]; - }; - - struct AuxiliaryWeakExternal { - uint32_t TagIndex; - uint32_t Characteristics; - uint8_t unused[10]; - }; - - /// These are not documented in the spec, but are located in WinNT.h. - enum WeakExternalCharacteristics { - IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY = 1, - IMAGE_WEAK_EXTERN_SEARCH_LIBRARY = 2, - IMAGE_WEAK_EXTERN_SEARCH_ALIAS = 3 - }; - - struct AuxiliarySectionDefinition { - uint32_t Length; - uint16_t NumberOfRelocations; - uint16_t NumberOfLinenumbers; - uint32_t CheckSum; - uint32_t Number; - uint8_t Selection; - char unused; - }; - - struct AuxiliaryCLRToken { - uint8_t AuxType; - uint8_t unused1; - uint32_t SymbolTableIndex; - char unused2[12]; - }; - - union Auxiliary { - AuxiliaryFunctionDefinition FunctionDefinition; - AuxiliarybfAndefSymbol bfAndefSymbol; - AuxiliaryWeakExternal WeakExternal; - AuxiliarySectionDefinition SectionDefinition; - }; - - /// @brief The Import Directory Table. - /// - /// There is a single array of these and one entry per imported DLL. - struct ImportDirectoryTableEntry { - uint32_t ImportLookupTableRVA; - uint32_t TimeDateStamp; - uint32_t ForwarderChain; - uint32_t NameRVA; - uint32_t ImportAddressTableRVA; - }; - - /// @brief The PE32 Import Lookup Table. - /// - /// There is an array of these for each imported DLL. It represents either - /// the ordinal to import from the target DLL, or a name to lookup and import - /// from the target DLL. - /// - /// This also happens to be the same format used by the Import Address Table - /// when it is initially written out to the image. - struct ImportLookupTableEntry32 { - uint32_t data; - - /// @brief Is this entry specified by ordinal, or name? - bool isOrdinal() const { return data & 0x80000000; } - - /// @brief Get the ordinal value of this entry. isOrdinal must be true. - uint16_t getOrdinal() const { - assert(isOrdinal() && "ILT entry is not an ordinal!"); - return data & 0xFFFF; - } - - /// @brief Set the ordinal value and set isOrdinal to true. - void setOrdinal(uint16_t o) { - data = o; - data |= 0x80000000; - } - - /// @brief Get the Hint/Name entry RVA. isOrdinal must be false. - uint32_t getHintNameRVA() const { - assert(!isOrdinal() && "ILT entry is not a Hint/Name RVA!"); - return data; - } - - /// @brief Set the Hint/Name entry RVA and set isOrdinal to false. - void setHintNameRVA(uint32_t rva) { data = rva; } - }; - - /// @brief The DOS compatible header at the front of all PEs. - struct DOSHeader { - uint16_t Magic; - uint16_t UsedBytesInTheLastPage; - uint16_t FileSizeInPages; - uint16_t NumberOfRelocationItems; - uint16_t HeaderSizeInParagraphs; - uint16_t MinimumExtraParagraphs; - uint16_t MaximumExtraParagraphs; - uint16_t InitialRelativeSS; - uint16_t InitialSP; - uint16_t Checksum; - uint16_t InitialIP; - uint16_t InitialRelativeCS; - uint16_t AddressOfRelocationTable; - uint16_t OverlayNumber; - uint16_t Reserved[4]; - uint16_t OEMid; - uint16_t OEMinfo; - uint16_t Reserved2[10]; - uint32_t AddressOfNewExeHeader; - }; - - struct PE32Header { - enum { - PE32 = 0x10b, - PE32_PLUS = 0x20b - }; - - uint16_t Magic; - uint8_t MajorLinkerVersion; - uint8_t MinorLinkerVersion; - uint32_t SizeOfCode; - uint32_t SizeOfInitializedData; - uint32_t SizeOfUninitializedData; - uint32_t AddressOfEntryPoint; // RVA - uint32_t BaseOfCode; // RVA - uint32_t BaseOfData; // RVA - uint32_t ImageBase; - uint32_t SectionAlignment; - uint32_t FileAlignment; - uint16_t MajorOperatingSystemVersion; - uint16_t MinorOperatingSystemVersion; - uint16_t MajorImageVersion; - uint16_t MinorImageVersion; - uint16_t MajorSubsystemVersion; - uint16_t MinorSubsystemVersion; - uint32_t Win32VersionValue; - uint32_t SizeOfImage; - uint32_t SizeOfHeaders; - uint32_t CheckSum; - uint16_t Subsystem; - // FIXME: This should be DllCharacteristics to match the COFF spec. - uint16_t DLLCharacteristics; - uint32_t SizeOfStackReserve; - uint32_t SizeOfStackCommit; - uint32_t SizeOfHeapReserve; - uint32_t SizeOfHeapCommit; - uint32_t LoaderFlags; - // FIXME: This should be NumberOfRvaAndSizes to match the COFF spec. - uint32_t NumberOfRvaAndSize; - }; - - struct DataDirectory { - uint32_t RelativeVirtualAddress; - uint32_t Size; - }; - - enum DataDirectoryIndex { - EXPORT_TABLE = 0, - IMPORT_TABLE, - RESOURCE_TABLE, - EXCEPTION_TABLE, - CERTIFICATE_TABLE, - BASE_RELOCATION_TABLE, - DEBUG, - ARCHITECTURE, - GLOBAL_PTR, - TLS_TABLE, - LOAD_CONFIG_TABLE, - BOUND_IMPORT, - IAT, - DELAY_IMPORT_DESCRIPTOR, - CLR_RUNTIME_HEADER, - - NUM_DATA_DIRECTORIES - }; - - enum WindowsSubsystem { - IMAGE_SUBSYSTEM_UNKNOWN = 0, ///< An unknown subsystem. - IMAGE_SUBSYSTEM_NATIVE = 1, ///< Device drivers and native Windows processes - IMAGE_SUBSYSTEM_WINDOWS_GUI = 2, ///< The Windows GUI subsystem. - IMAGE_SUBSYSTEM_WINDOWS_CUI = 3, ///< The Windows character subsystem. - IMAGE_SUBSYSTEM_OS2_CUI = 5, ///< The OS/2 character subsytem. - IMAGE_SUBSYSTEM_POSIX_CUI = 7, ///< The POSIX character subsystem. - IMAGE_SUBSYSTEM_NATIVE_WINDOWS = 8, ///< Native Windows 9x driver. - IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9, ///< Windows CE. - IMAGE_SUBSYSTEM_EFI_APPLICATION = 10, ///< An EFI application. - IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER = 11, ///< An EFI driver with boot - /// services. - IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER = 12, ///< An EFI driver with run-time - /// services. - IMAGE_SUBSYSTEM_EFI_ROM = 13, ///< An EFI ROM image. - IMAGE_SUBSYSTEM_XBOX = 14, ///< XBOX. - IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION = 16 ///< A BCD application. - }; - - enum DLLCharacteristics { - /// ASLR with 64 bit address space. - IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA = 0x0020, - /// DLL can be relocated at load time. - IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE = 0x0040, - /// Code integrity checks are enforced. - IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY = 0x0080, - ///< Image is NX compatible. - IMAGE_DLL_CHARACTERISTICS_NX_COMPAT = 0x0100, - /// Isolation aware, but do not isolate the image. - IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION = 0x0200, - /// Does not use structured exception handling (SEH). No SEH handler may be - /// called in this image. - IMAGE_DLL_CHARACTERISTICS_NO_SEH = 0x0400, - /// Do not bind the image. - IMAGE_DLL_CHARACTERISTICS_NO_BIND = 0x0800, - ///< Image should execute in an AppContainer. - IMAGE_DLL_CHARACTERISTICS_APPCONTAINER = 0x1000, - ///< A WDM driver. - IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER = 0x2000, - ///< Image supports Control Flow Guard. - IMAGE_DLL_CHARACTERISTICS_GUARD_CF = 0x4000, - /// Terminal Server aware. - IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE = 0x8000 - }; - - enum DebugType { - IMAGE_DEBUG_TYPE_UNKNOWN = 0, - IMAGE_DEBUG_TYPE_COFF = 1, - IMAGE_DEBUG_TYPE_CODEVIEW = 2, - IMAGE_DEBUG_TYPE_FPO = 3, - IMAGE_DEBUG_TYPE_MISC = 4, - IMAGE_DEBUG_TYPE_EXCEPTION = 5, - IMAGE_DEBUG_TYPE_FIXUP = 6, - IMAGE_DEBUG_TYPE_OMAP_TO_SRC = 7, - IMAGE_DEBUG_TYPE_OMAP_FROM_SRC = 8, - IMAGE_DEBUG_TYPE_BORLAND = 9, - IMAGE_DEBUG_TYPE_CLSID = 11 - }; - - enum BaseRelocationType { - IMAGE_REL_BASED_ABSOLUTE = 0, - IMAGE_REL_BASED_HIGH = 1, - IMAGE_REL_BASED_LOW = 2, - IMAGE_REL_BASED_HIGHLOW = 3, - IMAGE_REL_BASED_HIGHADJ = 4, - IMAGE_REL_BASED_MIPS_JMPADDR = 5, - IMAGE_REL_BASED_ARM_MOV32A = 5, - IMAGE_REL_BASED_ARM_MOV32T = 7, - IMAGE_REL_BASED_MIPS_JMPADDR16 = 9, - IMAGE_REL_BASED_DIR64 = 10 - }; - - enum ImportType { - IMPORT_CODE = 0, - IMPORT_DATA = 1, - IMPORT_CONST = 2 - }; - - enum ImportNameType { - /// Import is by ordinal. This indicates that the value in the Ordinal/Hint - /// field of the import header is the import's ordinal. If this constant is - /// not specified, then the Ordinal/Hint field should always be interpreted - /// as the import's hint. - IMPORT_ORDINAL = 0, - /// The import name is identical to the public symbol name - IMPORT_NAME = 1, - /// The import name is the public symbol name, but skipping the leading ?, - /// @, or optionally _. - IMPORT_NAME_NOPREFIX = 2, - /// The import name is the public symbol name, but skipping the leading ?, - /// @, or optionally _, and truncating at the first @. - IMPORT_NAME_UNDECORATE = 3 - }; - - struct ImportHeader { - uint16_t Sig1; ///< Must be IMAGE_FILE_MACHINE_UNKNOWN (0). - uint16_t Sig2; ///< Must be 0xFFFF. - uint16_t Version; - uint16_t Machine; - uint32_t TimeDateStamp; - uint32_t SizeOfData; - uint16_t OrdinalHint; - uint16_t TypeInfo; - - ImportType getType() const { - return static_cast(TypeInfo & 0x3); - } - - ImportNameType getNameType() const { - return static_cast((TypeInfo & 0x1C) >> 3); - } - }; - - enum CodeViewIdentifiers { - DEBUG_SECTION_MAGIC = 0x4, - }; - - inline bool isReservedSectionNumber(int32_t SectionNumber) { - return SectionNumber <= 0; - } - -} // End namespace COFF. -} // End namespace llvm. - -#endif diff --git a/llvm/include/llvm/Support/FileSystem.h b/llvm/include/llvm/Support/FileSystem.h index 62aba3e0..c278d206 100644 --- a/llvm/include/llvm/Support/FileSystem.h +++ b/llvm/include/llvm/Support/FileSystem.h @@ -242,9 +242,6 @@ struct file_magic { macho_dsym_companion, ///< Mach-O dSYM companion file macho_kext_bundle, ///< Mach-O kext bundle file macho_universal_binary, ///< Mach-O universal binary - coff_object, ///< COFF object file - coff_import_library, ///< COFF import library - pecoff_executable, ///< PECOFF executable file windows_resource ///< Windows compiled resource file (.rc) }; diff --git a/llvm/include/llvm/Support/MachO.h b/llvm/include/llvm/Support/MachO.h deleted file mode 100644 index 54b8745d..00000000 --- a/llvm/include/llvm/Support/MachO.h +++ /dev/null @@ -1,1675 +0,0 @@ -//===-- llvm/Support/MachO.h - The MachO file format ------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines manifest constants for the MachO object file format. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_SUPPORT_MACHO_H -#define LLVM_SUPPORT_MACHO_H - -#include "llvm/Support/Compiler.h" -#include "llvm/Support/DataTypes.h" -#include "llvm/Support/Host.h" - -namespace llvm { - namespace MachO { - // Enums from - enum : uint32_t { - // Constants for the "magic" field in llvm::MachO::mach_header and - // llvm::MachO::mach_header_64 - MH_MAGIC = 0xFEEDFACEu, - MH_CIGAM = 0xCEFAEDFEu, - MH_MAGIC_64 = 0xFEEDFACFu, - MH_CIGAM_64 = 0xCFFAEDFEu, - FAT_MAGIC = 0xCAFEBABEu, - FAT_CIGAM = 0xBEBAFECAu - }; - - enum HeaderFileType { - // Constants for the "filetype" field in llvm::MachO::mach_header and - // llvm::MachO::mach_header_64 - MH_OBJECT = 0x1u, - MH_EXECUTE = 0x2u, - MH_FVMLIB = 0x3u, - MH_CORE = 0x4u, - MH_PRELOAD = 0x5u, - MH_DYLIB = 0x6u, - MH_DYLINKER = 0x7u, - MH_BUNDLE = 0x8u, - MH_DYLIB_STUB = 0x9u, - MH_DSYM = 0xAu, - MH_KEXT_BUNDLE = 0xBu - }; - - enum { - // Constant bits for the "flags" field in llvm::MachO::mach_header and - // llvm::MachO::mach_header_64 - MH_NOUNDEFS = 0x00000001u, - MH_INCRLINK = 0x00000002u, - MH_DYLDLINK = 0x00000004u, - MH_BINDATLOAD = 0x00000008u, - MH_PREBOUND = 0x00000010u, - MH_SPLIT_SEGS = 0x00000020u, - MH_LAZY_INIT = 0x00000040u, - MH_TWOLEVEL = 0x00000080u, - MH_FORCE_FLAT = 0x00000100u, - MH_NOMULTIDEFS = 0x00000200u, - MH_NOFIXPREBINDING = 0x00000400u, - MH_PREBINDABLE = 0x00000800u, - MH_ALLMODSBOUND = 0x00001000u, - MH_SUBSECTIONS_VIA_SYMBOLS = 0x00002000u, - MH_CANONICAL = 0x00004000u, - MH_WEAK_DEFINES = 0x00008000u, - MH_BINDS_TO_WEAK = 0x00010000u, - MH_ALLOW_STACK_EXECUTION = 0x00020000u, - MH_ROOT_SAFE = 0x00040000u, - MH_SETUID_SAFE = 0x00080000u, - MH_NO_REEXPORTED_DYLIBS = 0x00100000u, - MH_PIE = 0x00200000u, - MH_DEAD_STRIPPABLE_DYLIB = 0x00400000u, - MH_HAS_TLV_DESCRIPTORS = 0x00800000u, - MH_NO_HEAP_EXECUTION = 0x01000000u, - MH_APP_EXTENSION_SAFE = 0x02000000u - }; - - enum : uint32_t { - // Flags for the "cmd" field in llvm::MachO::load_command - LC_REQ_DYLD = 0x80000000u - }; - - enum LoadCommandType : uint32_t { - // Constants for the "cmd" field in llvm::MachO::load_command - LC_SEGMENT = 0x00000001u, - LC_SYMTAB = 0x00000002u, - LC_SYMSEG = 0x00000003u, - LC_THREAD = 0x00000004u, - LC_UNIXTHREAD = 0x00000005u, - LC_LOADFVMLIB = 0x00000006u, - LC_IDFVMLIB = 0x00000007u, - LC_IDENT = 0x00000008u, - LC_FVMFILE = 0x00000009u, - LC_PREPAGE = 0x0000000Au, - LC_DYSYMTAB = 0x0000000Bu, - LC_LOAD_DYLIB = 0x0000000Cu, - LC_ID_DYLIB = 0x0000000Du, - LC_LOAD_DYLINKER = 0x0000000Eu, - LC_ID_DYLINKER = 0x0000000Fu, - LC_PREBOUND_DYLIB = 0x00000010u, - LC_ROUTINES = 0x00000011u, - LC_SUB_FRAMEWORK = 0x00000012u, - LC_SUB_UMBRELLA = 0x00000013u, - LC_SUB_CLIENT = 0x00000014u, - LC_SUB_LIBRARY = 0x00000015u, - LC_TWOLEVEL_HINTS = 0x00000016u, - LC_PREBIND_CKSUM = 0x00000017u, - LC_LOAD_WEAK_DYLIB = 0x80000018u, - LC_SEGMENT_64 = 0x00000019u, - LC_ROUTINES_64 = 0x0000001Au, - LC_UUID = 0x0000001Bu, - LC_RPATH = 0x8000001Cu, - LC_CODE_SIGNATURE = 0x0000001Du, - LC_SEGMENT_SPLIT_INFO = 0x0000001Eu, - LC_REEXPORT_DYLIB = 0x8000001Fu, - LC_LAZY_LOAD_DYLIB = 0x00000020u, - LC_ENCRYPTION_INFO = 0x00000021u, - LC_DYLD_INFO = 0x00000022u, - LC_DYLD_INFO_ONLY = 0x80000022u, - LC_LOAD_UPWARD_DYLIB = 0x80000023u, - LC_VERSION_MIN_MACOSX = 0x00000024u, - LC_VERSION_MIN_IPHONEOS = 0x00000025u, - LC_FUNCTION_STARTS = 0x00000026u, - LC_DYLD_ENVIRONMENT = 0x00000027u, - LC_MAIN = 0x80000028u, - LC_DATA_IN_CODE = 0x00000029u, - LC_SOURCE_VERSION = 0x0000002Au, - LC_DYLIB_CODE_SIGN_DRS = 0x0000002Bu, - LC_ENCRYPTION_INFO_64 = 0x0000002Cu, - LC_LINKER_OPTION = 0x0000002Du, - LC_LINKER_OPTIMIZATION_HINT = 0x0000002Eu, - LC_VERSION_MIN_TVOS = 0x0000002Fu, - LC_VERSION_MIN_WATCHOS = 0x00000030u, - }; - - enum : uint32_t { - // Constant bits for the "flags" field in llvm::MachO::segment_command - SG_HIGHVM = 0x1u, - SG_FVMLIB = 0x2u, - SG_NORELOC = 0x4u, - SG_PROTECTED_VERSION_1 = 0x8u, - - // Constant masks for the "flags" field in llvm::MachO::section and - // llvm::MachO::section_64 - SECTION_TYPE = 0x000000ffu, // SECTION_TYPE - SECTION_ATTRIBUTES = 0xffffff00u, // SECTION_ATTRIBUTES - SECTION_ATTRIBUTES_USR = 0xff000000u, // SECTION_ATTRIBUTES_USR - SECTION_ATTRIBUTES_SYS = 0x00ffff00u // SECTION_ATTRIBUTES_SYS - }; - - /// These are the section type and attributes fields. A MachO section can - /// have only one Type, but can have any of the attributes specified. - enum SectionType : uint32_t { - // Constant masks for the "flags[7:0]" field in llvm::MachO::section and - // llvm::MachO::section_64 (mask "flags" with SECTION_TYPE) - - /// S_REGULAR - Regular section. - S_REGULAR = 0x00u, - /// S_ZEROFILL - Zero fill on demand section. - S_ZEROFILL = 0x01u, - /// S_CSTRING_LITERALS - Section with literal C strings. - S_CSTRING_LITERALS = 0x02u, - /// S_4BYTE_LITERALS - Section with 4 byte literals. - S_4BYTE_LITERALS = 0x03u, - /// S_8BYTE_LITERALS - Section with 8 byte literals. - S_8BYTE_LITERALS = 0x04u, - /// S_LITERAL_POINTERS - Section with pointers to literals. - S_LITERAL_POINTERS = 0x05u, - /// S_NON_LAZY_SYMBOL_POINTERS - Section with non-lazy symbol pointers. - S_NON_LAZY_SYMBOL_POINTERS = 0x06u, - /// S_LAZY_SYMBOL_POINTERS - Section with lazy symbol pointers. - S_LAZY_SYMBOL_POINTERS = 0x07u, - /// S_SYMBOL_STUBS - Section with symbol stubs, byte size of stub in - /// the Reserved2 field. - S_SYMBOL_STUBS = 0x08u, - /// S_MOD_INIT_FUNC_POINTERS - Section with only function pointers for - /// initialization. - S_MOD_INIT_FUNC_POINTERS = 0x09u, - /// S_MOD_TERM_FUNC_POINTERS - Section with only function pointers for - /// termination. - S_MOD_TERM_FUNC_POINTERS = 0x0au, - /// S_COALESCED - Section contains symbols that are to be coalesced. - S_COALESCED = 0x0bu, - /// S_GB_ZEROFILL - Zero fill on demand section (that can be larger than 4 - /// gigabytes). - S_GB_ZEROFILL = 0x0cu, - /// S_INTERPOSING - Section with only pairs of function pointers for - /// interposing. - S_INTERPOSING = 0x0du, - /// S_16BYTE_LITERALS - Section with only 16 byte literals. - S_16BYTE_LITERALS = 0x0eu, - /// S_DTRACE_DOF - Section contains DTrace Object Format. - S_DTRACE_DOF = 0x0fu, - /// S_LAZY_DYLIB_SYMBOL_POINTERS - Section with lazy symbol pointers to - /// lazy loaded dylibs. - S_LAZY_DYLIB_SYMBOL_POINTERS = 0x10u, - /// S_THREAD_LOCAL_REGULAR - Thread local data section. - S_THREAD_LOCAL_REGULAR = 0x11u, - /// S_THREAD_LOCAL_ZEROFILL - Thread local zerofill section. - S_THREAD_LOCAL_ZEROFILL = 0x12u, - /// S_THREAD_LOCAL_VARIABLES - Section with thread local variable - /// structure data. - S_THREAD_LOCAL_VARIABLES = 0x13u, - /// S_THREAD_LOCAL_VARIABLE_POINTERS - Section with pointers to thread - /// local structures. - S_THREAD_LOCAL_VARIABLE_POINTERS = 0x14u, - /// S_THREAD_LOCAL_INIT_FUNCTION_POINTERS - Section with thread local - /// variable initialization pointers to functions. - S_THREAD_LOCAL_INIT_FUNCTION_POINTERS = 0x15u, - - LAST_KNOWN_SECTION_TYPE = S_THREAD_LOCAL_INIT_FUNCTION_POINTERS - }; - - enum : uint32_t { - // Constant masks for the "flags[31:24]" field in llvm::MachO::section and - // llvm::MachO::section_64 (mask "flags" with SECTION_ATTRIBUTES_USR) - - /// S_ATTR_PURE_INSTRUCTIONS - Section contains only true machine - /// instructions. - S_ATTR_PURE_INSTRUCTIONS = 0x80000000u, - /// S_ATTR_NO_TOC - Section contains coalesced symbols that are not to be - /// in a ranlib table of contents. - S_ATTR_NO_TOC = 0x40000000u, - /// S_ATTR_STRIP_STATIC_SYMS - Ok to strip static symbols in this section - /// in files with the MY_DYLDLINK flag. - S_ATTR_STRIP_STATIC_SYMS = 0x20000000u, - /// S_ATTR_NO_DEAD_STRIP - No dead stripping. - S_ATTR_NO_DEAD_STRIP = 0x10000000u, - /// S_ATTR_LIVE_SUPPORT - Blocks are live if they reference live blocks. - S_ATTR_LIVE_SUPPORT = 0x08000000u, - /// S_ATTR_SELF_MODIFYING_CODE - Used with i386 code stubs written on by - /// dyld. - S_ATTR_SELF_MODIFYING_CODE = 0x04000000u, - /// S_ATTR_DEBUG - A debug section. - S_ATTR_DEBUG = 0x02000000u, - - // Constant masks for the "flags[23:8]" field in llvm::MachO::section and - // llvm::MachO::section_64 (mask "flags" with SECTION_ATTRIBUTES_SYS) - - /// S_ATTR_SOME_INSTRUCTIONS - Section contains some machine instructions. - S_ATTR_SOME_INSTRUCTIONS = 0x00000400u, - /// S_ATTR_EXT_RELOC - Section has external relocation entries. - S_ATTR_EXT_RELOC = 0x00000200u, - /// S_ATTR_LOC_RELOC - Section has local relocation entries. - S_ATTR_LOC_RELOC = 0x00000100u, - - // Constant masks for the value of an indirect symbol in an indirect - // symbol table - INDIRECT_SYMBOL_LOCAL = 0x80000000u, - INDIRECT_SYMBOL_ABS = 0x40000000u - }; - - enum DataRegionType { - // Constants for the "kind" field in a data_in_code_entry structure - DICE_KIND_DATA = 1u, - DICE_KIND_JUMP_TABLE8 = 2u, - DICE_KIND_JUMP_TABLE16 = 3u, - DICE_KIND_JUMP_TABLE32 = 4u, - DICE_KIND_ABS_JUMP_TABLE32 = 5u - }; - - enum RebaseType { - REBASE_TYPE_POINTER = 1u, - REBASE_TYPE_TEXT_ABSOLUTE32 = 2u, - REBASE_TYPE_TEXT_PCREL32 = 3u - }; - - enum { - REBASE_OPCODE_MASK = 0xF0u, - REBASE_IMMEDIATE_MASK = 0x0Fu - }; - - enum RebaseOpcode { - REBASE_OPCODE_DONE = 0x00u, - REBASE_OPCODE_SET_TYPE_IMM = 0x10u, - REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB = 0x20u, - REBASE_OPCODE_ADD_ADDR_ULEB = 0x30u, - REBASE_OPCODE_ADD_ADDR_IMM_SCALED = 0x40u, - REBASE_OPCODE_DO_REBASE_IMM_TIMES = 0x50u, - REBASE_OPCODE_DO_REBASE_ULEB_TIMES = 0x60u, - REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB = 0x70u, - REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB = 0x80u - }; - - enum BindType { - BIND_TYPE_POINTER = 1u, - BIND_TYPE_TEXT_ABSOLUTE32 = 2u, - BIND_TYPE_TEXT_PCREL32 = 3u - }; - - enum BindSpecialDylib { - BIND_SPECIAL_DYLIB_SELF = 0, - BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE = -1, - BIND_SPECIAL_DYLIB_FLAT_LOOKUP = -2 - }; - - enum { - BIND_SYMBOL_FLAGS_WEAK_IMPORT = 0x1u, - BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION = 0x8u, - - BIND_OPCODE_MASK = 0xF0u, - BIND_IMMEDIATE_MASK = 0x0Fu - }; - - enum BindOpcode { - BIND_OPCODE_DONE = 0x00u, - BIND_OPCODE_SET_DYLIB_ORDINAL_IMM = 0x10u, - BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB = 0x20u, - BIND_OPCODE_SET_DYLIB_SPECIAL_IMM = 0x30u, - BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM = 0x40u, - BIND_OPCODE_SET_TYPE_IMM = 0x50u, - BIND_OPCODE_SET_ADDEND_SLEB = 0x60u, - BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB = 0x70u, - BIND_OPCODE_ADD_ADDR_ULEB = 0x80u, - BIND_OPCODE_DO_BIND = 0x90u, - BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB = 0xA0u, - BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED = 0xB0u, - BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB = 0xC0u - }; - - enum { - EXPORT_SYMBOL_FLAGS_KIND_MASK = 0x03u, - EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION = 0x04u, - EXPORT_SYMBOL_FLAGS_REEXPORT = 0x08u, - EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER = 0x10u - }; - - enum ExportSymbolKind { - EXPORT_SYMBOL_FLAGS_KIND_REGULAR = 0x00u, - EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL = 0x01u, - EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE = 0x02u - }; - - enum { - // Constant masks for the "n_type" field in llvm::MachO::nlist and - // llvm::MachO::nlist_64 - N_STAB = 0xe0, - N_PEXT = 0x10, - N_TYPE = 0x0e, - N_EXT = 0x01 - }; - - enum NListType { - // Constants for the "n_type & N_TYPE" llvm::MachO::nlist and - // llvm::MachO::nlist_64 - N_UNDF = 0x0u, - N_ABS = 0x2u, - N_SECT = 0xeu, - N_PBUD = 0xcu, - N_INDR = 0xau - }; - - enum SectionOrdinal { - // Constants for the "n_sect" field in llvm::MachO::nlist and - // llvm::MachO::nlist_64 - NO_SECT = 0u, - MAX_SECT = 0xffu - }; - - enum { - // Constant masks for the "n_desc" field in llvm::MachO::nlist and - // llvm::MachO::nlist_64 - // The low 3 bits are the for the REFERENCE_TYPE. - REFERENCE_TYPE = 0x7, - REFERENCE_FLAG_UNDEFINED_NON_LAZY = 0, - REFERENCE_FLAG_UNDEFINED_LAZY = 1, - REFERENCE_FLAG_DEFINED = 2, - REFERENCE_FLAG_PRIVATE_DEFINED = 3, - REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY = 4, - REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY = 5, - // Flag bits (some overlap with the library ordinal bits). - N_ARM_THUMB_DEF = 0x0008u, - REFERENCED_DYNAMICALLY = 0x0010u, - N_NO_DEAD_STRIP = 0x0020u, - N_WEAK_REF = 0x0040u, - N_WEAK_DEF = 0x0080u, - N_SYMBOL_RESOLVER = 0x0100u, - N_ALT_ENTRY = 0x0200u, - // For undefined symbols coming from libraries, see GET_LIBRARY_ORDINAL() - // as these are in the top 8 bits. - SELF_LIBRARY_ORDINAL = 0x0, - MAX_LIBRARY_ORDINAL = 0xfd, - DYNAMIC_LOOKUP_ORDINAL = 0xfe, - EXECUTABLE_ORDINAL = 0xff - }; - - enum StabType { - // Constant values for the "n_type" field in llvm::MachO::nlist and - // llvm::MachO::nlist_64 when "(n_type & N_STAB) != 0" - N_GSYM = 0x20u, - N_FNAME = 0x22u, - N_FUN = 0x24u, - N_STSYM = 0x26u, - N_LCSYM = 0x28u, - N_BNSYM = 0x2Eu, - N_PC = 0x30u, - N_AST = 0x32u, - N_OPT = 0x3Cu, - N_RSYM = 0x40u, - N_SLINE = 0x44u, - N_ENSYM = 0x4Eu, - N_SSYM = 0x60u, - N_SO = 0x64u, - N_OSO = 0x66u, - N_LSYM = 0x80u, - N_BINCL = 0x82u, - N_SOL = 0x84u, - N_PARAMS = 0x86u, - N_VERSION = 0x88u, - N_OLEVEL = 0x8Au, - N_PSYM = 0xA0u, - N_EINCL = 0xA2u, - N_ENTRY = 0xA4u, - N_LBRAC = 0xC0u, - N_EXCL = 0xC2u, - N_RBRAC = 0xE0u, - N_BCOMM = 0xE2u, - N_ECOMM = 0xE4u, - N_ECOML = 0xE8u, - N_LENG = 0xFEu - }; - - enum : uint32_t { - // Constant values for the r_symbolnum field in an - // llvm::MachO::relocation_info structure when r_extern is 0. - R_ABS = 0, - - // Constant bits for the r_address field in an - // llvm::MachO::relocation_info structure. - R_SCATTERED = 0x80000000 - }; - - enum RelocationInfoType { - // Constant values for the r_type field in an - // llvm::MachO::relocation_info or llvm::MachO::scattered_relocation_info - // structure. - GENERIC_RELOC_VANILLA = 0, - GENERIC_RELOC_PAIR = 1, - GENERIC_RELOC_SECTDIFF = 2, - GENERIC_RELOC_PB_LA_PTR = 3, - GENERIC_RELOC_LOCAL_SECTDIFF = 4, - GENERIC_RELOC_TLV = 5, - - // Constant values for the r_type field in a PowerPC architecture - // llvm::MachO::relocation_info or llvm::MachO::scattered_relocation_info - // structure. - PPC_RELOC_VANILLA = GENERIC_RELOC_VANILLA, - PPC_RELOC_PAIR = GENERIC_RELOC_PAIR, - PPC_RELOC_BR14 = 2, - PPC_RELOC_BR24 = 3, - PPC_RELOC_HI16 = 4, - PPC_RELOC_LO16 = 5, - PPC_RELOC_HA16 = 6, - PPC_RELOC_LO14 = 7, - PPC_RELOC_SECTDIFF = 8, - PPC_RELOC_PB_LA_PTR = 9, - PPC_RELOC_HI16_SECTDIFF = 10, - PPC_RELOC_LO16_SECTDIFF = 11, - PPC_RELOC_HA16_SECTDIFF = 12, - PPC_RELOC_JBSR = 13, - PPC_RELOC_LO14_SECTDIFF = 14, - PPC_RELOC_LOCAL_SECTDIFF = 15, - - // Constant values for the r_type field in an ARM architecture - // llvm::MachO::relocation_info or llvm::MachO::scattered_relocation_info - // structure. - ARM_RELOC_VANILLA = GENERIC_RELOC_VANILLA, - ARM_RELOC_PAIR = GENERIC_RELOC_PAIR, - ARM_RELOC_SECTDIFF = GENERIC_RELOC_SECTDIFF, - ARM_RELOC_LOCAL_SECTDIFF = 3, - ARM_RELOC_PB_LA_PTR = 4, - ARM_RELOC_BR24 = 5, - ARM_THUMB_RELOC_BR22 = 6, - ARM_THUMB_32BIT_BRANCH = 7, // obsolete - ARM_RELOC_HALF = 8, - ARM_RELOC_HALF_SECTDIFF = 9, - - // Constant values for the r_type field in an ARM64 architecture - // llvm::MachO::relocation_info or llvm::MachO::scattered_relocation_info - // structure. - - // For pointers. - ARM64_RELOC_UNSIGNED = 0, - // Must be followed by an ARM64_RELOC_UNSIGNED - ARM64_RELOC_SUBTRACTOR = 1, - // A B/BL instruction with 26-bit displacement. - ARM64_RELOC_BRANCH26 = 2, - // PC-rel distance to page of target. - ARM64_RELOC_PAGE21 = 3, - // Offset within page, scaled by r_length. - ARM64_RELOC_PAGEOFF12 = 4, - // PC-rel distance to page of GOT slot. - ARM64_RELOC_GOT_LOAD_PAGE21 = 5, - // Offset within page of GOT slot, scaled by r_length. - ARM64_RELOC_GOT_LOAD_PAGEOFF12 = 6, - // For pointers to GOT slots. - ARM64_RELOC_POINTER_TO_GOT = 7, - // PC-rel distance to page of TLVP slot. - ARM64_RELOC_TLVP_LOAD_PAGE21 = 8, - // Offset within page of TLVP slot, scaled by r_length. - ARM64_RELOC_TLVP_LOAD_PAGEOFF12 = 9, - // Must be followed by ARM64_RELOC_PAGE21 or ARM64_RELOC_PAGEOFF12. - ARM64_RELOC_ADDEND = 10, - - // Constant values for the r_type field in an x86_64 architecture - // llvm::MachO::relocation_info or llvm::MachO::scattered_relocation_info - // structure - X86_64_RELOC_UNSIGNED = 0, - X86_64_RELOC_SIGNED = 1, - X86_64_RELOC_BRANCH = 2, - X86_64_RELOC_GOT_LOAD = 3, - X86_64_RELOC_GOT = 4, - X86_64_RELOC_SUBTRACTOR = 5, - X86_64_RELOC_SIGNED_1 = 6, - X86_64_RELOC_SIGNED_2 = 7, - X86_64_RELOC_SIGNED_4 = 8, - X86_64_RELOC_TLV = 9 - }; - - // Values for segment_command.initprot. - // From - enum { - VM_PROT_READ = 0x1, - VM_PROT_WRITE = 0x2, - VM_PROT_EXECUTE = 0x4 - }; - - // Structs from - - struct mach_header { - uint32_t magic; - uint32_t cputype; - uint32_t cpusubtype; - uint32_t filetype; - uint32_t ncmds; - uint32_t sizeofcmds; - uint32_t flags; - }; - - struct mach_header_64 { - uint32_t magic; - uint32_t cputype; - uint32_t cpusubtype; - uint32_t filetype; - uint32_t ncmds; - uint32_t sizeofcmds; - uint32_t flags; - uint32_t reserved; - }; - - struct load_command { - uint32_t cmd; - uint32_t cmdsize; - }; - - struct segment_command { - uint32_t cmd; - uint32_t cmdsize; - char segname[16]; - uint32_t vmaddr; - uint32_t vmsize; - uint32_t fileoff; - uint32_t filesize; - uint32_t maxprot; - uint32_t initprot; - uint32_t nsects; - uint32_t flags; - }; - - struct segment_command_64 { - uint32_t cmd; - uint32_t cmdsize; - char segname[16]; - uint64_t vmaddr; - uint64_t vmsize; - uint64_t fileoff; - uint64_t filesize; - uint32_t maxprot; - uint32_t initprot; - uint32_t nsects; - uint32_t flags; - }; - - struct section { - char sectname[16]; - char segname[16]; - uint32_t addr; - uint32_t size; - uint32_t offset; - uint32_t align; - uint32_t reloff; - uint32_t nreloc; - uint32_t flags; - uint32_t reserved1; - uint32_t reserved2; - }; - - struct section_64 { - char sectname[16]; - char segname[16]; - uint64_t addr; - uint64_t size; - uint32_t offset; - uint32_t align; - uint32_t reloff; - uint32_t nreloc; - uint32_t flags; - uint32_t reserved1; - uint32_t reserved2; - uint32_t reserved3; - }; - - struct fvmlib { - uint32_t name; - uint32_t minor_version; - uint32_t header_addr; - }; - - struct fvmlib_command { - uint32_t cmd; - uint32_t cmdsize; - struct fvmlib fvmlib; - }; - - struct dylib { - uint32_t name; - uint32_t timestamp; - uint32_t current_version; - uint32_t compatibility_version; - }; - - struct dylib_command { - uint32_t cmd; - uint32_t cmdsize; - struct dylib dylib; - }; - - struct sub_framework_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t umbrella; - }; - - struct sub_client_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t client; - }; - - struct sub_umbrella_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t sub_umbrella; - }; - - struct sub_library_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t sub_library; - }; - - struct prebound_dylib_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t name; - uint32_t nmodules; - uint32_t linked_modules; - }; - - struct dylinker_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t name; - }; - - struct thread_command { - uint32_t cmd; - uint32_t cmdsize; - }; - - struct routines_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t init_address; - uint32_t init_module; - uint32_t reserved1; - uint32_t reserved2; - uint32_t reserved3; - uint32_t reserved4; - uint32_t reserved5; - uint32_t reserved6; - }; - - struct routines_command_64 { - uint32_t cmd; - uint32_t cmdsize; - uint64_t init_address; - uint64_t init_module; - uint64_t reserved1; - uint64_t reserved2; - uint64_t reserved3; - uint64_t reserved4; - uint64_t reserved5; - uint64_t reserved6; - }; - - struct symtab_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t symoff; - uint32_t nsyms; - uint32_t stroff; - uint32_t strsize; - }; - - struct dysymtab_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t ilocalsym; - uint32_t nlocalsym; - uint32_t iextdefsym; - uint32_t nextdefsym; - uint32_t iundefsym; - uint32_t nundefsym; - uint32_t tocoff; - uint32_t ntoc; - uint32_t modtaboff; - uint32_t nmodtab; - uint32_t extrefsymoff; - uint32_t nextrefsyms; - uint32_t indirectsymoff; - uint32_t nindirectsyms; - uint32_t extreloff; - uint32_t nextrel; - uint32_t locreloff; - uint32_t nlocrel; - }; - - struct dylib_table_of_contents { - uint32_t symbol_index; - uint32_t module_index; - }; - - struct dylib_module { - uint32_t module_name; - uint32_t iextdefsym; - uint32_t nextdefsym; - uint32_t irefsym; - uint32_t nrefsym; - uint32_t ilocalsym; - uint32_t nlocalsym; - uint32_t iextrel; - uint32_t nextrel; - uint32_t iinit_iterm; - uint32_t ninit_nterm; - uint32_t objc_module_info_addr; - uint32_t objc_module_info_size; - }; - - struct dylib_module_64 { - uint32_t module_name; - uint32_t iextdefsym; - uint32_t nextdefsym; - uint32_t irefsym; - uint32_t nrefsym; - uint32_t ilocalsym; - uint32_t nlocalsym; - uint32_t iextrel; - uint32_t nextrel; - uint32_t iinit_iterm; - uint32_t ninit_nterm; - uint32_t objc_module_info_size; - uint64_t objc_module_info_addr; - }; - - struct dylib_reference { - uint32_t isym:24, - flags:8; - }; - - struct twolevel_hints_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t offset; - uint32_t nhints; - }; - - struct twolevel_hint { - uint32_t isub_image:8, - itoc:24; - }; - - struct prebind_cksum_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t cksum; - }; - - struct uuid_command { - uint32_t cmd; - uint32_t cmdsize; - uint8_t uuid[16]; - }; - - struct rpath_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t path; - }; - - struct linkedit_data_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t dataoff; - uint32_t datasize; - }; - - struct data_in_code_entry { - uint32_t offset; - uint16_t length; - uint16_t kind; - }; - - struct source_version_command { - uint32_t cmd; - uint32_t cmdsize; - uint64_t version; - }; - - struct encryption_info_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t cryptoff; - uint32_t cryptsize; - uint32_t cryptid; - }; - - struct encryption_info_command_64 { - uint32_t cmd; - uint32_t cmdsize; - uint32_t cryptoff; - uint32_t cryptsize; - uint32_t cryptid; - uint32_t pad; - }; - - struct version_min_command { - uint32_t cmd; // LC_VERSION_MIN_MACOSX or - // LC_VERSION_MIN_IPHONEOS - uint32_t cmdsize; // sizeof(struct version_min_command) - uint32_t version; // X.Y.Z is encoded in nibbles xxxx.yy.zz - uint32_t sdk; // X.Y.Z is encoded in nibbles xxxx.yy.zz - }; - - struct dyld_info_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t rebase_off; - uint32_t rebase_size; - uint32_t bind_off; - uint32_t bind_size; - uint32_t weak_bind_off; - uint32_t weak_bind_size; - uint32_t lazy_bind_off; - uint32_t lazy_bind_size; - uint32_t export_off; - uint32_t export_size; - }; - - struct linker_option_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t count; - }; - - struct symseg_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t offset; - uint32_t size; - }; - - struct ident_command { - uint32_t cmd; - uint32_t cmdsize; - }; - - struct fvmfile_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t name; - uint32_t header_addr; - }; - - struct tlv_descriptor_32 { - uint32_t thunk; - uint32_t key; - uint32_t offset; - }; - - struct tlv_descriptor_64 { - uint64_t thunk; - uint64_t key; - uint64_t offset; - }; - - struct tlv_descriptor { - uintptr_t thunk; - uintptr_t key; - uintptr_t offset; - }; - - struct entry_point_command { - uint32_t cmd; - uint32_t cmdsize; - uint64_t entryoff; - uint64_t stacksize; - }; - - // Structs from - struct fat_header { - uint32_t magic; - uint32_t nfat_arch; - }; - - struct fat_arch { - uint32_t cputype; - uint32_t cpusubtype; - uint32_t offset; - uint32_t size; - uint32_t align; - }; - - // Structs from - struct relocation_info { - int32_t r_address; - uint32_t r_symbolnum:24, - r_pcrel:1, - r_length:2, - r_extern:1, - r_type:4; - }; - - struct scattered_relocation_info { -#if defined(BYTE_ORDER) && defined(BIG_ENDIAN) && (BYTE_ORDER == BIG_ENDIAN) - uint32_t r_scattered:1, - r_pcrel:1, - r_length:2, - r_type:4, - r_address:24; -#else - uint32_t r_address:24, - r_type:4, - r_length:2, - r_pcrel:1, - r_scattered:1; -#endif - int32_t r_value; - }; - - // Structs NOT from , but that make LLVM's life easier - struct any_relocation_info { - uint32_t r_word0, r_word1; - }; - - // Structs from - struct nlist_base { - uint32_t n_strx; - uint8_t n_type; - uint8_t n_sect; - uint16_t n_desc; - }; - - struct nlist { - uint32_t n_strx; - uint8_t n_type; - uint8_t n_sect; - int16_t n_desc; - uint32_t n_value; - }; - - struct nlist_64 { - uint32_t n_strx; - uint8_t n_type; - uint8_t n_sect; - uint16_t n_desc; - uint64_t n_value; - }; - - // Byte order swapping functions for MachO structs - - inline void swapStruct(mach_header &mh) { - sys::swapByteOrder(mh.magic); - sys::swapByteOrder(mh.cputype); - sys::swapByteOrder(mh.cpusubtype); - sys::swapByteOrder(mh.filetype); - sys::swapByteOrder(mh.ncmds); - sys::swapByteOrder(mh.sizeofcmds); - sys::swapByteOrder(mh.flags); - } - - inline void swapStruct(mach_header_64 &H) { - sys::swapByteOrder(H.magic); - sys::swapByteOrder(H.cputype); - sys::swapByteOrder(H.cpusubtype); - sys::swapByteOrder(H.filetype); - sys::swapByteOrder(H.ncmds); - sys::swapByteOrder(H.sizeofcmds); - sys::swapByteOrder(H.flags); - sys::swapByteOrder(H.reserved); - } - - inline void swapStruct(load_command &lc) { - sys::swapByteOrder(lc.cmd); - sys::swapByteOrder(lc.cmdsize); - } - - inline void swapStruct(symtab_command &lc) { - sys::swapByteOrder(lc.cmd); - sys::swapByteOrder(lc.cmdsize); - sys::swapByteOrder(lc.symoff); - sys::swapByteOrder(lc.nsyms); - sys::swapByteOrder(lc.stroff); - sys::swapByteOrder(lc.strsize); - } - - inline void swapStruct(segment_command_64 &seg) { - sys::swapByteOrder(seg.cmd); - sys::swapByteOrder(seg.cmdsize); - sys::swapByteOrder(seg.vmaddr); - sys::swapByteOrder(seg.vmsize); - sys::swapByteOrder(seg.fileoff); - sys::swapByteOrder(seg.filesize); - sys::swapByteOrder(seg.maxprot); - sys::swapByteOrder(seg.initprot); - sys::swapByteOrder(seg.nsects); - sys::swapByteOrder(seg.flags); - } - - inline void swapStruct(segment_command &seg) { - sys::swapByteOrder(seg.cmd); - sys::swapByteOrder(seg.cmdsize); - sys::swapByteOrder(seg.vmaddr); - sys::swapByteOrder(seg.vmsize); - sys::swapByteOrder(seg.fileoff); - sys::swapByteOrder(seg.filesize); - sys::swapByteOrder(seg.maxprot); - sys::swapByteOrder(seg.initprot); - sys::swapByteOrder(seg.nsects); - sys::swapByteOrder(seg.flags); - } - - inline void swapStruct(section_64 §) { - sys::swapByteOrder(sect.addr); - sys::swapByteOrder(sect.size); - sys::swapByteOrder(sect.offset); - sys::swapByteOrder(sect.align); - sys::swapByteOrder(sect.reloff); - sys::swapByteOrder(sect.nreloc); - sys::swapByteOrder(sect.flags); - sys::swapByteOrder(sect.reserved1); - sys::swapByteOrder(sect.reserved2); - } - - inline void swapStruct(section §) { - sys::swapByteOrder(sect.addr); - sys::swapByteOrder(sect.size); - sys::swapByteOrder(sect.offset); - sys::swapByteOrder(sect.align); - sys::swapByteOrder(sect.reloff); - sys::swapByteOrder(sect.nreloc); - sys::swapByteOrder(sect.flags); - sys::swapByteOrder(sect.reserved1); - sys::swapByteOrder(sect.reserved2); - } - - inline void swapStruct(dyld_info_command &info) { - sys::swapByteOrder(info.cmd); - sys::swapByteOrder(info.cmdsize); - sys::swapByteOrder(info.rebase_off); - sys::swapByteOrder(info.rebase_size); - sys::swapByteOrder(info.bind_off); - sys::swapByteOrder(info.bind_size); - sys::swapByteOrder(info.weak_bind_off); - sys::swapByteOrder(info.weak_bind_size); - sys::swapByteOrder(info.lazy_bind_off); - sys::swapByteOrder(info.lazy_bind_size); - sys::swapByteOrder(info.export_off); - sys::swapByteOrder(info.export_size); - } - - inline void swapStruct(dylib_command &d) { - sys::swapByteOrder(d.cmd); - sys::swapByteOrder(d.cmdsize); - sys::swapByteOrder(d.dylib.name); - sys::swapByteOrder(d.dylib.timestamp); - sys::swapByteOrder(d.dylib.current_version); - sys::swapByteOrder(d.dylib.compatibility_version); - } - - inline void swapStruct(sub_framework_command &s) { - sys::swapByteOrder(s.cmd); - sys::swapByteOrder(s.cmdsize); - sys::swapByteOrder(s.umbrella); - } - - inline void swapStruct(sub_umbrella_command &s) { - sys::swapByteOrder(s.cmd); - sys::swapByteOrder(s.cmdsize); - sys::swapByteOrder(s.sub_umbrella); - } - - inline void swapStruct(sub_library_command &s) { - sys::swapByteOrder(s.cmd); - sys::swapByteOrder(s.cmdsize); - sys::swapByteOrder(s.sub_library); - } - - inline void swapStruct(sub_client_command &s) { - sys::swapByteOrder(s.cmd); - sys::swapByteOrder(s.cmdsize); - sys::swapByteOrder(s.client); - } - - inline void swapStruct(routines_command &r) { - sys::swapByteOrder(r.cmd); - sys::swapByteOrder(r.cmdsize); - sys::swapByteOrder(r.init_address); - sys::swapByteOrder(r.init_module); - sys::swapByteOrder(r.reserved1); - sys::swapByteOrder(r.reserved2); - sys::swapByteOrder(r.reserved3); - sys::swapByteOrder(r.reserved4); - sys::swapByteOrder(r.reserved5); - sys::swapByteOrder(r.reserved6); - } - - inline void swapStruct(routines_command_64 &r) { - sys::swapByteOrder(r.cmd); - sys::swapByteOrder(r.cmdsize); - sys::swapByteOrder(r.init_address); - sys::swapByteOrder(r.init_module); - sys::swapByteOrder(r.reserved1); - sys::swapByteOrder(r.reserved2); - sys::swapByteOrder(r.reserved3); - sys::swapByteOrder(r.reserved4); - sys::swapByteOrder(r.reserved5); - sys::swapByteOrder(r.reserved6); - } - - inline void swapStruct(thread_command &t) { - sys::swapByteOrder(t.cmd); - sys::swapByteOrder(t.cmdsize); - } - - inline void swapStruct(dylinker_command &d) { - sys::swapByteOrder(d.cmd); - sys::swapByteOrder(d.cmdsize); - sys::swapByteOrder(d.name); - } - - inline void swapStruct(uuid_command &u) { - sys::swapByteOrder(u.cmd); - sys::swapByteOrder(u.cmdsize); - } - - inline void swapStruct(rpath_command &r) { - sys::swapByteOrder(r.cmd); - sys::swapByteOrder(r.cmdsize); - sys::swapByteOrder(r.path); - } - - inline void swapStruct(source_version_command &s) { - sys::swapByteOrder(s.cmd); - sys::swapByteOrder(s.cmdsize); - sys::swapByteOrder(s.version); - } - - inline void swapStruct(entry_point_command &e) { - sys::swapByteOrder(e.cmd); - sys::swapByteOrder(e.cmdsize); - sys::swapByteOrder(e.entryoff); - sys::swapByteOrder(e.stacksize); - } - - inline void swapStruct(encryption_info_command &e) { - sys::swapByteOrder(e.cmd); - sys::swapByteOrder(e.cmdsize); - sys::swapByteOrder(e.cryptoff); - sys::swapByteOrder(e.cryptsize); - sys::swapByteOrder(e.cryptid); - } - - inline void swapStruct(encryption_info_command_64 &e) { - sys::swapByteOrder(e.cmd); - sys::swapByteOrder(e.cmdsize); - sys::swapByteOrder(e.cryptoff); - sys::swapByteOrder(e.cryptsize); - sys::swapByteOrder(e.cryptid); - sys::swapByteOrder(e.pad); - } - - inline void swapStruct(dysymtab_command &dst) { - sys::swapByteOrder(dst.cmd); - sys::swapByteOrder(dst.cmdsize); - sys::swapByteOrder(dst.ilocalsym); - sys::swapByteOrder(dst.nlocalsym); - sys::swapByteOrder(dst.iextdefsym); - sys::swapByteOrder(dst.nextdefsym); - sys::swapByteOrder(dst.iundefsym); - sys::swapByteOrder(dst.nundefsym); - sys::swapByteOrder(dst.tocoff); - sys::swapByteOrder(dst.ntoc); - sys::swapByteOrder(dst.modtaboff); - sys::swapByteOrder(dst.nmodtab); - sys::swapByteOrder(dst.extrefsymoff); - sys::swapByteOrder(dst.nextrefsyms); - sys::swapByteOrder(dst.indirectsymoff); - sys::swapByteOrder(dst.nindirectsyms); - sys::swapByteOrder(dst.extreloff); - sys::swapByteOrder(dst.nextrel); - sys::swapByteOrder(dst.locreloff); - sys::swapByteOrder(dst.nlocrel); - } - - inline void swapStruct(any_relocation_info &reloc) { - sys::swapByteOrder(reloc.r_word0); - sys::swapByteOrder(reloc.r_word1); - } - - inline void swapStruct(nlist_base &S) { - sys::swapByteOrder(S.n_strx); - sys::swapByteOrder(S.n_desc); - } - - inline void swapStruct(nlist &sym) { - sys::swapByteOrder(sym.n_strx); - sys::swapByteOrder(sym.n_desc); - sys::swapByteOrder(sym.n_value); - } - - inline void swapStruct(nlist_64 &sym) { - sys::swapByteOrder(sym.n_strx); - sys::swapByteOrder(sym.n_desc); - sys::swapByteOrder(sym.n_value); - } - - inline void swapStruct(linkedit_data_command &C) { - sys::swapByteOrder(C.cmd); - sys::swapByteOrder(C.cmdsize); - sys::swapByteOrder(C.dataoff); - sys::swapByteOrder(C.datasize); - } - - inline void swapStruct(linker_option_command &C) { - sys::swapByteOrder(C.cmd); - sys::swapByteOrder(C.cmdsize); - sys::swapByteOrder(C.count); - } - - inline void swapStruct(version_min_command&C) { - sys::swapByteOrder(C.cmd); - sys::swapByteOrder(C.cmdsize); - sys::swapByteOrder(C.version); - sys::swapByteOrder(C.sdk); - } - - inline void swapStruct(data_in_code_entry &C) { - sys::swapByteOrder(C.offset); - sys::swapByteOrder(C.length); - sys::swapByteOrder(C.kind); - } - - inline void swapStruct(uint32_t &C) { - sys::swapByteOrder(C); - } - - // Get/Set functions from - - static inline uint16_t GET_LIBRARY_ORDINAL(uint16_t n_desc) { - return (((n_desc) >> 8u) & 0xffu); - } - - static inline void SET_LIBRARY_ORDINAL(uint16_t &n_desc, uint8_t ordinal) { - n_desc = (((n_desc) & 0x00ff) | (((ordinal) & 0xff) << 8)); - } - - static inline uint8_t GET_COMM_ALIGN (uint16_t n_desc) { - return (n_desc >> 8u) & 0x0fu; - } - - static inline void SET_COMM_ALIGN (uint16_t &n_desc, uint8_t align) { - n_desc = ((n_desc & 0xf0ffu) | ((align & 0x0fu) << 8u)); - } - - // Enums from - enum : uint32_t { - // Capability bits used in the definition of cpu_type. - CPU_ARCH_MASK = 0xff000000, // Mask for architecture bits - CPU_ARCH_ABI64 = 0x01000000 // 64 bit ABI - }; - - // Constants for the cputype field. - enum CPUType { - CPU_TYPE_ANY = -1, - CPU_TYPE_X86 = 7, - CPU_TYPE_I386 = CPU_TYPE_X86, - CPU_TYPE_X86_64 = CPU_TYPE_X86 | CPU_ARCH_ABI64, - /* CPU_TYPE_MIPS = 8, */ - CPU_TYPE_MC98000 = 10, // Old Motorola PowerPC - CPU_TYPE_ARM = 12, - CPU_TYPE_ARM64 = CPU_TYPE_ARM | CPU_ARCH_ABI64, - CPU_TYPE_SPARC = 14, - CPU_TYPE_POWERPC = 18, - CPU_TYPE_POWERPC64 = CPU_TYPE_POWERPC | CPU_ARCH_ABI64 - }; - - enum : uint32_t { - // Capability bits used in the definition of cpusubtype. - CPU_SUBTYPE_MASK = 0xff000000, // Mask for architecture bits - CPU_SUBTYPE_LIB64 = 0x80000000, // 64 bit libraries - - // Special CPU subtype constants. - CPU_SUBTYPE_MULTIPLE = ~0u - }; - - // Constants for the cpusubtype field. - enum CPUSubTypeX86 { - CPU_SUBTYPE_I386_ALL = 3, - CPU_SUBTYPE_386 = 3, - CPU_SUBTYPE_486 = 4, - CPU_SUBTYPE_486SX = 0x84, - CPU_SUBTYPE_586 = 5, - CPU_SUBTYPE_PENT = CPU_SUBTYPE_586, - CPU_SUBTYPE_PENTPRO = 0x16, - CPU_SUBTYPE_PENTII_M3 = 0x36, - CPU_SUBTYPE_PENTII_M5 = 0x56, - CPU_SUBTYPE_CELERON = 0x67, - CPU_SUBTYPE_CELERON_MOBILE = 0x77, - CPU_SUBTYPE_PENTIUM_3 = 0x08, - CPU_SUBTYPE_PENTIUM_3_M = 0x18, - CPU_SUBTYPE_PENTIUM_3_XEON = 0x28, - CPU_SUBTYPE_PENTIUM_M = 0x09, - CPU_SUBTYPE_PENTIUM_4 = 0x0a, - CPU_SUBTYPE_PENTIUM_4_M = 0x1a, - CPU_SUBTYPE_ITANIUM = 0x0b, - CPU_SUBTYPE_ITANIUM_2 = 0x1b, - CPU_SUBTYPE_XEON = 0x0c, - CPU_SUBTYPE_XEON_MP = 0x1c, - - CPU_SUBTYPE_X86_ALL = 3, - CPU_SUBTYPE_X86_64_ALL = 3, - CPU_SUBTYPE_X86_ARCH1 = 4, - CPU_SUBTYPE_X86_64_H = 8 - }; - static inline int CPU_SUBTYPE_INTEL(int Family, int Model) { - return Family | (Model << 4); - } - static inline int CPU_SUBTYPE_INTEL_FAMILY(CPUSubTypeX86 ST) { - return ((int)ST) & 0x0f; - } - static inline int CPU_SUBTYPE_INTEL_MODEL(CPUSubTypeX86 ST) { - return ((int)ST) >> 4; - } - enum { - CPU_SUBTYPE_INTEL_FAMILY_MAX = 15, - CPU_SUBTYPE_INTEL_MODEL_ALL = 0 - }; - - enum CPUSubTypeARM { - CPU_SUBTYPE_ARM_ALL = 0, - CPU_SUBTYPE_ARM_V4T = 5, - CPU_SUBTYPE_ARM_V6 = 6, - CPU_SUBTYPE_ARM_V5 = 7, - CPU_SUBTYPE_ARM_V5TEJ = 7, - CPU_SUBTYPE_ARM_XSCALE = 8, - CPU_SUBTYPE_ARM_V7 = 9, - // unused ARM_V7F = 10, - CPU_SUBTYPE_ARM_V7S = 11, - CPU_SUBTYPE_ARM_V7K = 12, - CPU_SUBTYPE_ARM_V6M = 14, - CPU_SUBTYPE_ARM_V7M = 15, - CPU_SUBTYPE_ARM_V7EM = 16 - }; - - enum CPUSubTypeARM64 { - CPU_SUBTYPE_ARM64_ALL = 0 - }; - - enum CPUSubTypeSPARC { - CPU_SUBTYPE_SPARC_ALL = 0 - }; - - enum CPUSubTypePowerPC { - CPU_SUBTYPE_POWERPC_ALL = 0, - CPU_SUBTYPE_POWERPC_601 = 1, - CPU_SUBTYPE_POWERPC_602 = 2, - CPU_SUBTYPE_POWERPC_603 = 3, - CPU_SUBTYPE_POWERPC_603e = 4, - CPU_SUBTYPE_POWERPC_603ev = 5, - CPU_SUBTYPE_POWERPC_604 = 6, - CPU_SUBTYPE_POWERPC_604e = 7, - CPU_SUBTYPE_POWERPC_620 = 8, - CPU_SUBTYPE_POWERPC_750 = 9, - CPU_SUBTYPE_POWERPC_7400 = 10, - CPU_SUBTYPE_POWERPC_7450 = 11, - CPU_SUBTYPE_POWERPC_970 = 100, - - CPU_SUBTYPE_MC980000_ALL = CPU_SUBTYPE_POWERPC_ALL, - CPU_SUBTYPE_MC98601 = CPU_SUBTYPE_POWERPC_601 - }; - - struct x86_thread_state64_t { - uint64_t rax; - uint64_t rbx; - uint64_t rcx; - uint64_t rdx; - uint64_t rdi; - uint64_t rsi; - uint64_t rbp; - uint64_t rsp; - uint64_t r8; - uint64_t r9; - uint64_t r10; - uint64_t r11; - uint64_t r12; - uint64_t r13; - uint64_t r14; - uint64_t r15; - uint64_t rip; - uint64_t rflags; - uint64_t cs; - uint64_t fs; - uint64_t gs; - }; - - enum x86_fp_control_precis { - x86_FP_PREC_24B = 0, - x86_FP_PREC_53B = 2, - x86_FP_PREC_64B = 3 - }; - - enum x86_fp_control_rc { - x86_FP_RND_NEAR = 0, - x86_FP_RND_DOWN = 1, - x86_FP_RND_UP = 2, - x86_FP_CHOP = 3 - }; - - struct fp_control_t { - unsigned short - invalid :1, - denorm :1, - zdiv :1, - ovrfl :1, - undfl :1, - precis :1, - :2, - pc :2, - rc :2, - :1, - :3; - }; - - struct fp_status_t { - unsigned short - invalid :1, - denorm :1, - zdiv :1, - ovrfl :1, - undfl :1, - precis :1, - stkflt :1, - errsumm :1, - c0 :1, - c1 :1, - c2 :1, - tos :3, - c3 :1, - busy :1; - }; - - struct mmst_reg_t { - char mmst_reg[10]; - char mmst_rsrv[6]; - }; - - struct xmm_reg_t { - char xmm_reg[16]; - }; - - struct x86_float_state64_t { - int32_t fpu_reserved[2]; - fp_control_t fpu_fcw; - fp_status_t fpu_fsw; - uint8_t fpu_ftw; - uint8_t fpu_rsrv1; - uint16_t fpu_fop; - uint32_t fpu_ip; - uint16_t fpu_cs; - uint16_t fpu_rsrv2; - uint32_t fpu_dp; - uint16_t fpu_ds; - uint16_t fpu_rsrv3; - uint32_t fpu_mxcsr; - uint32_t fpu_mxcsrmask; - mmst_reg_t fpu_stmm0; - mmst_reg_t fpu_stmm1; - mmst_reg_t fpu_stmm2; - mmst_reg_t fpu_stmm3; - mmst_reg_t fpu_stmm4; - mmst_reg_t fpu_stmm5; - mmst_reg_t fpu_stmm6; - mmst_reg_t fpu_stmm7; - xmm_reg_t fpu_xmm0; - xmm_reg_t fpu_xmm1; - xmm_reg_t fpu_xmm2; - xmm_reg_t fpu_xmm3; - xmm_reg_t fpu_xmm4; - xmm_reg_t fpu_xmm5; - xmm_reg_t fpu_xmm6; - xmm_reg_t fpu_xmm7; - xmm_reg_t fpu_xmm8; - xmm_reg_t fpu_xmm9; - xmm_reg_t fpu_xmm10; - xmm_reg_t fpu_xmm11; - xmm_reg_t fpu_xmm12; - xmm_reg_t fpu_xmm13; - xmm_reg_t fpu_xmm14; - xmm_reg_t fpu_xmm15; - char fpu_rsrv4[6*16]; - uint32_t fpu_reserved1; - }; - - struct x86_exception_state64_t { - uint16_t trapno; - uint16_t cpu; - uint32_t err; - uint64_t faultvaddr; - }; - - inline void swapStruct(x86_thread_state64_t &x) { - sys::swapByteOrder(x.rax); - sys::swapByteOrder(x.rbx); - sys::swapByteOrder(x.rcx); - sys::swapByteOrder(x.rdx); - sys::swapByteOrder(x.rdi); - sys::swapByteOrder(x.rsi); - sys::swapByteOrder(x.rbp); - sys::swapByteOrder(x.rsp); - sys::swapByteOrder(x.r8); - sys::swapByteOrder(x.r9); - sys::swapByteOrder(x.r10); - sys::swapByteOrder(x.r11); - sys::swapByteOrder(x.r12); - sys::swapByteOrder(x.r13); - sys::swapByteOrder(x.r14); - sys::swapByteOrder(x.r15); - sys::swapByteOrder(x.rip); - sys::swapByteOrder(x.rflags); - sys::swapByteOrder(x.cs); - sys::swapByteOrder(x.fs); - sys::swapByteOrder(x.gs); - } - - inline void swapStruct(x86_float_state64_t &x) { - sys::swapByteOrder(x.fpu_reserved[0]); - sys::swapByteOrder(x.fpu_reserved[1]); - // TODO swap: fp_control_t fpu_fcw; - // TODO swap: fp_status_t fpu_fsw; - sys::swapByteOrder(x.fpu_fop); - sys::swapByteOrder(x.fpu_ip); - sys::swapByteOrder(x.fpu_cs); - sys::swapByteOrder(x.fpu_rsrv2); - sys::swapByteOrder(x.fpu_dp); - sys::swapByteOrder(x.fpu_ds); - sys::swapByteOrder(x.fpu_rsrv3); - sys::swapByteOrder(x.fpu_mxcsr); - sys::swapByteOrder(x.fpu_mxcsrmask); - sys::swapByteOrder(x.fpu_reserved1); - } - - inline void swapStruct(x86_exception_state64_t &x) { - sys::swapByteOrder(x.trapno); - sys::swapByteOrder(x.cpu); - sys::swapByteOrder(x.err); - sys::swapByteOrder(x.faultvaddr); - } - - struct x86_state_hdr_t { - uint32_t flavor; - uint32_t count; - }; - - struct x86_thread_state_t { - x86_state_hdr_t tsh; - union { - x86_thread_state64_t ts64; - } uts; - }; - - struct x86_float_state_t { - x86_state_hdr_t fsh; - union { - x86_float_state64_t fs64; - } ufs; - }; - - struct x86_exception_state_t { - x86_state_hdr_t esh; - union { - x86_exception_state64_t es64; - } ues; - }; - - inline void swapStruct(x86_state_hdr_t &x) { - sys::swapByteOrder(x.flavor); - sys::swapByteOrder(x.count); - } - - enum X86ThreadFlavors { - x86_THREAD_STATE32 = 1, - x86_FLOAT_STATE32 = 2, - x86_EXCEPTION_STATE32 = 3, - x86_THREAD_STATE64 = 4, - x86_FLOAT_STATE64 = 5, - x86_EXCEPTION_STATE64 = 6, - x86_THREAD_STATE = 7, - x86_FLOAT_STATE = 8, - x86_EXCEPTION_STATE = 9, - x86_DEBUG_STATE32 = 10, - x86_DEBUG_STATE64 = 11, - x86_DEBUG_STATE = 12 - }; - - inline void swapStruct(x86_thread_state_t &x) { - swapStruct(x.tsh); - if (x.tsh.flavor == x86_THREAD_STATE64) - swapStruct(x.uts.ts64); - } - - inline void swapStruct(x86_float_state_t &x) { - swapStruct(x.fsh); - if (x.fsh.flavor == x86_FLOAT_STATE64) - swapStruct(x.ufs.fs64); - } - - inline void swapStruct(x86_exception_state_t &x) { - swapStruct(x.esh); - if (x.esh.flavor == x86_EXCEPTION_STATE64) - swapStruct(x.ues.es64); - } - - const uint32_t x86_THREAD_STATE64_COUNT = - sizeof(x86_thread_state64_t) / sizeof(uint32_t); - const uint32_t x86_FLOAT_STATE64_COUNT = - sizeof(x86_float_state64_t) / sizeof(uint32_t); - const uint32_t x86_EXCEPTION_STATE64_COUNT = - sizeof(x86_exception_state64_t) / sizeof(uint32_t); - - const uint32_t x86_THREAD_STATE_COUNT = - sizeof(x86_thread_state_t) / sizeof(uint32_t); - const uint32_t x86_FLOAT_STATE_COUNT = - sizeof(x86_float_state_t) / sizeof(uint32_t); - const uint32_t x86_EXCEPTION_STATE_COUNT = - sizeof(x86_exception_state_t) / sizeof(uint32_t); - - } // end namespace MachO -} // end namespace llvm - -#endif diff --git a/llvm/include/llvm/Support/TargetRegistry.h b/llvm/include/llvm/Support/TargetRegistry.h index 53bfcc21..d111741d 100644 --- a/llvm/include/llvm/Support/TargetRegistry.h +++ b/llvm/include/llvm/Support/TargetRegistry.h @@ -104,11 +104,6 @@ class Target { raw_pwrite_stream &OS, MCCodeEmitter *Emitter, bool RelaxAll); - typedef MCStreamer *(*MachOStreamerCtorTy)(MCContext &Ctx, MCAsmBackend &TAB, - raw_pwrite_stream &OS, - MCCodeEmitter *Emitter, - bool RelaxAll, - bool DWARFMustBeAtTheEnd); typedef MCTargetStreamer *(*NullTargetStreamerCtorTy)(MCStreamer &S); typedef MCTargetStreamer *(*AsmTargetStreamerCtorTy)( MCStreamer &S, formatted_raw_ostream &OS); @@ -345,16 +340,10 @@ class Target { const MCSubtargetInfo &STI, bool RelaxAll, bool DWARFMustBeAtTheEnd) const { MCStreamer *S; - switch (T.getObjectFormat()) { - default: - llvm_unreachable("Unknown object format"); - case Triple::ELF: - if (ELFStreamerCtorFn) - S = ELFStreamerCtorFn(T, Ctx, TAB, OS, Emitter, RelaxAll); - else - S = createELFStreamer(Ctx, TAB, OS, Emitter, RelaxAll); - break; - } + if (ELFStreamerCtorFn) + S = ELFStreamerCtorFn(T, Ctx, TAB, OS, Emitter, RelaxAll); + else + S = createELFStreamer(Ctx, TAB, OS, Emitter, RelaxAll); if (ObjectTargetStreamerCtorFn) ObjectTargetStreamerCtorFn(*S, STI); return S; diff --git a/llvm/lib/MC/MCAsmInfo.cpp b/llvm/lib/MC/MCAsmInfo.cpp index 36e10b3c..237ff13f 100644 --- a/llvm/lib/MC/MCAsmInfo.cpp +++ b/llvm/lib/MC/MCAsmInfo.cpp @@ -28,9 +28,6 @@ MCAsmInfo::MCAsmInfo() { IsLittleEndian = true; StackGrowsUp = false; - HasSubsectionsViaSymbols = false; - HasMachoZeroFillDirective = false; - HasMachoTBSSDirective = false; HasStaticCtorDtorReferenceInStaticMode = false; MaxInstLength = 4; MinInstAlignment = 1; @@ -74,7 +71,6 @@ MCAsmInfo::MCAsmInfo() { HasDotTypeDotSizeDirective = true; HasSingleParameterDotFile = true; HasIdentDirective = false; - HasNoDeadStrip = false; WeakDirective = "\t.weak\t"; WeakRefDirective = nullptr; HasWeakDefDirective = false; diff --git a/llvm/lib/MC/MCAsmInfoCOFF.cpp b/llvm/lib/MC/MCAsmInfoCOFF.cpp deleted file mode 100644 index d176d523..00000000 --- a/llvm/lib/MC/MCAsmInfoCOFF.cpp +++ /dev/null @@ -1,47 +0,0 @@ -//===-- MCAsmInfoCOFF.cpp - COFF asm properties -----------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines target asm properties related what form asm statements -// should take in general on COFF-based targets -// -//===----------------------------------------------------------------------===// - -#include "llvm/MC/MCAsmInfoCOFF.h" -using namespace llvm; - -MCAsmInfoCOFF::MCAsmInfoCOFF() { - // MingW 4.5 and later support .comm with log2 alignment, but .lcomm uses byte - // alignment. - COMMDirectiveAlignmentIsInBytes = false; - LCOMMDirectiveAlignmentType = LCOMM::ByteAlignment; - HasDotTypeDotSizeDirective = false; - HasSingleParameterDotFile = false; - WeakRefDirective = "\t.weak\t"; - HasLinkOnceDirective = true; - - // Doesn't support visibility: - HiddenVisibilityAttr = HiddenDeclarationVisibilityAttr = MCSA_Invalid; - ProtectedVisibilityAttr = MCSA_Invalid; - - // Set up DWARF directives - SupportsDebugInformation = true; - NeedsDwarfSectionOffsetDirective = true; - - UseIntegratedAssembler = true; - - // At least MSVC inline-asm does AShr. - UseLogicalShr = false; -} - -MCAsmInfoMicrosoft::MCAsmInfoMicrosoft() { -} - -MCAsmInfoGNUCOFF::MCAsmInfoGNUCOFF() { - -} diff --git a/llvm/lib/MC/MCAsmInfoDarwin.cpp b/llvm/lib/MC/MCAsmInfoDarwin.cpp deleted file mode 100644 index ae9486d3..00000000 --- a/llvm/lib/MC/MCAsmInfoDarwin.cpp +++ /dev/null @@ -1,96 +0,0 @@ -//===-- MCAsmInfoDarwin.cpp - Darwin asm properties -------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines target asm properties related what form asm statements -// should take in general on Darwin-based targets -// -//===----------------------------------------------------------------------===// - -#include "llvm/MC/MCAsmInfoDarwin.h" -#include "llvm/MC/MCContext.h" -#include "llvm/MC/MCExpr.h" -#include "llvm/MC/MCSectionMachO.h" -using namespace llvm; - -bool MCAsmInfoDarwin::isSectionAtomizableBySymbols( - const MCSection &Section) const { - const MCSectionMachO &SMO = static_cast(Section); - - // Sections holding 1 byte strings are atomized based on the data they - // contain. - // Sections holding 2 byte strings require symbols in order to be atomized. - // There is no dedicated section for 4 byte strings. - if (SMO.getType() == MachO::S_CSTRING_LITERALS) - return false; - - if (SMO.getSegmentName() == "__DATA" && SMO.getSectionName() == "__cfstring") - return false; - - if (SMO.getSegmentName() == "__DATA" && - SMO.getSectionName() == "__objc_classrefs") - return false; - - switch (SMO.getType()) { - default: - return true; - - // These sections are atomized at the element boundaries without using - // symbols. - case MachO::S_4BYTE_LITERALS: - case MachO::S_8BYTE_LITERALS: - case MachO::S_16BYTE_LITERALS: - case MachO::S_LITERAL_POINTERS: - case MachO::S_NON_LAZY_SYMBOL_POINTERS: - case MachO::S_LAZY_SYMBOL_POINTERS: - case MachO::S_MOD_INIT_FUNC_POINTERS: - case MachO::S_MOD_TERM_FUNC_POINTERS: - case MachO::S_INTERPOSING: - return false; - } -} - -MCAsmInfoDarwin::MCAsmInfoDarwin() { - // Common settings for all Darwin targets. - // Syntax: - LinkerPrivateGlobalPrefix = "l"; - HasSingleParameterDotFile = false; - HasSubsectionsViaSymbols = true; - - AlignmentIsInBytes = false; - COMMDirectiveAlignmentIsInBytes = false; - LCOMMDirectiveAlignmentType = LCOMM::Log2Alignment; - InlineAsmStart = " InlineAsm Start"; - InlineAsmEnd = " InlineAsm End"; - - // Directives: - HasWeakDefDirective = true; - HasWeakDefCanBeHiddenDirective = true; - WeakRefDirective = "\t.weak_reference "; - ZeroDirective = "\t.space\t"; // ".space N" emits N zeros. - HasMachoZeroFillDirective = true; // Uses .zerofill - HasMachoTBSSDirective = true; // Uses .tbss - HasStaticCtorDtorReferenceInStaticMode = true; - - // FIXME: Change this once MC is the system assembler. - HasAggressiveSymbolFolding = false; - - HiddenVisibilityAttr = MCSA_PrivateExtern; - HiddenDeclarationVisibilityAttr = MCSA_Invalid; - - // Doesn't support protected visibility. - ProtectedVisibilityAttr = MCSA_Invalid; - - HasDotTypeDotSizeDirective = false; - HasNoDeadStrip = true; - - DwarfUsesRelocationsAcrossSections = false; - - UseIntegratedAssembler = true; - SetDirectiveSuppressesReloc = true; -} diff --git a/llvm/lib/MC/MCContext.cpp b/llvm/lib/MC/MCContext.cpp index 9ff66e48..7016cff5 100644 --- a/llvm/lib/MC/MCContext.cpp +++ b/llvm/lib/MC/MCContext.cpp @@ -17,14 +17,9 @@ #include "llvm/MC/MCLabel.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCRegisterInfo.h" -#include "llvm/MC/MCSectionCOFF.h" #include "llvm/MC/MCSectionELF.h" -#include "llvm/MC/MCSectionMachO.h" #include "llvm/MC/MCStreamer.h" -#include "llvm/MC/MCSymbolCOFF.h" #include "llvm/MC/MCSymbolELF.h" -#include "llvm/MC/MCSymbolMachO.h" -#include "llvm/Support/COFF.h" #include "llvm/Support/ELF.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" @@ -71,9 +66,7 @@ MCContext::~MCContext() { void MCContext::reset() { // Call the destructors so the fragments are freed - COFFAllocator.DestroyAll(); ELFAllocator.DestroyAll(); - MachOAllocator.DestroyAll(); MCSubtargetAllocator.DestroyAll(); UsedNames.clear(); @@ -90,9 +83,7 @@ void MCContext::reset() { DwarfCompileUnitID = 0; CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0); - MachOUniquingMap.clear(); ELFUniquingMap.clear(); - COFFUniquingMap.clear(); NextID.clear(); AllowTemporaryLabels = true; @@ -162,12 +153,8 @@ MCSymbol *MCContext::createSymbolImpl(const StringMapEntry *Name, bool IsTemporary) { if (MOFI) { switch (MOFI->getObjectFileType()) { - case MCObjectFileInfo::IsCOFF: - return new (Name, *this) MCSymbolCOFF(Name, IsTemporary); case MCObjectFileInfo::IsELF: return new (Name, *this) MCSymbolELF(Name, IsTemporary); - case MCObjectFileInfo::IsMachO: - return new (Name, *this) MCSymbolMachO(Name, IsTemporary); } } return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name, @@ -267,35 +254,6 @@ MCSymbol *MCContext::lookupSymbol(const Twine &Name) const { // Section Management //===----------------------------------------------------------------------===// -MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section, - unsigned TypeAndAttributes, - unsigned Reserved2, SectionKind Kind, - const char *BeginSymName) { - - // We unique sections by their segment/section pair. The returned section - // may not have the same flags as the requested section, if so this should be - // diagnosed by the client as an error. - - // Form the name to look up. - SmallString<64> Name; - Name += Segment; - Name.push_back(','); - Name += Section; - - // Do the lookup, if we have a hit, return it. - MCSectionMachO *&Entry = MachOUniquingMap[Name]; - if (Entry) - return Entry; - - MCSymbol *Begin = nullptr; - if (BeginSymName) - Begin = createTempSymbol(BeginSymName, false); - - // Otherwise, return a new section. - return Entry = new (MachOAllocator.Allocate()) MCSectionMachO( - Segment, Section, TypeAndAttributes, Reserved2, Kind, Begin); -} - void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) { StringRef GroupName; if (const MCSymbol *Group = Section->getGroup()) @@ -379,66 +337,6 @@ MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) { return Result; } -MCSectionCOFF *MCContext::getCOFFSection(StringRef Section, - unsigned Characteristics, - SectionKind Kind, - StringRef COMDATSymName, int Selection, - const char *BeginSymName) { - MCSymbol *COMDATSymbol = nullptr; - if (!COMDATSymName.empty()) { - COMDATSymbol = getOrCreateSymbol(COMDATSymName); - COMDATSymName = COMDATSymbol->getName(); - } - - // Do the lookup, if we have a hit, return it. - COFFSectionKey T{Section, COMDATSymName, Selection}; - auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr)); - auto Iter = IterBool.first; - if (!IterBool.second) - return Iter->second; - - MCSymbol *Begin = nullptr; - if (BeginSymName) - Begin = createTempSymbol(BeginSymName, false); - - StringRef CachedName = Iter->first.SectionName; - MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF( - CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin); - - Iter->second = Result; - return Result; -} - -MCSectionCOFF *MCContext::getCOFFSection(StringRef Section, - unsigned Characteristics, - SectionKind Kind, - const char *BeginSymName) { - return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName); -} - -MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) { - COFFSectionKey T{Section, "", 0}; - auto Iter = COFFUniquingMap.find(T); - if (Iter == COFFUniquingMap.end()) - return nullptr; - return Iter->second; -} - -MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec, - const MCSymbol *KeySym) { - // Return the normal section if we don't have to be associative. - if (!KeySym) - return Sec; - - // Make an associative section with the same name and kind as the normal - // section. - unsigned Characteristics = - Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT; - return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(), - KeySym->getName(), - COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE); -} - MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) { return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI); } diff --git a/llvm/lib/MC/MCELFStreamer.cpp b/llvm/lib/MC/MCELFStreamer.cpp index 3445f021..d4930982 100644 --- a/llvm/lib/MC/MCELFStreamer.cpp +++ b/llvm/lib/MC/MCELFStreamer.cpp @@ -653,22 +653,6 @@ void MCELFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) { llvm_unreachable("ELF doesn't support this directive"); } -void MCELFStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) { - llvm_unreachable("ELF doesn't support this directive"); -} - -void MCELFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) { - llvm_unreachable("ELF doesn't support this directive"); -} - -void MCELFStreamer::EmitCOFFSymbolType(int Type) { - llvm_unreachable("ELF doesn't support this directive"); -} - -void MCELFStreamer::EndCOFFSymbolDef() { - llvm_unreachable("ELF doesn't support this directive"); -} - void MCELFStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) { llvm_unreachable("ELF doesn't support this directive"); diff --git a/llvm/lib/MC/MCExpr.cpp b/llvm/lib/MC/MCExpr.cpp index d3686f54..45bddba7 100644 --- a/llvm/lib/MC/MCExpr.cpp +++ b/llvm/lib/MC/MCExpr.cpp @@ -149,7 +149,6 @@ MCSymbolRefExpr::MCSymbolRefExpr(const MCSymbol *Symbol, VariantKind Kind, const MCAsmInfo *MAI) : MCExpr(MCExpr::SymbolRef), Kind(Kind), UseParensForSymbolVariant(MAI->useParensForSymbolVariant()), - HasSubsectionsViaSymbols(MAI->hasSubsectionsViaSymbols()), Symbol(Symbol) { assert(Symbol); } @@ -281,7 +280,6 @@ StringRef MCSymbolRefExpr::getVariantKindName(VariantKind Kind) { case VK_Mips_CALL_LO16: return "CALL_LO16"; case VK_Mips_PCREL_HI16: return "PCREL_HI16"; case VK_Mips_PCREL_LO16: return "PCREL_LO16"; - case VK_COFF_IMGREL32: return "IMGREL"; case VK_Hexagon_PCREL: return "PCREL"; case VK_Hexagon_LO16: return "LO16"; case VK_Hexagon_HI16: return "HI16"; @@ -322,7 +320,6 @@ MCSymbolRefExpr::getVariantKindForName(StringRef Name) { .Case("pageoff", VK_PAGEOFF) .Case("gotpage", VK_GOTPAGE) .Case("gotpageoff", VK_GOTPAGEOFF) - .Case("imgrel", VK_COFF_IMGREL32) .Case("secrel32", VK_SECREL) .Case("size", VK_SIZE) .Case("l", VK_PPC_LO) @@ -637,22 +634,9 @@ bool MCExpr::evaluateAsRelocatableImpl(MCValue &Res, const MCAssembler *Asm, // Evaluate recursively if this is a variable. if (Sym.isVariable() && SRE->getKind() == MCSymbolRefExpr::VK_None && canExpand(Sym, InSet)) { - bool IsMachO = SRE->hasSubsectionsViaSymbols(); if (Sym.getVariableValue()->evaluateAsRelocatableImpl( - Res, Asm, Layout, Fixup, Addrs, InSet || IsMachO)) { - if (!IsMachO) - return true; - - const MCSymbolRefExpr *A = Res.getSymA(); - const MCSymbolRefExpr *B = Res.getSymB(); - // FIXME: This is small hack. Given - // a = b + 4 - // .long a - // the OS X assembler will completely drop the 4. We should probably - // include it in the relocation or produce an error if that is not - // possible. - if (!A && !B) - return true; + Res, Asm, Layout, Fixup, Addrs, InSet)) { + return true; } } diff --git a/llvm/lib/MC/MCObjectFileInfo.cpp b/llvm/lib/MC/MCObjectFileInfo.cpp index 287b1b99..cd032206 100644 --- a/llvm/lib/MC/MCObjectFileInfo.cpp +++ b/llvm/lib/MC/MCObjectFileInfo.cpp @@ -13,257 +13,10 @@ #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCSection.h" -#include "llvm/MC/MCSectionCOFF.h" #include "llvm/MC/MCSectionELF.h" -#include "llvm/MC/MCSectionMachO.h" -#include "llvm/Support/COFF.h" using namespace llvm; -static bool useCompactUnwind(const Triple &T) { - // Only on darwin. - if (!T.isOSDarwin()) - return false; - - // aarch64 always has it. - if (T.getArch() == Triple::aarch64) - return true; - - // armv7k always has it. - if (T.isWatchABI()) - return true; - - // Use it on newer version of OS X. - if (T.isMacOSX() && !T.isMacOSXVersionLT(10, 6)) - return true; - - // And the iOS simulator. - if (T.isiOS() && - (T.getArch() == Triple::x86_64 || T.getArch() == Triple::x86)) - return true; - - return false; -} - -void MCObjectFileInfo::initMachOMCObjectFileInfo(Triple T) { - // MachO - SupportsWeakOmittedEHFrame = false; - - EHFrameSection = Ctx->getMachOSection( - "__TEXT", "__eh_frame", - MachO::S_COALESCED | MachO::S_ATTR_NO_TOC | - MachO::S_ATTR_STRIP_STATIC_SYMS | MachO::S_ATTR_LIVE_SUPPORT, - SectionKind::getReadOnly()); - - if (T.isOSDarwin() && T.getArch() == Triple::aarch64) - SupportsCompactUnwindWithoutEHFrame = true; - - if (T.isWatchABI()) - OmitDwarfIfHaveCompactUnwind = true; - - PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel - | dwarf::DW_EH_PE_sdata4; - LSDAEncoding = FDECFIEncoding = dwarf::DW_EH_PE_pcrel; - TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | - dwarf::DW_EH_PE_sdata4; - - // .comm doesn't support alignment before Leopard. - if (T.isMacOSX() && T.isMacOSXVersionLT(10, 5)) - CommDirectiveSupportsAlignment = false; - - TextSection // .text - = Ctx->getMachOSection("__TEXT", "__text", - MachO::S_ATTR_PURE_INSTRUCTIONS, - SectionKind::getText()); - DataSection // .data - = Ctx->getMachOSection("__DATA", "__data", 0, SectionKind::getData()); - - // BSSSection might not be expected initialized on msvc. - BSSSection = nullptr; - - TLSDataSection // .tdata - = Ctx->getMachOSection("__DATA", "__thread_data", - MachO::S_THREAD_LOCAL_REGULAR, - SectionKind::getData()); - TLSBSSSection // .tbss - = Ctx->getMachOSection("__DATA", "__thread_bss", - MachO::S_THREAD_LOCAL_ZEROFILL, - SectionKind::getThreadBSS()); - - // TODO: Verify datarel below. - TLSTLVSection // .tlv - = Ctx->getMachOSection("__DATA", "__thread_vars", - MachO::S_THREAD_LOCAL_VARIABLES, - SectionKind::getData()); - - TLSThreadInitSection = Ctx->getMachOSection( - "__DATA", "__thread_init", MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS, - SectionKind::getData()); - - CStringSection // .cstring - = Ctx->getMachOSection("__TEXT", "__cstring", - MachO::S_CSTRING_LITERALS, - SectionKind::getMergeable1ByteCString()); - UStringSection - = Ctx->getMachOSection("__TEXT","__ustring", 0, - SectionKind::getMergeable2ByteCString()); - FourByteConstantSection // .literal4 - = Ctx->getMachOSection("__TEXT", "__literal4", - MachO::S_4BYTE_LITERALS, - SectionKind::getMergeableConst4()); - EightByteConstantSection // .literal8 - = Ctx->getMachOSection("__TEXT", "__literal8", - MachO::S_8BYTE_LITERALS, - SectionKind::getMergeableConst8()); - - SixteenByteConstantSection // .literal16 - = Ctx->getMachOSection("__TEXT", "__literal16", - MachO::S_16BYTE_LITERALS, - SectionKind::getMergeableConst16()); - - ReadOnlySection // .const - = Ctx->getMachOSection("__TEXT", "__const", 0, - SectionKind::getReadOnly()); - - // If the target is not powerpc, map the coal sections to the non-coal - // sections. - // - // "__TEXT/__textcoal_nt" => section "__TEXT/__text" - // "__TEXT/__const_coal" => section "__TEXT/__const" - // "__DATA/__datacoal_nt" => section "__DATA/__data" - Triple::ArchType ArchTy = T.getArch(); - - if (ArchTy == Triple::ppc || ArchTy == Triple::ppc64) { - TextCoalSection - = Ctx->getMachOSection("__TEXT", "__textcoal_nt", - MachO::S_COALESCED | - MachO::S_ATTR_PURE_INSTRUCTIONS, - SectionKind::getText()); - ConstTextCoalSection - = Ctx->getMachOSection("__TEXT", "__const_coal", - MachO::S_COALESCED, - SectionKind::getReadOnly()); - DataCoalSection = Ctx->getMachOSection( - "__DATA", "__datacoal_nt", MachO::S_COALESCED, SectionKind::getData()); - } else { - TextCoalSection = TextSection; - ConstTextCoalSection = ReadOnlySection; - DataCoalSection = DataSection; - } - - ConstDataSection // .const_data - = Ctx->getMachOSection("__DATA", "__const", 0, - SectionKind::getReadOnlyWithRel()); - DataCommonSection - = Ctx->getMachOSection("__DATA","__common", - MachO::S_ZEROFILL, - SectionKind::getBSS()); - DataBSSSection - = Ctx->getMachOSection("__DATA","__bss", MachO::S_ZEROFILL, - SectionKind::getBSS()); - - - LazySymbolPointerSection - = Ctx->getMachOSection("__DATA", "__la_symbol_ptr", - MachO::S_LAZY_SYMBOL_POINTERS, - SectionKind::getMetadata()); - NonLazySymbolPointerSection - = Ctx->getMachOSection("__DATA", "__nl_symbol_ptr", - MachO::S_NON_LAZY_SYMBOL_POINTERS, - SectionKind::getMetadata()); - - // Exception Handling. - LSDASection = Ctx->getMachOSection("__TEXT", "__gcc_except_tab", 0, - SectionKind::getReadOnlyWithRel()); - - COFFDebugSymbolsSection = nullptr; - COFFDebugTypesSection = nullptr; - - if (useCompactUnwind(T)) { - CompactUnwindSection = - Ctx->getMachOSection("__LD", "__compact_unwind", MachO::S_ATTR_DEBUG, - SectionKind::getReadOnly()); - - if (T.getArch() == Triple::x86_64 || T.getArch() == Triple::x86) - CompactUnwindDwarfEHFrameOnly = 0x04000000; // UNWIND_X86_64_MODE_DWARF - else if (T.getArch() == Triple::aarch64) - CompactUnwindDwarfEHFrameOnly = 0x03000000; // UNWIND_ARM64_MODE_DWARF - else if (T.getArch() == Triple::arm || T.getArch() == Triple::thumb) - CompactUnwindDwarfEHFrameOnly = 0x04000000; // UNWIND_ARM_MODE_DWARF - } - - // Debug Information. - DwarfAccelNamesSection = - Ctx->getMachOSection("__DWARF", "__apple_names", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata(), "names_begin"); - DwarfAccelObjCSection = - Ctx->getMachOSection("__DWARF", "__apple_objc", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata(), "objc_begin"); - // 16 character section limit... - DwarfAccelNamespaceSection = - Ctx->getMachOSection("__DWARF", "__apple_namespac", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata(), "namespac_begin"); - DwarfAccelTypesSection = - Ctx->getMachOSection("__DWARF", "__apple_types", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata(), "types_begin"); - - DwarfAbbrevSection = - Ctx->getMachOSection("__DWARF", "__debug_abbrev", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata(), "section_abbrev"); - DwarfInfoSection = - Ctx->getMachOSection("__DWARF", "__debug_info", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata(), "section_info"); - DwarfLineSection = - Ctx->getMachOSection("__DWARF", "__debug_line", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata(), "section_line"); - DwarfFrameSection = - Ctx->getMachOSection("__DWARF", "__debug_frame", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata()); - DwarfPubNamesSection = - Ctx->getMachOSection("__DWARF", "__debug_pubnames", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata()); - DwarfPubTypesSection = - Ctx->getMachOSection("__DWARF", "__debug_pubtypes", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata()); - DwarfGnuPubNamesSection = - Ctx->getMachOSection("__DWARF", "__debug_gnu_pubn", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata()); - DwarfGnuPubTypesSection = - Ctx->getMachOSection("__DWARF", "__debug_gnu_pubt", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata()); - DwarfStrSection = - Ctx->getMachOSection("__DWARF", "__debug_str", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata(), "info_string"); - DwarfLocSection = - Ctx->getMachOSection("__DWARF", "__debug_loc", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata(), "section_debug_loc"); - DwarfARangesSection = - Ctx->getMachOSection("__DWARF", "__debug_aranges", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata()); - DwarfRangesSection = - Ctx->getMachOSection("__DWARF", "__debug_ranges", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata(), "debug_range"); - DwarfMacinfoSection = - Ctx->getMachOSection("__DWARF", "__debug_macinfo", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata(), "debug_macinfo"); - DwarfDebugInlineSection = - Ctx->getMachOSection("__DWARF", "__debug_inlined", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata()); - DwarfCUIndexSection = - Ctx->getMachOSection("__DWARF", "__debug_cu_index", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata()); - DwarfTUIndexSection = - Ctx->getMachOSection("__DWARF", "__debug_tu_index", MachO::S_ATTR_DEBUG, - SectionKind::getMetadata()); - StackMapSection = Ctx->getMachOSection("__LLVM_STACKMAPS", "__llvm_stackmaps", - 0, SectionKind::getMetadata()); - - FaultMapSection = Ctx->getMachOSection("__LLVM_FAULTMAPS", "__llvm_faultmaps", - 0, SectionKind::getMetadata()); - - TLSExtraDataSection = TLSTLVSection; -} - void MCObjectFileInfo::initELFMCObjectFileInfo(Triple T) { switch (T.getArch()) { case Triple::mips: @@ -397,9 +150,6 @@ void MCObjectFileInfo::initELFMCObjectFileInfo(Triple T) { LSDASection = Ctx->getELFSection(".gcc_except_table", ELF::SHT_PROGBITS, ELF::SHF_ALLOC); - COFFDebugSymbolsSection = nullptr; - COFFDebugTypesSection = nullptr; - // Debug Info Sections. DwarfAbbrevSection = Ctx->getELFSection(".debug_abbrev", ELF::SHT_PROGBITS, 0, "section_abbrev"); @@ -473,244 +223,6 @@ void MCObjectFileInfo::initELFMCObjectFileInfo(Triple T) { Ctx->getELFSection(".eh_frame", EHSectionType, EHSectionFlags); } -void MCObjectFileInfo::initCOFFMCObjectFileInfo(Triple T) { - EHFrameSection = Ctx->getCOFFSection( - ".eh_frame", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, - SectionKind::getData()); - - bool IsWoA = T.getArch() == Triple::arm || T.getArch() == Triple::thumb; - - CommDirectiveSupportsAlignment = true; - - // COFF - BSSSection = Ctx->getCOFFSection( - ".bss", COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, - SectionKind::getBSS()); - TextSection = Ctx->getCOFFSection( - ".text", - (IsWoA ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0) | - COFF::IMAGE_SCN_CNT_CODE | COFF::IMAGE_SCN_MEM_EXECUTE | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getText()); - DataSection = Ctx->getCOFFSection( - ".data", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ | - COFF::IMAGE_SCN_MEM_WRITE, - SectionKind::getData()); - ReadOnlySection = Ctx->getCOFFSection( - ".rdata", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ, - SectionKind::getReadOnly()); - - if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) { - StaticCtorSection = - Ctx->getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getReadOnly()); - StaticDtorSection = - Ctx->getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getReadOnly()); - } else { - StaticCtorSection = Ctx->getCOFFSection( - ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, - SectionKind::getData()); - StaticDtorSection = Ctx->getCOFFSection( - ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, - SectionKind::getData()); - } - - // FIXME: We're emitting LSDA info into a readonly section on COFF, even - // though it contains relocatable pointers. In PIC mode, this is probably a - // big runtime hit for C++ apps. Either the contents of the LSDA need to be - // adjusted or this should be a data section. - if (T.getArch() == Triple::x86_64) { - // On Windows 64 with SEH, the LSDA is emitted into the .xdata section - LSDASection = nullptr; - } else { - LSDASection = Ctx->getCOFFSection(".gcc_except_table", - COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getReadOnly()); - } - - // Debug info. - COFFDebugSymbolsSection = - Ctx->getCOFFSection(".debug$S", (COFF::IMAGE_SCN_MEM_DISCARDABLE | - COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ), - SectionKind::getMetadata()); - COFFDebugTypesSection = - Ctx->getCOFFSection(".debug$T", (COFF::IMAGE_SCN_MEM_DISCARDABLE | - COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ), - SectionKind::getMetadata()); - - DwarfAbbrevSection = Ctx->getCOFFSection( - ".debug_abbrev", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata(), "section_abbrev"); - DwarfInfoSection = Ctx->getCOFFSection( - ".debug_info", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata(), "section_info"); - DwarfLineSection = Ctx->getCOFFSection( - ".debug_line", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata(), "section_line"); - - DwarfFrameSection = Ctx->getCOFFSection( - ".debug_frame", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata()); - DwarfPubNamesSection = Ctx->getCOFFSection( - ".debug_pubnames", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata()); - DwarfPubTypesSection = Ctx->getCOFFSection( - ".debug_pubtypes", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata()); - DwarfGnuPubNamesSection = Ctx->getCOFFSection( - ".debug_gnu_pubnames", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata()); - DwarfGnuPubTypesSection = Ctx->getCOFFSection( - ".debug_gnu_pubtypes", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata()); - DwarfStrSection = Ctx->getCOFFSection( - ".debug_str", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata(), "info_string"); - DwarfLocSection = Ctx->getCOFFSection( - ".debug_loc", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata(), "section_debug_loc"); - DwarfARangesSection = Ctx->getCOFFSection( - ".debug_aranges", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata()); - DwarfRangesSection = Ctx->getCOFFSection( - ".debug_ranges", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata(), "debug_range"); - DwarfMacinfoSection = Ctx->getCOFFSection( - ".debug_macinfo", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata(), "debug_macinfo"); - DwarfInfoDWOSection = Ctx->getCOFFSection( - ".debug_info.dwo", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata(), "section_info_dwo"); - DwarfTypesDWOSection = Ctx->getCOFFSection( - ".debug_types.dwo", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata(), "section_types_dwo"); - DwarfAbbrevDWOSection = Ctx->getCOFFSection( - ".debug_abbrev.dwo", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata(), "section_abbrev_dwo"); - DwarfStrDWOSection = Ctx->getCOFFSection( - ".debug_str.dwo", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata(), "skel_string"); - DwarfLineDWOSection = Ctx->getCOFFSection( - ".debug_line.dwo", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata()); - DwarfLocDWOSection = Ctx->getCOFFSection( - ".debug_loc.dwo", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata(), "skel_loc"); - DwarfStrOffDWOSection = Ctx->getCOFFSection( - ".debug_str_offsets.dwo", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata()); - DwarfAddrSection = Ctx->getCOFFSection( - ".debug_addr", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata(), "addr_sec"); - DwarfCUIndexSection = Ctx->getCOFFSection( - ".debug_cu_index", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata()); - DwarfTUIndexSection = Ctx->getCOFFSection( - ".debug_tu_index", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata()); - DwarfAccelNamesSection = Ctx->getCOFFSection( - ".apple_names", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata(), "names_begin"); - DwarfAccelNamespaceSection = Ctx->getCOFFSection( - ".apple_namespaces", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata(), "namespac_begin"); - DwarfAccelTypesSection = Ctx->getCOFFSection( - ".apple_types", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata(), "types_begin"); - DwarfAccelObjCSection = Ctx->getCOFFSection( - ".apple_objc", - COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getMetadata(), "objc_begin"); - - DrectveSection = Ctx->getCOFFSection( - ".drectve", COFF::IMAGE_SCN_LNK_INFO | COFF::IMAGE_SCN_LNK_REMOVE, - SectionKind::getMetadata()); - - PDataSection = Ctx->getCOFFSection( - ".pdata", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ, - SectionKind::getData()); - - XDataSection = Ctx->getCOFFSection( - ".xdata", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ, - SectionKind::getData()); - - SXDataSection = Ctx->getCOFFSection(".sxdata", COFF::IMAGE_SCN_LNK_INFO, - SectionKind::getMetadata()); - - TLSDataSection = Ctx->getCOFFSection( - ".tls$", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ | - COFF::IMAGE_SCN_MEM_WRITE, - SectionKind::getData()); - - StackMapSection = Ctx->getCOFFSection(".llvm_stackmaps", - COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ, - SectionKind::getReadOnly()); -} - void MCObjectFileInfo::InitMCObjectFileInfo(const Triple &TheTriple, MCContext &ctx) { Ctx = &ctx; @@ -735,27 +247,8 @@ void MCObjectFileInfo::InitMCObjectFileInfo(const Triple &TheTriple, TT = TheTriple; - switch (TT.getObjectFormat()) { - case Triple::MachO: - Env = IsMachO; - initMachOMCObjectFileInfo(TT); - break; - case Triple::COFF: - if (!TT.isOSWindows()) - report_fatal_error( - "Cannot initialize MC for non-Windows COFF object files."); - - Env = IsCOFF; - initCOFFMCObjectFileInfo(TT); - break; - case Triple::ELF: - Env = IsELF; - initELFMCObjectFileInfo(TT); - break; - case Triple::UnknownObjectFormat: - report_fatal_error("Cannot initialize MC for unknown object file format."); - break; - } + Env = IsELF; + initELFMCObjectFileInfo(TT); } MCSection *MCObjectFileInfo::getDwarfTypesSection(uint64_t Hash) const { diff --git a/llvm/lib/MC/MCParser/AsmParser.cpp b/llvm/lib/MC/MCParser/AsmParser.cpp index fc63e533..8920821a 100644 --- a/llvm/lib/MC/MCParser/AsmParser.cpp +++ b/llvm/lib/MC/MCParser/AsmParser.cpp @@ -29,7 +29,6 @@ #include "llvm/MC/MCParser/MCParsedAsmOperand.h" #include "llvm/MC/MCParser/MCTargetAsmParser.h" #include "llvm/MC/MCRegisterInfo.h" -#include "llvm/MC/MCSectionMachO.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/MC/MCValue.h" @@ -176,9 +175,6 @@ class AsmParser : public MCAsmParser { /// AssemblerDialect. ~OU means unset value and use value provided by MAI. unsigned AssemblerDialect; - /// \brief is Darwin compatibility enabled? - bool IsDarwin; - /// \brief Are we parsing ms-style inline assembly? bool ParsingInlineAsm; @@ -533,9 +529,7 @@ class AsmParser : public MCAsmParser { namespace llvm { -extern MCAsmParserExtension *createDarwinAsmParser(); extern MCAsmParserExtension *createELFAsmParser(); -extern MCAsmParserExtension *createCOFFAsmParser(); } @@ -546,7 +540,7 @@ AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out, : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM), PlatformParser(nullptr), CurBuffer(SM.getMainFileID()), MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0), - AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false), + AssemblerDialect(~0U), ParsingInlineAsm(false), NasmDefaultRel(false) { // Save the old handler. SavedDiagHandler = SrcMgr.getDiagHandler(); @@ -556,17 +550,9 @@ AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out, Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); // Initialize the platform / file format parser. - PlatformParser.reset(createDarwinAsmParser()); - IsDarwin = true; + PlatformParser.reset(createELFAsmParser()); #if 0 switch (Ctx.getObjectFileInfo()->getObjectFileType()) { - case MCObjectFileInfo::IsCOFF: - PlatformParser.reset(createCOFFAsmParser()); - break; - case MCObjectFileInfo::IsMachO: - PlatformParser.reset(createDarwinAsmParser()); - IsDarwin = true; - break; case MCObjectFileInfo::IsELF: PlatformParser.reset(createELFAsmParser()); break; @@ -721,25 +707,6 @@ size_t AsmParser::Run(bool NoInitialTextSection, uint64_t Address, bool NoFinali TheCondState.Ignore != StartingCondState.Ignore) return TokError("unmatched .ifs or .elses"); - // Check to see that all assembler local symbols were actually defined. - // Targets that don't do subsections via symbols may not want this, though, - // so conservatively exclude them. Only do this if we're finalizing, though, - // as otherwise we won't necessarilly have seen everything yet. - if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) { - for (const auto &TableEntry : getContext().getSymbols()) { - MCSymbol *Sym = TableEntry.getValue(); - // Variable symbols may not be marked as defined, so check those - // explicitly. If we know it's a variable, we have a definition for - // the purposes of this check. - if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined()) - // FIXME: We would really like to refer back to where the symbol was - // first referenced for a source location. We need to add something - // to track that. Currently, we just point to the end of the file. - return Error(getLexer().getLoc(), "assembler local symbol '" + - Sym->getName() + "' not defined"); - } - } - // Finalize the output stream if there are no errors and if the client wants // us to. if (!KsError && !HadError && !NoFinalize) @@ -1171,84 +1138,6 @@ bool AsmParser::parseAbsoluteExpression(int64_t &Res) { return false; } -static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K, - MCBinaryExpr::Opcode &Kind, - bool ShouldUseLogicalShr) { - switch (K) { - default: - return 0; // not a binop. - - // Lowest Precedence: &&, || - case AsmToken::AmpAmp: - Kind = MCBinaryExpr::LAnd; - return 1; - case AsmToken::PipePipe: - Kind = MCBinaryExpr::LOr; - return 1; - - // Low Precedence: |, &, ^ - // - // FIXME: gas seems to support '!' as an infix operator? - case AsmToken::Pipe: - Kind = MCBinaryExpr::Or; - return 2; - case AsmToken::Caret: - Kind = MCBinaryExpr::Xor; - return 2; - case AsmToken::Amp: - Kind = MCBinaryExpr::And; - return 2; - - // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >= - case AsmToken::EqualEqual: - Kind = MCBinaryExpr::EQ; - return 3; - case AsmToken::ExclaimEqual: - case AsmToken::LessGreater: - Kind = MCBinaryExpr::NE; - return 3; - case AsmToken::Less: - Kind = MCBinaryExpr::LT; - return 3; - case AsmToken::LessEqual: - Kind = MCBinaryExpr::LTE; - return 3; - case AsmToken::Greater: - Kind = MCBinaryExpr::GT; - return 3; - case AsmToken::GreaterEqual: - Kind = MCBinaryExpr::GTE; - return 3; - - // Intermediate Precedence: <<, >> - case AsmToken::LessLess: - Kind = MCBinaryExpr::Shl; - return 4; - case AsmToken::GreaterGreater: - Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr; - return 4; - - // High Intermediate Precedence: +, - - case AsmToken::Plus: - Kind = MCBinaryExpr::Add; - return 5; - case AsmToken::Minus: - Kind = MCBinaryExpr::Sub; - return 5; - - // Highest Precedence: *, /, % - case AsmToken::Star: - Kind = MCBinaryExpr::Mul; - return 6; - case AsmToken::Slash: - Kind = MCBinaryExpr::Div; - return 6; - case AsmToken::Percent: - Kind = MCBinaryExpr::Mod; - return 6; - } -} - static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K, MCBinaryExpr::Opcode &Kind, bool ShouldUseLogicalShr) { @@ -1328,8 +1217,7 @@ static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K, unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K, MCBinaryExpr::Opcode &Kind) { bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr(); - return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr) - : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr); + return getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr); } /// \brief Parse all binary operators with precedence >= 'Precedence'. @@ -2048,7 +1936,7 @@ bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body, { unsigned NParameters = Parameters.size(); bool HasVararg = NParameters ? Parameters.back().Vararg : false; - if ((!IsDarwin || NParameters != 0) && NParameters != A.size()) + if ((NParameters != 0) && NParameters != A.size()) return Error(L, "Wrong number of arguments"); // A macro without parameters is handled differently on Darwin: @@ -2058,20 +1946,9 @@ bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body, std::size_t End = Body.size(), Pos = 0; for (; Pos != End; ++Pos) { // Check for a substitution or escape. - if (IsDarwin && !NParameters) { - // This macro has no parameters, look for $0, $1, etc. - if (Body[Pos] != '$' || Pos + 1 == End) - continue; - - char Next = Body[Pos + 1]; - if (Next == '$' || Next == 'n' || - isdigit(static_cast(Next))) - break; - } else { - // This macro has parameters, look for \foo, \bar, etc. - if (Body[Pos] == '\\' && Pos + 1 != End) - break; - } + // This macro has parameters, look for \foo, \bar, etc. + if (Body[Pos] == '\\' && Pos + 1 != End) + break; } // Add the prefix. @@ -2081,79 +1958,51 @@ bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body, if (Pos == End) break; - if (IsDarwin && !NParameters) { - switch (Body[Pos + 1]) { - // $$ => $ - case '$': - OS << '$'; - break; + unsigned I = Pos + 1; - // $n => number of arguments - case 'n': - OS << A.size(); - break; + // Check for the \@ pseudo-variable. + if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End) + ++I; + else + while (isIdentifierChar(Body[I]) && I + 1 != End) + ++I; - // $[0-9] => argument - default: { - // Missing arguments are ignored. - unsigned Index = Body[Pos + 1] - '0'; - if (Index >= A.size()) - break; + const char *Begin = Body.data() + Pos + 1; + StringRef Argument(Begin, I - (Pos + 1)); + unsigned Index = 0; - // Otherwise substitute with the token values, with spaces eliminated. - for (const AsmToken &Token : A[Index]) - OS << Token.getString(); - break; - } - } + if (Argument == "@") { + OS << NumOfMacroInstantiations; Pos += 2; } else { - unsigned I = Pos + 1; - - // Check for the \@ pseudo-variable. - if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End) - ++I; - else - while (isIdentifierChar(Body[I]) && I + 1 != End) - ++I; - - const char *Begin = Body.data() + Pos + 1; - StringRef Argument(Begin, I - (Pos + 1)); - unsigned Index = 0; + for (; Index < NParameters; ++Index) + if (Parameters[Index].Name == Argument) + break; - if (Argument == "@") { - OS << NumOfMacroInstantiations; - Pos += 2; + if (Index == NParameters) { + if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')') + Pos += 3; + else { + OS << '\\' << Argument; + Pos = I; + } } else { - for (; Index < NParameters; ++Index) - if (Parameters[Index].Name == Argument) - break; - - if (Index == NParameters) { - if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')') - Pos += 3; + bool VarargParameter = HasVararg && Index == (NParameters - 1); + for (const AsmToken &Token : A[Index]) + // We expect no quotes around the string's contents when + // parsing for varargs. + if (Token.getKind() != AsmToken::String || VarargParameter) + OS << Token.getString(); else { - OS << '\\' << Argument; - Pos = I; - } - } else { - bool VarargParameter = HasVararg && Index == (NParameters - 1); - for (const AsmToken &Token : A[Index]) - // We expect no quotes around the string's contents when - // parsing for varargs. - if (Token.getKind() != AsmToken::String || VarargParameter) - OS << Token.getString(); - else { - bool valid; - OS << Token.getStringContents(valid); - if (!valid) { - KsError = KS_ERR_ASM_MACRO_STR; - return true; - } + bool valid; + OS << Token.getStringContents(valid); + if (!valid) { + KsError = KS_ERR_ASM_MACRO_STR; + return true; } + } - Pos += 1 + Argument.size(); - } + Pos += 1 + Argument.size(); } } // Update the scan point. @@ -2228,8 +2077,7 @@ bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) { unsigned ParenLevel = 0; unsigned AddTokens = 0; - // Darwin doesn't use spaces to delmit arguments. - AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin); + AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, false); for (;;) { if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) { @@ -2247,18 +2095,16 @@ bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) { // Spaces can delimit parameters, but could also be part an expression. // If the token after a space is an operator, add the token and the next // one into this argument - if (!IsDarwin) { - if (isOperator(Lexer.getKind())) { - // Check to see whether the token is used as an operator, - // or part of an identifier - const char *NextChar = getTok().getEndLoc().getPointer(); - if (*NextChar == ' ') - AddTokens = 2; - } + if (isOperator(Lexer.getKind())) { + // Check to see whether the token is used as an operator, + // or part of an identifier + const char *NextChar = getTok().getEndLoc().getPointer(); + if (*NextChar == ' ') + AddTokens = 2; + } - if (!AddTokens && ParenLevel == 0) { - break; - } + if (!AddTokens && ParenLevel == 0) { + break; } } diff --git a/llvm/lib/MC/MCParser/CMakeLists.txt b/llvm/lib/MC/MCParser/CMakeLists.txt index 99fdd016..c66cebe4 100644 --- a/llvm/lib/MC/MCParser/CMakeLists.txt +++ b/llvm/lib/MC/MCParser/CMakeLists.txt @@ -1,7 +1,6 @@ add_llvm_library(LLVMMCParser AsmLexer.cpp AsmParser.cpp - COFFAsmParser.cpp DarwinAsmParser.cpp ELFAsmParser.cpp MCAsmLexer.cpp diff --git a/llvm/lib/MC/MCParser/COFFAsmParser.cpp b/llvm/lib/MC/MCParser/COFFAsmParser.cpp deleted file mode 100644 index 6e90435e..00000000 --- a/llvm/lib/MC/MCParser/COFFAsmParser.cpp +++ /dev/null @@ -1,802 +0,0 @@ -//===- COFFAsmParser.cpp - COFF Assembly Parser ---------------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "llvm/MC/MCParser/MCAsmParserExtension.h" -#include "llvm/ADT/StringSwitch.h" -#include "llvm/ADT/Twine.h" -#include "llvm/MC/MCAsmInfo.h" -#include "llvm/MC/MCContext.h" -#include "llvm/MC/MCExpr.h" -#include "llvm/MC/MCObjectFileInfo.h" -#include "llvm/MC/MCParser/MCAsmLexer.h" -#include "llvm/MC/MCParser/MCTargetAsmParser.h" -#include "llvm/MC/MCRegisterInfo.h" -#include "llvm/MC/MCSectionCOFF.h" -#include "llvm/MC/MCStreamer.h" -#include "llvm/Support/COFF.h" -using namespace llvm; - -namespace { - -class COFFAsmParser : public MCAsmParserExtension { - template - void addDirectiveHandler(StringRef Directive) { - MCAsmParser::ExtensionDirectiveHandler Handler = std::make_pair( - this, HandleDirective); - getParser().addDirectiveHandler(Directive, Handler); - } - - bool ParseSectionSwitch(StringRef Section, - unsigned Characteristics, - SectionKind Kind); - - bool ParseSectionSwitch(StringRef Section, unsigned Characteristics, - SectionKind Kind, StringRef COMDATSymName, - COFF::COMDATType Type); - - bool ParseSectionName(StringRef &SectionName); - bool ParseSectionFlags(StringRef FlagsString, unsigned* Flags); - - void Initialize(MCAsmParser &Parser) override { - // Call the base implementation. - MCAsmParserExtension::Initialize(Parser); - - addDirectiveHandler<&COFFAsmParser::ParseSectionDirectiveText>(".text"); - addDirectiveHandler<&COFFAsmParser::ParseSectionDirectiveData>(".data"); - addDirectiveHandler<&COFFAsmParser::ParseSectionDirectiveBSS>(".bss"); - addDirectiveHandler<&COFFAsmParser::ParseDirectiveSection>(".section"); - addDirectiveHandler<&COFFAsmParser::ParseDirectiveDef>(".def"); - addDirectiveHandler<&COFFAsmParser::ParseDirectiveScl>(".scl"); - addDirectiveHandler<&COFFAsmParser::ParseDirectiveType>(".type"); - addDirectiveHandler<&COFFAsmParser::ParseDirectiveEndef>(".endef"); - addDirectiveHandler<&COFFAsmParser::ParseDirectiveSecRel32>(".secrel32"); - addDirectiveHandler<&COFFAsmParser::ParseDirectiveSecIdx>(".secidx"); - addDirectiveHandler<&COFFAsmParser::ParseDirectiveSafeSEH>(".safeseh"); - addDirectiveHandler<&COFFAsmParser::ParseDirectiveLinkOnce>(".linkonce"); - - // Win64 EH directives. - addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveStartProc>( - ".seh_proc"); - addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveEndProc>( - ".seh_endproc"); - addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveStartChained>( - ".seh_startchained"); - addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveEndChained>( - ".seh_endchained"); - addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveHandler>( - ".seh_handler"); - addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveHandlerData>( - ".seh_handlerdata"); - addDirectiveHandler<&COFFAsmParser::ParseSEHDirectivePushReg>( - ".seh_pushreg"); - addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveSetFrame>( - ".seh_setframe"); - addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveAllocStack>( - ".seh_stackalloc"); - addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveSaveReg>( - ".seh_savereg"); - addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveSaveXMM>( - ".seh_savexmm"); - addDirectiveHandler<&COFFAsmParser::ParseSEHDirectivePushFrame>( - ".seh_pushframe"); - addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveEndProlog>( - ".seh_endprologue"); - addDirectiveHandler<&COFFAsmParser::ParseDirectiveSymbolAttribute>(".weak"); - } - - bool ParseSectionDirectiveText(StringRef, SMLoc) { - return ParseSectionSwitch(".text", - COFF::IMAGE_SCN_CNT_CODE - | COFF::IMAGE_SCN_MEM_EXECUTE - | COFF::IMAGE_SCN_MEM_READ, - SectionKind::getText()); - } - bool ParseSectionDirectiveData(StringRef, SMLoc) { - return ParseSectionSwitch(".data", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ | - COFF::IMAGE_SCN_MEM_WRITE, - SectionKind::getData()); - } - bool ParseSectionDirectiveBSS(StringRef, SMLoc) { - return ParseSectionSwitch(".bss", - COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA - | COFF::IMAGE_SCN_MEM_READ - | COFF::IMAGE_SCN_MEM_WRITE, - SectionKind::getBSS()); - } - - bool ParseDirectiveSection(StringRef, SMLoc); - bool ParseDirectiveDef(StringRef, SMLoc); - bool ParseDirectiveScl(StringRef, SMLoc); - bool ParseDirectiveType(StringRef, SMLoc); - bool ParseDirectiveEndef(StringRef, SMLoc); - bool ParseDirectiveSecRel32(StringRef, SMLoc); - bool ParseDirectiveSecIdx(StringRef, SMLoc); - bool ParseDirectiveSafeSEH(StringRef, SMLoc); - bool parseCOMDATType(COFF::COMDATType &Type); - bool ParseDirectiveLinkOnce(StringRef, SMLoc); - - // Win64 EH directives. - bool ParseSEHDirectiveStartProc(StringRef, SMLoc); - bool ParseSEHDirectiveEndProc(StringRef, SMLoc); - bool ParseSEHDirectiveStartChained(StringRef, SMLoc); - bool ParseSEHDirectiveEndChained(StringRef, SMLoc); - bool ParseSEHDirectiveHandler(StringRef, SMLoc); - bool ParseSEHDirectiveHandlerData(StringRef, SMLoc); - bool ParseSEHDirectivePushReg(StringRef, SMLoc); - bool ParseSEHDirectiveSetFrame(StringRef, SMLoc); - bool ParseSEHDirectiveAllocStack(StringRef, SMLoc); - bool ParseSEHDirectiveSaveReg(StringRef, SMLoc); - bool ParseSEHDirectiveSaveXMM(StringRef, SMLoc); - bool ParseSEHDirectivePushFrame(StringRef, SMLoc); - bool ParseSEHDirectiveEndProlog(StringRef, SMLoc); - - bool ParseAtUnwindOrAtExcept(bool &unwind, bool &except); - bool ParseSEHRegisterNumber(unsigned &RegNo); - bool ParseDirectiveSymbolAttribute(StringRef Directive, SMLoc); -public: - COFFAsmParser() {} -}; - -} // end annonomous namespace. - -static SectionKind computeSectionKind(unsigned Flags) { - if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE) - return SectionKind::getText(); - if (Flags & COFF::IMAGE_SCN_MEM_READ && - (Flags & COFF::IMAGE_SCN_MEM_WRITE) == 0) - return SectionKind::getReadOnly(); - return SectionKind::getData(); -} - -bool COFFAsmParser::ParseSectionFlags(StringRef FlagsString, unsigned* Flags) { - enum { - None = 0, - Alloc = 1 << 0, - Code = 1 << 1, - Load = 1 << 2, - InitData = 1 << 3, - Shared = 1 << 4, - NoLoad = 1 << 5, - NoRead = 1 << 6, - NoWrite = 1 << 7 - }; - - bool ReadOnlyRemoved = false; - unsigned SecFlags = None; - - for (char FlagChar : FlagsString) { - switch (FlagChar) { - case 'a': - // Ignored. - break; - - case 'b': // bss section - SecFlags |= Alloc; - if (SecFlags & InitData) - return TokError("conflicting section flags 'b' and 'd'."); - SecFlags &= ~Load; - break; - - case 'd': // data section - SecFlags |= InitData; - if (SecFlags & Alloc) - return TokError("conflicting section flags 'b' and 'd'."); - SecFlags &= ~NoWrite; - if ((SecFlags & NoLoad) == 0) - SecFlags |= Load; - break; - - case 'n': // section is not loaded - SecFlags |= NoLoad; - SecFlags &= ~Load; - break; - - case 'r': // read-only - ReadOnlyRemoved = false; - SecFlags |= NoWrite; - if ((SecFlags & Code) == 0) - SecFlags |= InitData; - if ((SecFlags & NoLoad) == 0) - SecFlags |= Load; - break; - - case 's': // shared section - SecFlags |= Shared | InitData; - SecFlags &= ~NoWrite; - if ((SecFlags & NoLoad) == 0) - SecFlags |= Load; - break; - - case 'w': // writable - SecFlags &= ~NoWrite; - ReadOnlyRemoved = true; - break; - - case 'x': // executable section - SecFlags |= Code; - if ((SecFlags & NoLoad) == 0) - SecFlags |= Load; - if (!ReadOnlyRemoved) - SecFlags |= NoWrite; - break; - - case 'y': // not readable - SecFlags |= NoRead | NoWrite; - break; - - default: - return TokError("unknown flag"); - } - } - - *Flags = 0; - - if (SecFlags == None) - SecFlags = InitData; - - if (SecFlags & Code) - *Flags |= COFF::IMAGE_SCN_CNT_CODE | COFF::IMAGE_SCN_MEM_EXECUTE; - if (SecFlags & InitData) - *Flags |= COFF::IMAGE_SCN_CNT_INITIALIZED_DATA; - if ((SecFlags & Alloc) && (SecFlags & Load) == 0) - *Flags |= COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA; - if (SecFlags & NoLoad) - *Flags |= COFF::IMAGE_SCN_LNK_REMOVE; - if ((SecFlags & NoRead) == 0) - *Flags |= COFF::IMAGE_SCN_MEM_READ; - if ((SecFlags & NoWrite) == 0) - *Flags |= COFF::IMAGE_SCN_MEM_WRITE; - if (SecFlags & Shared) - *Flags |= COFF::IMAGE_SCN_MEM_SHARED; - - return false; -} - -/// ParseDirectiveSymbolAttribute -/// ::= { ".weak", ... } [ identifier ( , identifier )* ] -bool COFFAsmParser::ParseDirectiveSymbolAttribute(StringRef Directive, SMLoc) { - MCSymbolAttr Attr = StringSwitch(Directive) - .Case(".weak", MCSA_Weak) - .Default(MCSA_Invalid); - assert(Attr != MCSA_Invalid && "unexpected symbol attribute directive!"); - if (getLexer().isNot(AsmToken::EndOfStatement)) { - for (;;) { - StringRef Name; - - if (getParser().parseIdentifier(Name)) - return TokError("expected identifier in directive"); - - MCSymbol *Sym = getContext().getOrCreateSymbol(Name); - - getStreamer().EmitSymbolAttribute(Sym, Attr); - - if (getLexer().is(AsmToken::EndOfStatement)) - break; - - if (getLexer().isNot(AsmToken::Comma)) - return TokError("unexpected token in directive"); - Lex(); - } - } - - Lex(); - return false; -} - -bool COFFAsmParser::ParseSectionSwitch(StringRef Section, - unsigned Characteristics, - SectionKind Kind) { - return ParseSectionSwitch(Section, Characteristics, Kind, "", (COFF::COMDATType)0); -} - -bool COFFAsmParser::ParseSectionSwitch(StringRef Section, - unsigned Characteristics, - SectionKind Kind, - StringRef COMDATSymName, - COFF::COMDATType Type) { - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in section switching directive"); - Lex(); - - getStreamer().SwitchSection(getContext().getCOFFSection( - Section, Characteristics, Kind, COMDATSymName, Type)); - - return false; -} - -bool COFFAsmParser::ParseSectionName(StringRef &SectionName) { - if (!getLexer().is(AsmToken::Identifier)) - return true; - - SectionName = getTok().getIdentifier(); - Lex(); - return false; -} - -// .section name [, "flags"] [, identifier [ identifier ], identifier] -// -// Supported flags: -// a: Ignored. -// b: BSS section (uninitialized data) -// d: data section (initialized data) -// n: Discardable section -// r: Readable section -// s: Shared section -// w: Writable section -// x: Executable section -// y: Not-readable section (clears 'r') -// -// Subsections are not supported. -bool COFFAsmParser::ParseDirectiveSection(StringRef, SMLoc) -{ - StringRef SectionName; - - if (ParseSectionName(SectionName)) - return TokError("expected identifier in directive"); - - unsigned Flags = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | - COFF::IMAGE_SCN_MEM_READ | - COFF::IMAGE_SCN_MEM_WRITE; - - if (getLexer().is(AsmToken::Comma)) { - Lex(); - - if (getLexer().isNot(AsmToken::String)) - return TokError("expected string in directive"); - - bool valid; - StringRef FlagsStr = getTok().getStringContents(valid); - if (!valid) - return true; - - Lex(); - - if (ParseSectionFlags(FlagsStr, &Flags)) - return true; - } - - COFF::COMDATType Type = (COFF::COMDATType)0; - StringRef COMDATSymName; - if (getLexer().is(AsmToken::Comma)) { - Type = COFF::IMAGE_COMDAT_SELECT_ANY; - Lex(); - - Flags |= COFF::IMAGE_SCN_LNK_COMDAT; - - if (!getLexer().is(AsmToken::Identifier)) - return TokError("expected comdat type such as 'discard' or 'largest' " - "after protection bits"); - - if (parseCOMDATType(Type)) - return true; - - if (getLexer().isNot(AsmToken::Comma)) - return TokError("expected comma in directive"); - Lex(); - - if (getParser().parseIdentifier(COMDATSymName)) - return TokError("expected identifier in directive"); - } - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in directive"); - - SectionKind Kind = computeSectionKind(Flags); - if (Kind.isText()) { - const Triple &T = getContext().getObjectFileInfo()->getTargetTriple(); - if (T.getArch() == Triple::arm || T.getArch() == Triple::thumb) - Flags |= COFF::IMAGE_SCN_MEM_16BIT; - } - ParseSectionSwitch(SectionName, Flags, Kind, COMDATSymName, Type); - return false; -} - -bool COFFAsmParser::ParseDirectiveDef(StringRef, SMLoc) { - StringRef SymbolName; - - if (getParser().parseIdentifier(SymbolName)) - return TokError("expected identifier in directive"); - - MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName); - - getStreamer().BeginCOFFSymbolDef(Sym); - - Lex(); - return false; -} - -bool COFFAsmParser::ParseDirectiveScl(StringRef, SMLoc) { - int64_t SymbolStorageClass; - if (getParser().parseAbsoluteExpression(SymbolStorageClass)) - return true; - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in directive"); - - Lex(); - getStreamer().EmitCOFFSymbolStorageClass(SymbolStorageClass); - return false; -} - -bool COFFAsmParser::ParseDirectiveType(StringRef, SMLoc) { - int64_t Type; - if (getParser().parseAbsoluteExpression(Type)) - return true; - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in directive"); - - Lex(); - getStreamer().EmitCOFFSymbolType(Type); - return false; -} - -bool COFFAsmParser::ParseDirectiveEndef(StringRef, SMLoc) { - Lex(); - getStreamer().EndCOFFSymbolDef(); - return false; -} - -bool COFFAsmParser::ParseDirectiveSecRel32(StringRef, SMLoc) { - StringRef SymbolID; - if (getParser().parseIdentifier(SymbolID)) - return TokError("expected identifier in directive"); - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in directive"); - - MCSymbol *Symbol = getContext().getOrCreateSymbol(SymbolID); - - Lex(); - getStreamer().EmitCOFFSecRel32(Symbol); - return false; -} - -bool COFFAsmParser::ParseDirectiveSafeSEH(StringRef, SMLoc) { - StringRef SymbolID; - if (getParser().parseIdentifier(SymbolID)) - return TokError("expected identifier in directive"); - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in directive"); - - MCSymbol *Symbol = getContext().getOrCreateSymbol(SymbolID); - - Lex(); - getStreamer().EmitCOFFSafeSEH(Symbol); - return false; -} - -bool COFFAsmParser::ParseDirectiveSecIdx(StringRef, SMLoc) { - StringRef SymbolID; - if (getParser().parseIdentifier(SymbolID)) - return TokError("expected identifier in directive"); - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in directive"); - - MCSymbol *Symbol = getContext().getOrCreateSymbol(SymbolID); - - Lex(); - getStreamer().EmitCOFFSectionIndex(Symbol); - return false; -} - -/// ::= [ identifier ] -bool COFFAsmParser::parseCOMDATType(COFF::COMDATType &Type) { - StringRef TypeId = getTok().getIdentifier(); - - Type = StringSwitch(TypeId) - .Case("one_only", COFF::IMAGE_COMDAT_SELECT_NODUPLICATES) - .Case("discard", COFF::IMAGE_COMDAT_SELECT_ANY) - .Case("same_size", COFF::IMAGE_COMDAT_SELECT_SAME_SIZE) - .Case("same_contents", COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH) - .Case("associative", COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) - .Case("largest", COFF::IMAGE_COMDAT_SELECT_LARGEST) - .Case("newest", COFF::IMAGE_COMDAT_SELECT_NEWEST) - .Default((COFF::COMDATType)0); - - if (Type == 0) - return TokError(Twine("unrecognized COMDAT type '" + TypeId + "'")); - - Lex(); - - return false; -} - -/// ParseDirectiveLinkOnce -/// ::= .linkonce [ identifier ] -bool COFFAsmParser::ParseDirectiveLinkOnce(StringRef, SMLoc Loc) { - COFF::COMDATType Type = COFF::IMAGE_COMDAT_SELECT_ANY; - if (getLexer().is(AsmToken::Identifier)) - if (parseCOMDATType(Type)) - return true; - - const MCSectionCOFF *Current = static_cast( - getStreamer().getCurrentSection().first); - - if (Type == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) - return Error(Loc, "cannot make section associative with .linkonce"); - - if (Current->getCharacteristics() & COFF::IMAGE_SCN_LNK_COMDAT) - return Error(Loc, Twine("section '") + Current->getSectionName() + - "' is already linkonce"); - - Current->setSelection(Type); - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in directive"); - - return false; -} - -bool COFFAsmParser::ParseSEHDirectiveStartProc(StringRef, SMLoc) { - StringRef SymbolID; - if (getParser().parseIdentifier(SymbolID)) - return true; - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in directive"); - - MCSymbol *Symbol = getContext().getOrCreateSymbol(SymbolID); - - Lex(); - getStreamer().EmitWinCFIStartProc(Symbol); - return false; -} - -bool COFFAsmParser::ParseSEHDirectiveEndProc(StringRef, SMLoc) { - Lex(); - getStreamer().EmitWinCFIEndProc(); - return false; -} - -bool COFFAsmParser::ParseSEHDirectiveStartChained(StringRef, SMLoc) { - Lex(); - getStreamer().EmitWinCFIStartChained(); - return false; -} - -bool COFFAsmParser::ParseSEHDirectiveEndChained(StringRef, SMLoc) { - Lex(); - getStreamer().EmitWinCFIEndChained(); - return false; -} - -bool COFFAsmParser::ParseSEHDirectiveHandler(StringRef, SMLoc) { - StringRef SymbolID; - if (getParser().parseIdentifier(SymbolID)) - return true; - - if (getLexer().isNot(AsmToken::Comma)) - return TokError("you must specify one or both of @unwind or @except"); - Lex(); - bool unwind = false, except = false; - if (ParseAtUnwindOrAtExcept(unwind, except)) - return true; - if (getLexer().is(AsmToken::Comma)) { - Lex(); - if (ParseAtUnwindOrAtExcept(unwind, except)) - return true; - } - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in directive"); - - MCSymbol *handler = getContext().getOrCreateSymbol(SymbolID); - - Lex(); - getStreamer().EmitWinEHHandler(handler, unwind, except); - return false; -} - -bool COFFAsmParser::ParseSEHDirectiveHandlerData(StringRef, SMLoc) { - Lex(); - getStreamer().EmitWinEHHandlerData(); - return false; -} - -bool COFFAsmParser::ParseSEHDirectivePushReg(StringRef, SMLoc L) { - unsigned Reg = 0; - if (ParseSEHRegisterNumber(Reg)) - return true; - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in directive"); - - Lex(); - getStreamer().EmitWinCFIPushReg(Reg); - return false; -} - -bool COFFAsmParser::ParseSEHDirectiveSetFrame(StringRef, SMLoc L) { - unsigned Reg = 0; - int64_t Off; - if (ParseSEHRegisterNumber(Reg)) - return true; - if (getLexer().isNot(AsmToken::Comma)) - return TokError("you must specify a stack pointer offset"); - - Lex(); - SMLoc startLoc = getLexer().getLoc(); - if (getParser().parseAbsoluteExpression(Off)) - return true; - - if (Off & 0x0F) - return Error(startLoc, "offset is not a multiple of 16"); - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in directive"); - - Lex(); - getStreamer().EmitWinCFISetFrame(Reg, Off); - return false; -} - -bool COFFAsmParser::ParseSEHDirectiveAllocStack(StringRef, SMLoc) { - int64_t Size; - SMLoc startLoc = getLexer().getLoc(); - if (getParser().parseAbsoluteExpression(Size)) - return true; - - if (Size & 7) - return Error(startLoc, "size is not a multiple of 8"); - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in directive"); - - Lex(); - getStreamer().EmitWinCFIAllocStack(Size); - return false; -} - -bool COFFAsmParser::ParseSEHDirectiveSaveReg(StringRef, SMLoc L) { - unsigned Reg = 0; - int64_t Off; - if (ParseSEHRegisterNumber(Reg)) - return true; - if (getLexer().isNot(AsmToken::Comma)) - return TokError("you must specify an offset on the stack"); - - Lex(); - SMLoc startLoc = getLexer().getLoc(); - if (getParser().parseAbsoluteExpression(Off)) - return true; - - if (Off & 7) - return Error(startLoc, "size is not a multiple of 8"); - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in directive"); - - Lex(); - // FIXME: Err on %xmm* registers - getStreamer().EmitWinCFISaveReg(Reg, Off); - return false; -} - -// FIXME: This method is inherently x86-specific. It should really be in the -// x86 backend. -bool COFFAsmParser::ParseSEHDirectiveSaveXMM(StringRef, SMLoc L) { - unsigned Reg = 0; - int64_t Off; - if (ParseSEHRegisterNumber(Reg)) - return true; - if (getLexer().isNot(AsmToken::Comma)) - return TokError("you must specify an offset on the stack"); - - Lex(); - SMLoc startLoc = getLexer().getLoc(); - if (getParser().parseAbsoluteExpression(Off)) - return true; - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in directive"); - - if (Off & 0x0F) - return Error(startLoc, "offset is not a multiple of 16"); - - Lex(); - // FIXME: Err on non-%xmm* registers - getStreamer().EmitWinCFISaveXMM(Reg, Off); - return false; -} - -bool COFFAsmParser::ParseSEHDirectivePushFrame(StringRef, SMLoc) { - bool Code = false; - StringRef CodeID; - if (getLexer().is(AsmToken::At)) { - SMLoc startLoc = getLexer().getLoc(); - Lex(); - if (!getParser().parseIdentifier(CodeID)) { - if (CodeID != "code") - return Error(startLoc, "expected @code"); - Code = true; - } - } - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in directive"); - - Lex(); - getStreamer().EmitWinCFIPushFrame(Code); - return false; -} - -bool COFFAsmParser::ParseSEHDirectiveEndProlog(StringRef, SMLoc) { - Lex(); - getStreamer().EmitWinCFIEndProlog(); - return false; -} - -bool COFFAsmParser::ParseAtUnwindOrAtExcept(bool &unwind, bool &except) { - StringRef identifier; - if (getLexer().isNot(AsmToken::At)) - return TokError("a handler attribute must begin with '@'"); - SMLoc startLoc = getLexer().getLoc(); - Lex(); - if (getParser().parseIdentifier(identifier)) - return Error(startLoc, "expected @unwind or @except"); - if (identifier == "unwind") - unwind = true; - else if (identifier == "except") - except = true; - else - return Error(startLoc, "expected @unwind or @except"); - return false; -} - -bool COFFAsmParser::ParseSEHRegisterNumber(unsigned &RegNo) { - SMLoc startLoc = getLexer().getLoc(); - if (getLexer().is(AsmToken::Percent)) { - const MCRegisterInfo *MRI = getContext().getRegisterInfo(); - SMLoc endLoc; - unsigned LLVMRegNo; - unsigned int ErrorCode; - if (getParser().getTargetParser().ParseRegister(LLVMRegNo,startLoc,endLoc, ErrorCode)) - return true; - -#if 0 - // FIXME: TargetAsmInfo::getCalleeSavedRegs() commits a serious layering - // violation so this validation code is disabled. - - // Check that this is a non-volatile register. - const unsigned *NVRegs = TAI.getCalleeSavedRegs(); - unsigned i; - for (i = 0; NVRegs[i] != 0; ++i) - if (NVRegs[i] == LLVMRegNo) - break; - if (NVRegs[i] == 0) - return Error(startLoc, "expected non-volatile register"); -#endif - - int SEHRegNo = MRI->getSEHRegNum(LLVMRegNo); - if (SEHRegNo < 0) - return Error(startLoc,"register can't be represented in SEH unwind info"); - RegNo = SEHRegNo; - } - else { - int64_t n; - if (getParser().parseAbsoluteExpression(n)) - return true; - if (n > 15) - return Error(startLoc, "register number is too high"); - RegNo = n; - } - - return false; -} - -namespace llvm { - -MCAsmParserExtension *createCOFFAsmParser() { - return new COFFAsmParser; -} - -} diff --git a/llvm/lib/MC/MCParser/DarwinAsmParser.cpp b/llvm/lib/MC/MCParser/DarwinAsmParser.cpp deleted file mode 100644 index 73e068a3..00000000 --- a/llvm/lib/MC/MCParser/DarwinAsmParser.cpp +++ /dev/null @@ -1,967 +0,0 @@ -//===- DarwinAsmParser.cpp - Darwin (Mach-O) Assembly Parser --------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "llvm/MC/MCParser/MCAsmParserExtension.h" -#include "llvm/ADT/STLExtras.h" -#include "llvm/ADT/StringRef.h" -#include "llvm/ADT/StringSwitch.h" -#include "llvm/ADT/Triple.h" -#include "llvm/ADT/Twine.h" -#include "llvm/MC/MCContext.h" -#include "llvm/MC/MCObjectFileInfo.h" -#include "llvm/MC/MCParser/MCAsmLexer.h" -#include "llvm/MC/MCParser/MCAsmParser.h" -#include "llvm/MC/MCSectionMachO.h" -#include "llvm/MC/MCStreamer.h" -#include "llvm/MC/MCSymbol.h" -#include "llvm/Support/FileSystem.h" -#include "llvm/Support/MemoryBuffer.h" -#include "llvm/Support/SourceMgr.h" -using namespace llvm; - -namespace { - -/// \brief Implementation of directive handling which is shared across all -/// Darwin targets. -class DarwinAsmParser : public MCAsmParserExtension { - template - void addDirectiveHandler(StringRef Directive) { - MCAsmParser::ExtensionDirectiveHandler Handler = std::make_pair( - this, HandleDirective); - getParser().addDirectiveHandler(Directive, Handler); - } - - bool parseSectionSwitch(const char *Segment, const char *Section, - unsigned TAA = 0, unsigned ImplicitAlign = 0, - unsigned StubSize = 0); - - SMLoc LastVersionMinDirective; - -public: - DarwinAsmParser() {} - - void Initialize(MCAsmParser &Parser) override { - // Call the base implementation. - this->MCAsmParserExtension::Initialize(Parser); - - addDirectiveHandler<&DarwinAsmParser::parseDirectiveDesc>(".desc"); - addDirectiveHandler<&DarwinAsmParser::parseDirectiveIndirectSymbol>( - ".indirect_symbol"); - addDirectiveHandler<&DarwinAsmParser::parseDirectiveLsym>(".lsym"); - addDirectiveHandler<&DarwinAsmParser::parseDirectiveSubsectionsViaSymbols>( - ".subsections_via_symbols"); - addDirectiveHandler<&DarwinAsmParser::parseDirectiveDumpOrLoad>(".dump"); - addDirectiveHandler<&DarwinAsmParser::parseDirectiveDumpOrLoad>(".load"); - addDirectiveHandler<&DarwinAsmParser::parseDirectiveSection>(".section"); - addDirectiveHandler<&DarwinAsmParser::parseDirectivePushSection>( - ".pushsection"); - addDirectiveHandler<&DarwinAsmParser::parseDirectivePopSection>( - ".popsection"); - addDirectiveHandler<&DarwinAsmParser::parseDirectivePrevious>(".previous"); - addDirectiveHandler<&DarwinAsmParser::parseDirectiveSecureLogUnique>( - ".secure_log_unique"); - addDirectiveHandler<&DarwinAsmParser::parseDirectiveSecureLogReset>( - ".secure_log_reset"); - addDirectiveHandler<&DarwinAsmParser::parseDirectiveTBSS>(".tbss"); - addDirectiveHandler<&DarwinAsmParser::parseDirectiveZerofill>(".zerofill"); - - addDirectiveHandler<&DarwinAsmParser::parseDirectiveDataRegion>( - ".data_region"); - addDirectiveHandler<&DarwinAsmParser::parseDirectiveDataRegionEnd>( - ".end_data_region"); - - // Special section directives. - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveBss>(".bss"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveConst>(".const"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveConstData>( - ".const_data"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveConstructor>( - ".constructor"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveCString>( - ".cstring"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveData>(".data"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveDestructor>( - ".destructor"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveDyld>(".dyld"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveFVMLibInit0>( - ".fvmlib_init0"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveFVMLibInit1>( - ".fvmlib_init1"); - addDirectiveHandler< - &DarwinAsmParser::parseSectionDirectiveLazySymbolPointers>( - ".lazy_symbol_pointer"); - addDirectiveHandler<&DarwinAsmParser::parseDirectiveLinkerOption>( - ".linker_option"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveLiteral16>( - ".literal16"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveLiteral4>( - ".literal4"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveLiteral8>( - ".literal8"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveModInitFunc>( - ".mod_init_func"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveModTermFunc>( - ".mod_term_func"); - addDirectiveHandler< - &DarwinAsmParser::parseSectionDirectiveNonLazySymbolPointers>( - ".non_lazy_symbol_pointer"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCCatClsMeth>( - ".objc_cat_cls_meth"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCCatInstMeth>( - ".objc_cat_inst_meth"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCCategory>( - ".objc_category"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClass>( - ".objc_class"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClassNames>( - ".objc_class_names"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClassVars>( - ".objc_class_vars"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClsMeth>( - ".objc_cls_meth"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClsRefs>( - ".objc_cls_refs"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCInstMeth>( - ".objc_inst_meth"); - addDirectiveHandler< - &DarwinAsmParser::parseSectionDirectiveObjCInstanceVars>( - ".objc_instance_vars"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCMessageRefs>( - ".objc_message_refs"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCMetaClass>( - ".objc_meta_class"); - addDirectiveHandler< - &DarwinAsmParser::parseSectionDirectiveObjCMethVarNames>( - ".objc_meth_var_names"); - addDirectiveHandler< - &DarwinAsmParser::parseSectionDirectiveObjCMethVarTypes>( - ".objc_meth_var_types"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCModuleInfo>( - ".objc_module_info"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCProtocol>( - ".objc_protocol"); - addDirectiveHandler< - &DarwinAsmParser::parseSectionDirectiveObjCSelectorStrs>( - ".objc_selector_strs"); - addDirectiveHandler< - &DarwinAsmParser::parseSectionDirectiveObjCStringObject>( - ".objc_string_object"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCSymbols>( - ".objc_symbols"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectivePICSymbolStub>( - ".picsymbol_stub"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveStaticConst>( - ".static_const"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveStaticData>( - ".static_data"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveSymbolStub>( - ".symbol_stub"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveTData>(".tdata"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveText>(".text"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveThreadInitFunc>( - ".thread_init_func"); - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveTLV>(".tlv"); - - addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveIdent>(".ident"); - addDirectiveHandler<&DarwinAsmParser::parseVersionMin>( - ".watchos_version_min"); - addDirectiveHandler<&DarwinAsmParser::parseVersionMin>(".tvos_version_min"); - addDirectiveHandler<&DarwinAsmParser::parseVersionMin>(".ios_version_min"); - addDirectiveHandler<&DarwinAsmParser::parseVersionMin>( - ".macosx_version_min"); - - LastVersionMinDirective = SMLoc(); - } - - bool parseDirectiveDesc(StringRef, SMLoc); - bool parseDirectiveIndirectSymbol(StringRef, SMLoc); - bool parseDirectiveDumpOrLoad(StringRef, SMLoc); - bool parseDirectiveLsym(StringRef, SMLoc); - bool parseDirectiveLinkerOption(StringRef, SMLoc); - bool parseDirectiveSection(StringRef, SMLoc); - bool parseDirectivePushSection(StringRef, SMLoc); - bool parseDirectivePopSection(StringRef, SMLoc); - bool parseDirectivePrevious(StringRef, SMLoc); - bool parseDirectiveSecureLogReset(StringRef, SMLoc); - bool parseDirectiveSecureLogUnique(StringRef, SMLoc); - bool parseDirectiveSubsectionsViaSymbols(StringRef, SMLoc); - bool parseDirectiveTBSS(StringRef, SMLoc); - bool parseDirectiveZerofill(StringRef, SMLoc); - bool parseDirectiveDataRegion(StringRef, SMLoc); - bool parseDirectiveDataRegionEnd(StringRef, SMLoc); - - // Named Section Directive - bool parseSectionDirectiveBss(StringRef, SMLoc) { - return parseSectionSwitch("__DATA", "__bss"); - } - - bool parseSectionDirectiveConst(StringRef, SMLoc) { - return parseSectionSwitch("__TEXT", "__const"); - } - bool parseSectionDirectiveStaticConst(StringRef, SMLoc) { - return parseSectionSwitch("__TEXT", "__static_const"); - } - bool parseSectionDirectiveCString(StringRef, SMLoc) { - return parseSectionSwitch("__TEXT","__cstring", - MachO::S_CSTRING_LITERALS); - } - bool parseSectionDirectiveLiteral4(StringRef, SMLoc) { - return parseSectionSwitch("__TEXT", "__literal4", - MachO::S_4BYTE_LITERALS, 4); - } - bool parseSectionDirectiveLiteral8(StringRef, SMLoc) { - return parseSectionSwitch("__TEXT", "__literal8", - MachO::S_8BYTE_LITERALS, 8); - } - bool parseSectionDirectiveLiteral16(StringRef, SMLoc) { - return parseSectionSwitch("__TEXT","__literal16", - MachO::S_16BYTE_LITERALS, 16); - } - bool parseSectionDirectiveConstructor(StringRef, SMLoc) { - return parseSectionSwitch("__TEXT","__constructor"); - } - bool parseSectionDirectiveDestructor(StringRef, SMLoc) { - return parseSectionSwitch("__TEXT","__destructor"); - } - bool parseSectionDirectiveFVMLibInit0(StringRef, SMLoc) { - return parseSectionSwitch("__TEXT","__fvmlib_init0"); - } - bool parseSectionDirectiveFVMLibInit1(StringRef, SMLoc) { - return parseSectionSwitch("__TEXT","__fvmlib_init1"); - } - bool parseSectionDirectiveSymbolStub(StringRef, SMLoc) { - return parseSectionSwitch("__TEXT","__symbol_stub", - MachO::S_SYMBOL_STUBS | - MachO::S_ATTR_PURE_INSTRUCTIONS, - // FIXME: Different on PPC and ARM. - 0, 16); - } - bool parseSectionDirectivePICSymbolStub(StringRef, SMLoc) { - return parseSectionSwitch("__TEXT","__picsymbol_stub", - MachO::S_SYMBOL_STUBS | - MachO::S_ATTR_PURE_INSTRUCTIONS, 0, 26); - } - bool parseSectionDirectiveData(StringRef, SMLoc) { - return parseSectionSwitch("__DATA", "__data"); - } - bool parseSectionDirectiveStaticData(StringRef, SMLoc) { - return parseSectionSwitch("__DATA", "__static_data"); - } - bool parseSectionDirectiveNonLazySymbolPointers(StringRef, SMLoc) { - return parseSectionSwitch("__DATA", "__nl_symbol_ptr", - MachO::S_NON_LAZY_SYMBOL_POINTERS, 4); - } - bool parseSectionDirectiveLazySymbolPointers(StringRef, SMLoc) { - return parseSectionSwitch("__DATA", "__la_symbol_ptr", - MachO::S_LAZY_SYMBOL_POINTERS, 4); - } - bool parseSectionDirectiveDyld(StringRef, SMLoc) { - return parseSectionSwitch("__DATA", "__dyld"); - } - bool parseSectionDirectiveModInitFunc(StringRef, SMLoc) { - return parseSectionSwitch("__DATA", "__mod_init_func", - MachO::S_MOD_INIT_FUNC_POINTERS, 4); - } - bool parseSectionDirectiveModTermFunc(StringRef, SMLoc) { - return parseSectionSwitch("__DATA", "__mod_term_func", - MachO::S_MOD_TERM_FUNC_POINTERS, 4); - } - bool parseSectionDirectiveConstData(StringRef, SMLoc) { - return parseSectionSwitch("__DATA", "__const"); - } - bool parseSectionDirectiveObjCClass(StringRef, SMLoc) { - return parseSectionSwitch("__OBJC", "__class", - MachO::S_ATTR_NO_DEAD_STRIP); - } - bool parseSectionDirectiveObjCMetaClass(StringRef, SMLoc) { - return parseSectionSwitch("__OBJC", "__meta_class", - MachO::S_ATTR_NO_DEAD_STRIP); - } - bool parseSectionDirectiveObjCCatClsMeth(StringRef, SMLoc) { - return parseSectionSwitch("__OBJC", "__cat_cls_meth", - MachO::S_ATTR_NO_DEAD_STRIP); - } - bool parseSectionDirectiveObjCCatInstMeth(StringRef, SMLoc) { - return parseSectionSwitch("__OBJC", "__cat_inst_meth", - MachO::S_ATTR_NO_DEAD_STRIP); - } - bool parseSectionDirectiveObjCProtocol(StringRef, SMLoc) { - return parseSectionSwitch("__OBJC", "__protocol", - MachO::S_ATTR_NO_DEAD_STRIP); - } - bool parseSectionDirectiveObjCStringObject(StringRef, SMLoc) { - return parseSectionSwitch("__OBJC", "__string_object", - MachO::S_ATTR_NO_DEAD_STRIP); - } - bool parseSectionDirectiveObjCClsMeth(StringRef, SMLoc) { - return parseSectionSwitch("__OBJC", "__cls_meth", - MachO::S_ATTR_NO_DEAD_STRIP); - } - bool parseSectionDirectiveObjCInstMeth(StringRef, SMLoc) { - return parseSectionSwitch("__OBJC", "__inst_meth", - MachO::S_ATTR_NO_DEAD_STRIP); - } - bool parseSectionDirectiveObjCClsRefs(StringRef, SMLoc) { - return parseSectionSwitch("__OBJC", "__cls_refs", - MachO::S_ATTR_NO_DEAD_STRIP | - MachO::S_LITERAL_POINTERS, 4); - } - bool parseSectionDirectiveObjCMessageRefs(StringRef, SMLoc) { - return parseSectionSwitch("__OBJC", "__message_refs", - MachO::S_ATTR_NO_DEAD_STRIP | - MachO::S_LITERAL_POINTERS, 4); - } - bool parseSectionDirectiveObjCSymbols(StringRef, SMLoc) { - return parseSectionSwitch("__OBJC", "__symbols", - MachO::S_ATTR_NO_DEAD_STRIP); - } - bool parseSectionDirectiveObjCCategory(StringRef, SMLoc) { - return parseSectionSwitch("__OBJC", "__category", - MachO::S_ATTR_NO_DEAD_STRIP); - } - bool parseSectionDirectiveObjCClassVars(StringRef, SMLoc) { - return parseSectionSwitch("__OBJC", "__class_vars", - MachO::S_ATTR_NO_DEAD_STRIP); - } - bool parseSectionDirectiveObjCInstanceVars(StringRef, SMLoc) { - return parseSectionSwitch("__OBJC", "__instance_vars", - MachO::S_ATTR_NO_DEAD_STRIP); - } - bool parseSectionDirectiveObjCModuleInfo(StringRef, SMLoc) { - return parseSectionSwitch("__OBJC", "__module_info", - MachO::S_ATTR_NO_DEAD_STRIP); - } - bool parseSectionDirectiveObjCClassNames(StringRef, SMLoc) { - return parseSectionSwitch("__TEXT", "__cstring", - MachO::S_CSTRING_LITERALS); - } - bool parseSectionDirectiveObjCMethVarTypes(StringRef, SMLoc) { - return parseSectionSwitch("__TEXT", "__cstring", - MachO::S_CSTRING_LITERALS); - } - bool parseSectionDirectiveObjCMethVarNames(StringRef, SMLoc) { - return parseSectionSwitch("__TEXT", "__cstring", - MachO::S_CSTRING_LITERALS); - } - bool parseSectionDirectiveObjCSelectorStrs(StringRef, SMLoc) { - return parseSectionSwitch("__OBJC", "__selector_strs", - MachO::S_CSTRING_LITERALS); - } - bool parseSectionDirectiveTData(StringRef, SMLoc) { - return parseSectionSwitch("__DATA", "__thread_data", - MachO::S_THREAD_LOCAL_REGULAR); - } - bool parseSectionDirectiveText(StringRef, SMLoc) { - return parseSectionSwitch("__TEXT", "__text", - MachO::S_ATTR_PURE_INSTRUCTIONS); - } - bool parseSectionDirectiveTLV(StringRef, SMLoc) { - return parseSectionSwitch("__DATA", "__thread_vars", - MachO::S_THREAD_LOCAL_VARIABLES); - } - bool parseSectionDirectiveIdent(StringRef, SMLoc) { - // Darwin silently ignores the .ident directive. - getParser().eatToEndOfStatement(); - return false; - } - bool parseSectionDirectiveThreadInitFunc(StringRef, SMLoc) { - return parseSectionSwitch("__DATA", "__thread_init", - MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS); - } - bool parseVersionMin(StringRef, SMLoc); - -}; - -} // end anonymous namespace - -bool DarwinAsmParser::parseSectionSwitch(const char *Segment, - const char *Section, - unsigned TAA, unsigned Align, - unsigned StubSize) { - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in section switching directive"); - Lex(); - - // FIXME: Arch specific. - bool isText = TAA & MachO::S_ATTR_PURE_INSTRUCTIONS; - getStreamer().SwitchSection(getContext().getMachOSection( - Segment, Section, TAA, StubSize, - isText ? SectionKind::getText() : SectionKind::getData())); - - // Set the implicit alignment, if any. - // - // FIXME: This isn't really what 'as' does; I think it just uses the implicit - // alignment on the section (e.g., if one manually inserts bytes into the - // section, then just issuing the section switch directive will not realign - // the section. However, this is arguably more reasonable behavior, and there - // is no good reason for someone to intentionally emit incorrectly sized - // values into the implicitly aligned sections. - if (Align) - getStreamer().EmitValueToAlignment(Align); - - return false; -} - -/// parseDirectiveDesc -/// ::= .desc identifier , expression -bool DarwinAsmParser::parseDirectiveDesc(StringRef, SMLoc) { - StringRef Name; - if (getParser().parseIdentifier(Name)) - return TokError("expected identifier in directive"); - - // Handle the identifier as the key symbol. - MCSymbol *Sym = getContext().getOrCreateSymbol(Name); - - if (getLexer().isNot(AsmToken::Comma)) - return TokError("unexpected token in '.desc' directive"); - Lex(); - - int64_t DescValue; - if (getParser().parseAbsoluteExpression(DescValue)) - return true; - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in '.desc' directive"); - - Lex(); - - // Set the n_desc field of this Symbol to this DescValue - getStreamer().EmitSymbolDesc(Sym, DescValue); - - return false; -} - -/// parseDirectiveIndirectSymbol -/// ::= .indirect_symbol identifier -bool DarwinAsmParser::parseDirectiveIndirectSymbol(StringRef, SMLoc Loc) { - const MCSectionMachO *Current = static_cast( - getStreamer().getCurrentSection().first); - MachO::SectionType SectionType = Current->getType(); - if (SectionType != MachO::S_NON_LAZY_SYMBOL_POINTERS && - SectionType != MachO::S_LAZY_SYMBOL_POINTERS && - SectionType != MachO::S_SYMBOL_STUBS) - return Error(Loc, "indirect symbol not in a symbol pointer or stub " - "section"); - - StringRef Name; - if (getParser().parseIdentifier(Name)) - return TokError("expected identifier in .indirect_symbol directive"); - - MCSymbol *Sym = getContext().getOrCreateSymbol(Name); - - // Assembler local symbols don't make any sense here. Complain loudly. - if (Sym->isTemporary()) - return TokError("non-local symbol required in directive"); - - if (!getStreamer().EmitSymbolAttribute(Sym, MCSA_IndirectSymbol)) - return TokError("unable to emit indirect symbol attribute for: " + Name); - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in '.indirect_symbol' directive"); - - Lex(); - - return false; -} - -/// parseDirectiveDumpOrLoad -/// ::= ( .dump | .load ) "filename" -bool DarwinAsmParser::parseDirectiveDumpOrLoad(StringRef Directive, - SMLoc IDLoc) { - bool IsDump = Directive == ".dump"; - if (getLexer().isNot(AsmToken::String)) - return TokError("expected string in '.dump' or '.load' directive"); - - Lex(); - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in '.dump' or '.load' directive"); - - Lex(); - - // FIXME: If/when .dump and .load are implemented they will be done in the - // the assembly parser and not have any need for an MCStreamer API. - if (IsDump) - return Warning(IDLoc, "ignoring directive .dump for now"); - else - return Warning(IDLoc, "ignoring directive .load for now"); -} - -/// ParseDirectiveLinkerOption -/// ::= .linker_option "string" ( , "string" )* -bool DarwinAsmParser::parseDirectiveLinkerOption(StringRef IDVal, SMLoc) { - SmallVector Args; - for (;;) { - if (getLexer().isNot(AsmToken::String)) - return TokError("expected string in '" + Twine(IDVal) + "' directive"); - - std::string Data; - if (getParser().parseEscapedString(Data)) - return true; - - Args.push_back(Data); - - Lex(); - if (getLexer().is(AsmToken::EndOfStatement)) - break; - - if (getLexer().isNot(AsmToken::Comma)) - return TokError("unexpected token in '" + Twine(IDVal) + "' directive"); - Lex(); - } - - getStreamer().EmitLinkerOptions(Args); - return false; -} - -/// parseDirectiveLsym -/// ::= .lsym identifier , expression -bool DarwinAsmParser::parseDirectiveLsym(StringRef, SMLoc) { - StringRef Name; - if (getParser().parseIdentifier(Name)) - return TokError("expected identifier in directive"); - - // Handle the identifier as the key symbol. - MCSymbol *Sym = getContext().getOrCreateSymbol(Name); - - if (getLexer().isNot(AsmToken::Comma)) - return TokError("unexpected token in '.lsym' directive"); - Lex(); - - const MCExpr *Value; - if (getParser().parseExpression(Value)) - return true; - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in '.lsym' directive"); - - Lex(); - - // We don't currently support this directive. - // - // FIXME: Diagnostic location! - (void) Sym; - return TokError("directive '.lsym' is unsupported"); -} - -/// parseDirectiveSection: -/// ::= .section identifier (',' identifier)* -bool DarwinAsmParser::parseDirectiveSection(StringRef, SMLoc) { - SMLoc Loc = getLexer().getLoc(); - - StringRef SectionName; - if (getParser().parseIdentifier(SectionName)) - return Error(Loc, "expected identifier after '.section' directive"); - - // Verify there is a following comma. - if (!getLexer().is(AsmToken::Comma)) - return TokError("unexpected token in '.section' directive"); - - std::string SectionSpec = SectionName; - SectionSpec += ","; - - // Add all the tokens until the end of the line, ParseSectionSpecifier will - // handle this. - StringRef EOL = getLexer().LexUntilEndOfStatement(); - SectionSpec.append(EOL.begin(), EOL.end()); - - Lex(); - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in '.section' directive"); - Lex(); - - - StringRef Segment, Section; - unsigned StubSize; - unsigned TAA; - bool TAAParsed; - std::string ErrorStr = - MCSectionMachO::ParseSectionSpecifier(SectionSpec, Segment, Section, - TAA, TAAParsed, StubSize); - - if (!ErrorStr.empty()) - return Error(Loc, ErrorStr.c_str()); - - // Issue a warning if the target is not powerpc and Section is a *coal* section. - Triple TT = getParser().getContext().getObjectFileInfo()->getTargetTriple(); - Triple::ArchType ArchTy = TT.getArch(); - - if (ArchTy != Triple::ppc && ArchTy != Triple::ppc64) { - StringRef NonCoalSection = StringSwitch(Section) - .Case("__textcoal_nt", "__text") - .Case("__const_coal", "__const") - .Case("__datacoal_nt", "__data") - .Default(Section); - - if (!Section.equals(NonCoalSection)) { - StringRef SectionVal(Loc.getPointer()); - size_t B = SectionVal.find(',') + 1, E = SectionVal.find(',', B); - SMLoc BLoc = SMLoc::getFromPointer(SectionVal.data() + B); - SMLoc ELoc = SMLoc::getFromPointer(SectionVal.data() + E); - getParser().Warning(Loc, "section \"" + Section + "\" is deprecated", - SMRange(BLoc, ELoc)); - getParser().Note(Loc, "change section name to \"" + NonCoalSection + - "\"", SMRange(BLoc, ELoc)); - } - } - - // FIXME: Arch specific. - bool isText = Segment == "__TEXT"; // FIXME: Hack. - getStreamer().SwitchSection(getContext().getMachOSection( - Segment, Section, TAA, StubSize, - isText ? SectionKind::getText() : SectionKind::getData())); - return false; -} - -/// ParseDirectivePushSection: -/// ::= .pushsection identifier (',' identifier)* -bool DarwinAsmParser::parseDirectivePushSection(StringRef S, SMLoc Loc) { - getStreamer().PushSection(); - - if (parseDirectiveSection(S, Loc)) { - getStreamer().PopSection(); - return true; - } - - return false; -} - -/// ParseDirectivePopSection: -/// ::= .popsection -bool DarwinAsmParser::parseDirectivePopSection(StringRef, SMLoc) { - if (!getStreamer().PopSection()) - return TokError(".popsection without corresponding .pushsection"); - return false; -} - -/// ParseDirectivePrevious: -/// ::= .previous -bool DarwinAsmParser::parseDirectivePrevious(StringRef DirName, SMLoc) { - MCSectionSubPair PreviousSection = getStreamer().getPreviousSection(); - if (!PreviousSection.first) - return TokError(".previous without corresponding .section"); - getStreamer().SwitchSection(PreviousSection.first, PreviousSection.second); - return false; -} - -/// ParseDirectiveSecureLogUnique -/// ::= .secure_log_unique ... message ... -bool DarwinAsmParser::parseDirectiveSecureLogUnique(StringRef, SMLoc IDLoc) { - StringRef LogMessage = getParser().parseStringToEndOfStatement(); - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in '.secure_log_unique' directive"); - - if (getContext().getSecureLogUsed()) - return Error(IDLoc, ".secure_log_unique specified multiple times"); - - // Get the secure log path. - const char *SecureLogFile = getContext().getSecureLogFile(); - if (!SecureLogFile) - return Error(IDLoc, ".secure_log_unique used but AS_SECURE_LOG_FILE " - "environment variable unset."); - - // Open the secure log file if we haven't already. - raw_fd_ostream *OS = getContext().getSecureLog(); - if (!OS) { - std::error_code EC; - auto NewOS = llvm::make_unique( - SecureLogFile, EC, sys::fs::F_Append | sys::fs::F_Text); - if (EC) - return Error(IDLoc, Twine("can't open secure log file: ") + - SecureLogFile + " (" + EC.message() + ")"); - OS = NewOS.get(); - getContext().setSecureLog(std::move(NewOS)); - } - - // Write the message. - unsigned CurBuf = getSourceManager().FindBufferContainingLoc(IDLoc); - *OS << getSourceManager().getBufferInfo(CurBuf).Buffer->getBufferIdentifier() - << ":" << getSourceManager().FindLineNumber(IDLoc, CurBuf) << ":" - << LogMessage + "\n"; - - getContext().setSecureLogUsed(true); - - return false; -} - -/// ParseDirectiveSecureLogReset -/// ::= .secure_log_reset -bool DarwinAsmParser::parseDirectiveSecureLogReset(StringRef, SMLoc IDLoc) { - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in '.secure_log_reset' directive"); - - Lex(); - - getContext().setSecureLogUsed(false); - - return false; -} - -/// parseDirectiveSubsectionsViaSymbols -/// ::= .subsections_via_symbols -bool DarwinAsmParser::parseDirectiveSubsectionsViaSymbols(StringRef, SMLoc) { - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in '.subsections_via_symbols' directive"); - - Lex(); - - getStreamer().EmitAssemblerFlag(MCAF_SubsectionsViaSymbols); - - return false; -} - -/// ParseDirectiveTBSS -/// ::= .tbss identifier, size, align -bool DarwinAsmParser::parseDirectiveTBSS(StringRef, SMLoc) { - SMLoc IDLoc = getLexer().getLoc(); - StringRef Name; - if (getParser().parseIdentifier(Name)) - return TokError("expected identifier in directive"); - - // Handle the identifier as the key symbol. - MCSymbol *Sym = getContext().getOrCreateSymbol(Name); - - if (getLexer().isNot(AsmToken::Comma)) - return TokError("unexpected token in directive"); - Lex(); - - int64_t Size; - SMLoc SizeLoc = getLexer().getLoc(); - if (getParser().parseAbsoluteExpression(Size)) - return true; - - int64_t Pow2Alignment = 0; - SMLoc Pow2AlignmentLoc; - if (getLexer().is(AsmToken::Comma)) { - Lex(); - Pow2AlignmentLoc = getLexer().getLoc(); - if (getParser().parseAbsoluteExpression(Pow2Alignment)) - return true; - } - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in '.tbss' directive"); - - Lex(); - - if (Size < 0) - return Error(SizeLoc, "invalid '.tbss' directive size, can't be less than" - "zero"); - - // FIXME: Diagnose overflow. - if (Pow2Alignment < 0) - return Error(Pow2AlignmentLoc, "invalid '.tbss' alignment, can't be less" - "than zero"); - - if (!Sym->isUndefined()) - return Error(IDLoc, "invalid symbol redefinition"); - - getStreamer().EmitTBSSSymbol(getContext().getMachOSection( - "__DATA", "__thread_bss", - MachO::S_THREAD_LOCAL_ZEROFILL, - 0, SectionKind::getThreadBSS()), - Sym, Size, 1 << Pow2Alignment); - - return false; -} - -/// ParseDirectiveZerofill -/// ::= .zerofill segname , sectname [, identifier , size_expression [ -/// , align_expression ]] -bool DarwinAsmParser::parseDirectiveZerofill(StringRef, SMLoc) { - StringRef Segment; - if (getParser().parseIdentifier(Segment)) - return TokError("expected segment name after '.zerofill' directive"); - - if (getLexer().isNot(AsmToken::Comma)) - return TokError("unexpected token in directive"); - Lex(); - - StringRef Section; - if (getParser().parseIdentifier(Section)) - return TokError("expected section name after comma in '.zerofill' " - "directive"); - - // If this is the end of the line all that was wanted was to create the - // the section but with no symbol. - if (getLexer().is(AsmToken::EndOfStatement)) { - // Create the zerofill section but no symbol - getStreamer().EmitZerofill(getContext().getMachOSection( - Segment, Section, MachO::S_ZEROFILL, - 0, SectionKind::getBSS())); - return false; - } - - if (getLexer().isNot(AsmToken::Comma)) - return TokError("unexpected token in directive"); - Lex(); - - SMLoc IDLoc = getLexer().getLoc(); - StringRef IDStr; - if (getParser().parseIdentifier(IDStr)) - return TokError("expected identifier in directive"); - - // handle the identifier as the key symbol. - MCSymbol *Sym = getContext().getOrCreateSymbol(IDStr); - - if (getLexer().isNot(AsmToken::Comma)) - return TokError("unexpected token in directive"); - Lex(); - - int64_t Size; - SMLoc SizeLoc = getLexer().getLoc(); - if (getParser().parseAbsoluteExpression(Size)) - return true; - - int64_t Pow2Alignment = 0; - SMLoc Pow2AlignmentLoc; - if (getLexer().is(AsmToken::Comma)) { - Lex(); - Pow2AlignmentLoc = getLexer().getLoc(); - if (getParser().parseAbsoluteExpression(Pow2Alignment)) - return true; - } - - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in '.zerofill' directive"); - - Lex(); - - if (Size < 0) - return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less " - "than zero"); - - // NOTE: The alignment in the directive is a power of 2 value, the assembler - // may internally end up wanting an alignment in bytes. - // FIXME: Diagnose overflow. - if (Pow2Alignment < 0) - return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, " - "can't be less than zero"); - - if (!Sym->isUndefined()) - return Error(IDLoc, "invalid symbol redefinition"); - - // Create the zerofill Symbol with Size and Pow2Alignment - // - // FIXME: Arch specific. - getStreamer().EmitZerofill(getContext().getMachOSection( - Segment, Section, MachO::S_ZEROFILL, - 0, SectionKind::getBSS()), - Sym, Size, 1 << Pow2Alignment); - - return false; -} - -/// ParseDirectiveDataRegion -/// ::= .data_region [ ( jt8 | jt16 | jt32 ) ] -bool DarwinAsmParser::parseDirectiveDataRegion(StringRef, SMLoc) { - if (getLexer().is(AsmToken::EndOfStatement)) { - Lex(); - getStreamer().EmitDataRegion(MCDR_DataRegion); - return false; - } - StringRef RegionType; - SMLoc Loc = getParser().getTok().getLoc(); - if (getParser().parseIdentifier(RegionType)) - return TokError("expected region type after '.data_region' directive"); - int Kind = StringSwitch(RegionType) - .Case("jt8", MCDR_DataRegionJT8) - .Case("jt16", MCDR_DataRegionJT16) - .Case("jt32", MCDR_DataRegionJT32) - .Default(-1); - if (Kind == -1) - return Error(Loc, "unknown region type in '.data_region' directive"); - Lex(); - - getStreamer().EmitDataRegion((MCDataRegionType)Kind); - return false; -} - -/// ParseDirectiveDataRegionEnd -/// ::= .end_data_region -bool DarwinAsmParser::parseDirectiveDataRegionEnd(StringRef, SMLoc) { - if (getLexer().isNot(AsmToken::EndOfStatement)) - return TokError("unexpected token in '.end_data_region' directive"); - - Lex(); - getStreamer().EmitDataRegion(MCDR_DataRegionEnd); - return false; -} - -/// parseVersionMin -/// ::= .ios_version_min major,minor[,update] -/// ::= .macosx_version_min major,minor[,update] -bool DarwinAsmParser::parseVersionMin(StringRef Directive, SMLoc Loc) { - int64_t Major = 0, Minor = 0, Update = 0; - int Kind = StringSwitch(Directive) - .Case(".watchos_version_min", MCVM_WatchOSVersionMin) - .Case(".tvos_version_min", MCVM_TvOSVersionMin) - .Case(".ios_version_min", MCVM_IOSVersionMin) - .Case(".macosx_version_min", MCVM_OSXVersionMin); - // Get the major version number. - if (getLexer().isNot(AsmToken::Integer)) - return TokError("invalid OS major version number"); - Major = getLexer().getTok().getIntVal(); - if (Major > 65535 || Major <= 0) - return TokError("invalid OS major version number"); - Lex(); - if (getLexer().isNot(AsmToken::Comma)) - return TokError("minor OS version number required, comma expected"); - Lex(); - // Get the minor version number. - if (getLexer().isNot(AsmToken::Integer)) - return TokError("invalid OS minor version number"); - Minor = getLexer().getTok().getIntVal(); - if (Minor > 255 || Minor < 0) - return TokError("invalid OS minor version number"); - Lex(); - // Get the update level, if specified - if (getLexer().isNot(AsmToken::EndOfStatement)) { - if (getLexer().isNot(AsmToken::Comma)) - return TokError("invalid update specifier, comma expected"); - Lex(); - if (getLexer().isNot(AsmToken::Integer)) - return TokError("invalid OS update number"); - Update = getLexer().getTok().getIntVal(); - if (Update > 255 || Update < 0) - return TokError("invalid OS update number"); - Lex(); - } - - const Triple &T = getContext().getObjectFileInfo()->getTargetTriple(); - Triple::OSType ExpectedOS = Triple::UnknownOS; - switch ((MCVersionMinType)Kind) { - case MCVM_WatchOSVersionMin: ExpectedOS = Triple::WatchOS; break; - case MCVM_TvOSVersionMin: ExpectedOS = Triple::TvOS; break; - case MCVM_IOSVersionMin: ExpectedOS = Triple::IOS; break; - case MCVM_OSXVersionMin: ExpectedOS = Triple::MacOSX; break; - } - if (T.getOS() != ExpectedOS) - Warning(Loc, Directive + " should only be used for " + - Triple::getOSTypeName(ExpectedOS) + " targets"); - - if (LastVersionMinDirective.isValid()) { - Warning(Loc, "overriding previous version_min directive"); - Note(LastVersionMinDirective, "previous definition is here"); - } - LastVersionMinDirective = Loc; - - // We've parsed a correct version specifier, so send it to the streamer. - getStreamer().EmitVersionMin((MCVersionMinType)Kind, Major, Minor, Update); - - return false; -} - -namespace llvm { - -MCAsmParserExtension *createDarwinAsmParser() { - return new DarwinAsmParser; -} - -} // end llvm namespace diff --git a/llvm/lib/MC/MCSectionCOFF.cpp b/llvm/lib/MC/MCSectionCOFF.cpp deleted file mode 100644 index b8373f40..00000000 --- a/llvm/lib/MC/MCSectionCOFF.cpp +++ /dev/null @@ -1,109 +0,0 @@ -//===- lib/MC/MCSectionCOFF.cpp - COFF Code Section Representation --------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "llvm/MC/MCSectionCOFF.h" -#include "llvm/MC/MCAsmInfo.h" -#include "llvm/MC/MCContext.h" -#include "llvm/MC/MCSymbol.h" -#include "llvm/Support/COFF.h" -#include "llvm/Support/raw_ostream.h" -using namespace llvm; - -MCSectionCOFF::~MCSectionCOFF() {} // anchor. - -// ShouldOmitSectionDirective - Decides whether a '.section' directive -// should be printed before the section name -bool MCSectionCOFF::ShouldOmitSectionDirective(StringRef Name, - const MCAsmInfo &MAI) const { - if (COMDATSymbol) - return false; - - // FIXME: Does .section .bss/.data/.text work everywhere?? - if (Name == ".text" || Name == ".data" || Name == ".bss") - return true; - - return false; -} - -void MCSectionCOFF::setSelection(int Selection) const { - assert(Selection != 0 && "invalid COMDAT selection type"); - this->Selection = Selection; - Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; -} - -void MCSectionCOFF::PrintSwitchToSection(const MCAsmInfo &MAI, - raw_ostream &OS, - const MCExpr *Subsection) const { - - // standard sections don't require the '.section' - if (ShouldOmitSectionDirective(SectionName, MAI)) { - OS << '\t' << getSectionName() << '\n'; - return; - } - - OS << "\t.section\t" << getSectionName() << ",\""; - if (getCharacteristics() & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA) - OS << 'd'; - if (getCharacteristics() & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) - OS << 'b'; - if (getCharacteristics() & COFF::IMAGE_SCN_MEM_EXECUTE) - OS << 'x'; - if (getCharacteristics() & COFF::IMAGE_SCN_MEM_WRITE) - OS << 'w'; - else if (getCharacteristics() & COFF::IMAGE_SCN_MEM_READ) - OS << 'r'; - else - OS << 'y'; - if (getCharacteristics() & COFF::IMAGE_SCN_LNK_REMOVE) - OS << 'n'; - if (getCharacteristics() & COFF::IMAGE_SCN_MEM_SHARED) - OS << 's'; - OS << '"'; - - if (getCharacteristics() & COFF::IMAGE_SCN_LNK_COMDAT) { - OS << ","; - switch (Selection) { - case COFF::IMAGE_COMDAT_SELECT_NODUPLICATES: - OS << "one_only,"; - break; - case COFF::IMAGE_COMDAT_SELECT_ANY: - OS << "discard,"; - break; - case COFF::IMAGE_COMDAT_SELECT_SAME_SIZE: - OS << "same_size,"; - break; - case COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH: - OS << "same_contents,"; - break; - case COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE: - OS << "associative,"; - break; - case COFF::IMAGE_COMDAT_SELECT_LARGEST: - OS << "largest,"; - break; - case COFF::IMAGE_COMDAT_SELECT_NEWEST: - OS << "newest,"; - break; - default: - assert (0 && "unsupported COFF selection type"); - break; - } - assert(COMDATSymbol); - COMDATSymbol->print(OS, &MAI); - } - OS << '\n'; -} - -bool MCSectionCOFF::UseCodeAlign() const { - return getKind().isText(); -} - -bool MCSectionCOFF::isVirtualSection() const { - return getCharacteristics() & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA; -} diff --git a/llvm/lib/MC/MCSectionMachO.cpp b/llvm/lib/MC/MCSectionMachO.cpp deleted file mode 100644 index 879c6e5f..00000000 --- a/llvm/lib/MC/MCSectionMachO.cpp +++ /dev/null @@ -1,272 +0,0 @@ -//===- lib/MC/MCSectionMachO.cpp - MachO Code Section Representation ------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "llvm/MC/MCSectionMachO.h" -#include "llvm/MC/MCContext.h" -#include "llvm/Support/raw_ostream.h" -#include -using namespace llvm; - -/// SectionTypeDescriptors - These are strings that describe the various section -/// types. This *must* be kept in order with and stay synchronized with the -/// section type list. -static const struct { - const char *AssemblerName, *EnumName; -} SectionTypeDescriptors[MachO::LAST_KNOWN_SECTION_TYPE+1] = { - { "regular", "S_REGULAR" }, // 0x00 - { nullptr, "S_ZEROFILL" }, // 0x01 - { "cstring_literals", "S_CSTRING_LITERALS" }, // 0x02 - { "4byte_literals", "S_4BYTE_LITERALS" }, // 0x03 - { "8byte_literals", "S_8BYTE_LITERALS" }, // 0x04 - { "literal_pointers", "S_LITERAL_POINTERS" }, // 0x05 - { "non_lazy_symbol_pointers", "S_NON_LAZY_SYMBOL_POINTERS" }, // 0x06 - { "lazy_symbol_pointers", "S_LAZY_SYMBOL_POINTERS" }, // 0x07 - { "symbol_stubs", "S_SYMBOL_STUBS" }, // 0x08 - { "mod_init_funcs", "S_MOD_INIT_FUNC_POINTERS" }, // 0x09 - { "mod_term_funcs", "S_MOD_TERM_FUNC_POINTERS" }, // 0x0A - { "coalesced", "S_COALESCED" }, // 0x0B - { nullptr, /*FIXME??*/ "S_GB_ZEROFILL" }, // 0x0C - { "interposing", "S_INTERPOSING" }, // 0x0D - { "16byte_literals", "S_16BYTE_LITERALS" }, // 0x0E - { nullptr, /*FIXME??*/ "S_DTRACE_DOF" }, // 0x0F - { nullptr, /*FIXME??*/ "S_LAZY_DYLIB_SYMBOL_POINTERS" }, // 0x10 - { "thread_local_regular", "S_THREAD_LOCAL_REGULAR" }, // 0x11 - { "thread_local_zerofill", "S_THREAD_LOCAL_ZEROFILL" }, // 0x12 - { "thread_local_variables", "S_THREAD_LOCAL_VARIABLES" }, // 0x13 - { "thread_local_variable_pointers", - "S_THREAD_LOCAL_VARIABLE_POINTERS" }, // 0x14 - { "thread_local_init_function_pointers", - "S_THREAD_LOCAL_INIT_FUNCTION_POINTERS"}, // 0x15 -}; - - -/// SectionAttrDescriptors - This is an array of descriptors for section -/// attributes. Unlike the SectionTypeDescriptors, this is not directly indexed -/// by attribute, instead it is searched. -static const struct { - unsigned AttrFlag; - const char *AssemblerName, *EnumName; -} SectionAttrDescriptors[] = { -#define ENTRY(ASMNAME, ENUM) \ - { MachO::ENUM, ASMNAME, #ENUM }, -ENTRY("pure_instructions", S_ATTR_PURE_INSTRUCTIONS) -ENTRY("no_toc", S_ATTR_NO_TOC) -ENTRY("strip_static_syms", S_ATTR_STRIP_STATIC_SYMS) -ENTRY("no_dead_strip", S_ATTR_NO_DEAD_STRIP) -ENTRY("live_support", S_ATTR_LIVE_SUPPORT) -ENTRY("self_modifying_code", S_ATTR_SELF_MODIFYING_CODE) -ENTRY("debug", S_ATTR_DEBUG) -ENTRY(nullptr /*FIXME*/, S_ATTR_SOME_INSTRUCTIONS) -ENTRY(nullptr /*FIXME*/, S_ATTR_EXT_RELOC) -ENTRY(nullptr /*FIXME*/, S_ATTR_LOC_RELOC) -#undef ENTRY - { 0, "none", nullptr }, // used if section has no attributes but has a stub size -}; - -MCSectionMachO::MCSectionMachO(StringRef Segment, StringRef Section, - unsigned TAA, unsigned reserved2, SectionKind K, - MCSymbol *Begin) - : MCSection(SV_MachO, K, Begin), TypeAndAttributes(TAA), - Reserved2(reserved2) { - assert(Segment.size() <= 16 && Section.size() <= 16 && - "Segment or section string too long"); - for (unsigned i = 0; i != 16; ++i) { - if (i < Segment.size()) - SegmentName[i] = Segment[i]; - else - SegmentName[i] = 0; - - if (i < Section.size()) - SectionName[i] = Section[i]; - else - SectionName[i] = 0; - } -} - -void MCSectionMachO::PrintSwitchToSection(const MCAsmInfo &MAI, - raw_ostream &OS, - const MCExpr *Subsection) const { - OS << "\t.section\t" << getSegmentName() << ',' << getSectionName(); - - // Get the section type and attributes. - unsigned TAA = getTypeAndAttributes(); - if (TAA == 0) { - OS << '\n'; - return; - } - - MachO::SectionType SectionType = getType(); - assert(SectionType <= MachO::LAST_KNOWN_SECTION_TYPE && - "Invalid SectionType specified!"); - - if (SectionTypeDescriptors[SectionType].AssemblerName) { - OS << ','; - OS << SectionTypeDescriptors[SectionType].AssemblerName; - } else { - // If we have no name for the attribute, stop here. - OS << '\n'; - return; - } - - // If we don't have any attributes, we're done. - unsigned SectionAttrs = TAA & MachO::SECTION_ATTRIBUTES; - if (SectionAttrs == 0) { - // If we have a S_SYMBOL_STUBS size specified, print it along with 'none' as - // the attribute specifier. - if (Reserved2 != 0) - OS << ",none," << Reserved2; - OS << '\n'; - return; - } - - // Check each attribute to see if we have it. - char Separator = ','; - for (unsigned i = 0; - SectionAttrs != 0 && SectionAttrDescriptors[i].AttrFlag; - ++i) { - // Check to see if we have this attribute. - if ((SectionAttrDescriptors[i].AttrFlag & SectionAttrs) == 0) - continue; - - // Yep, clear it and print it. - SectionAttrs &= ~SectionAttrDescriptors[i].AttrFlag; - - OS << Separator; - if (SectionAttrDescriptors[i].AssemblerName) - OS << SectionAttrDescriptors[i].AssemblerName; - else - OS << "<<" << SectionAttrDescriptors[i].EnumName << ">>"; - Separator = '+'; - } - - assert(SectionAttrs == 0 && "Unknown section attributes!"); - - // If we have a S_SYMBOL_STUBS size specified, print it. - if (Reserved2 != 0) - OS << ',' << Reserved2; - OS << '\n'; -} - -bool MCSectionMachO::UseCodeAlign() const { - return hasAttribute(MachO::S_ATTR_PURE_INSTRUCTIONS); -} - -bool MCSectionMachO::isVirtualSection() const { - return (getType() == MachO::S_ZEROFILL || - getType() == MachO::S_GB_ZEROFILL || - getType() == MachO::S_THREAD_LOCAL_ZEROFILL); -} - -/// ParseSectionSpecifier - Parse the section specifier indicated by "Spec". -/// This is a string that can appear after a .section directive in a mach-o -/// flavored .s file. If successful, this fills in the specified Out -/// parameters and returns an empty string. When an invalid section -/// specifier is present, this returns a string indicating the problem. -std::string MCSectionMachO::ParseSectionSpecifier(StringRef Spec, // In. - StringRef &Segment, // Out. - StringRef &Section, // Out. - unsigned &TAA, // Out. - bool &TAAParsed, // Out. - unsigned &StubSize) { // Out. - TAAParsed = false; - - SmallVector SplitSpec; - Spec.split(SplitSpec, ','); - // Remove leading and trailing whitespace. - auto GetEmptyOrTrim = [&SplitSpec](size_t Idx) -> StringRef { - return SplitSpec.size() > Idx ? SplitSpec[Idx].trim() : StringRef(); - }; - Segment = GetEmptyOrTrim(0); - Section = GetEmptyOrTrim(1); - StringRef SectionType = GetEmptyOrTrim(2); - StringRef Attrs = GetEmptyOrTrim(3); - StringRef StubSizeStr = GetEmptyOrTrim(4); - - // Verify that the segment is present and not too long. - if (Segment.empty() || Segment.size() > 16) - return "mach-o section specifier requires a segment whose length is " - "between 1 and 16 characters"; - - // Verify that the section is present and not too long. - if (Section.empty()) - return "mach-o section specifier requires a segment and section " - "separated by a comma"; - - if (Section.size() > 16) - return "mach-o section specifier requires a section whose length is " - "between 1 and 16 characters"; - - // If there is no comma after the section, we're done. - TAA = 0; - StubSize = 0; - if (SectionType.empty()) - return ""; - - // Figure out which section type it is. - auto TypeDescriptor = std::find_if( - std::begin(SectionTypeDescriptors), std::end(SectionTypeDescriptors), - [&](decltype(*SectionTypeDescriptors) &Descriptor) { - return Descriptor.AssemblerName && - SectionType == Descriptor.AssemblerName; - }); - - // If we didn't find the section type, reject it. - if (TypeDescriptor == std::end(SectionTypeDescriptors)) - return "mach-o section specifier uses an unknown section type"; - - // Remember the TypeID. - TAA = TypeDescriptor - std::begin(SectionTypeDescriptors); - TAAParsed = true; - - // If we have no comma after the section type, there are no attributes. - if (Attrs.empty()) { - // S_SYMBOL_STUBS always require a symbol stub size specifier. - if (TAA == MachO::S_SYMBOL_STUBS) - return "mach-o section specifier of type 'symbol_stubs' requires a size " - "specifier"; - return ""; - } - - // The attribute list is a '+' separated list of attributes. - SmallVector SectionAttrs; - Attrs.split(SectionAttrs, '+', /*MaxSplit=*/-1, /*KeepEmpty=*/false); - - for (StringRef &SectionAttr : SectionAttrs) { - auto AttrDescriptorI = std::find_if( - std::begin(SectionAttrDescriptors), std::end(SectionAttrDescriptors), - [&](decltype(*SectionAttrDescriptors) &Descriptor) { - return Descriptor.AssemblerName && - SectionAttr.trim() == Descriptor.AssemblerName; - }); - if (AttrDescriptorI == std::end(SectionAttrDescriptors)) - return "mach-o section specifier has invalid attribute"; - - TAA |= AttrDescriptorI->AttrFlag; - } - - // Okay, we've parsed the section attributes, see if we have a stub size spec. - if (StubSizeStr.empty()) { - // S_SYMBOL_STUBS always require a symbol stub size specifier. - if (TAA == MachO::S_SYMBOL_STUBS) - return "mach-o section specifier of type 'symbol_stubs' requires a size " - "specifier"; - return ""; - } - - // If we have a stub size spec, we must have a sectiontype of S_SYMBOL_STUBS. - if ((TAA & MachO::SECTION_TYPE) != MachO::S_SYMBOL_STUBS) - return "mach-o section specifier cannot have a stub size specified because " - "it does not have type 'symbol_stubs'"; - - // Convert the stub size from a string to an integer. - if (StubSizeStr.getAsInteger(0, StubSize)) - return "mach-o section specifier has a malformed stub size"; - - return ""; -} diff --git a/llvm/lib/MC/MCStreamer.cpp b/llvm/lib/MC/MCStreamer.cpp index ac51eaf1..4c9e8751 100644 --- a/llvm/lib/MC/MCStreamer.cpp +++ b/llvm/lib/MC/MCStreamer.cpp @@ -120,8 +120,6 @@ void MCStreamer::EmitSymbolValue(const MCSymbol *Sym, unsigned Size, if (!IsSectionRelative) EmitValueImpl(MCSymbolRefExpr::create(Sym, getContext()), Size); - else - EmitCOFFSecRel32(Sym); } void MCStreamer::EmitGPRel64Value(const MCExpr *Value) { @@ -586,15 +584,6 @@ void MCStreamer::EmitWinCFIEndProlog() { CurrentWinFrameInfo->PrologEnd = Label; } -void MCStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) { -} - -void MCStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) { -} - -void MCStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) { -} - /// 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. @@ -692,11 +681,7 @@ void MCStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo, void MCStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {} void MCStreamer::EmitThumbFunc(MCSymbol *Func) {} void MCStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {} -void MCStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {} -void MCStreamer::EndCOFFSymbolDef() {} void MCStreamer::EmitFileDirective(StringRef Filename) {} -void MCStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {} -void MCStreamer::EmitCOFFSymbolType(int Type) {} void MCStreamer::emitELFSize(MCSymbolELF *Symbol, const MCExpr *Value) {} void MCStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) {} diff --git a/llvm/lib/MC/StringTableBuilder.cpp b/llvm/lib/MC/StringTableBuilder.cpp index f50e098e..5768f7f1 100644 --- a/llvm/lib/MC/StringTableBuilder.cpp +++ b/llvm/lib/MC/StringTableBuilder.cpp @@ -9,7 +9,6 @@ #include "llvm/MC/StringTableBuilder.h" #include "llvm/ADT/STLExtras.h" -#include "llvm/Support/COFF.h" #include "llvm/Support/Endian.h" #include @@ -23,13 +22,9 @@ StringTableBuilder::StringTableBuilder(Kind K) : K(K) { case RAW: Size = 0; break; - case MachO: case ELF: Size = 1; break; - case WinCOFF: - Size = 4; - break; } } @@ -108,22 +103,14 @@ void StringTableBuilder::finalizeStringTable(bool Optimize) { case RAW: break; case ELF: - case MachO: // Start the table with a NUL byte. StringTable += '\x00'; break; - case WinCOFF: - // Make room to write the table size later. - StringTable.append(4, '\x00'); - break; } StringRef Previous; for (StringOffsetPair *P : Strings) { StringRef S = P->first; - if (K == WinCOFF) - assert(S.size() > COFF::NameSize && "Short string in COFF string table!"); - if (Optimize && Previous.endswith(S)) { P->second = StringTable.size() - S.size() - (K != RAW); continue; @@ -145,18 +132,10 @@ void StringTableBuilder::finalizeStringTable(bool Optimize) { case RAW: case ELF: break; - case MachO: // Pad to multiple of 4. while (StringTable.size() % 4) StringTable += '\x00'; break; - case WinCOFF: - // Write the table size in the first word. - assert(StringTable.size() <= std::numeric_limits::max()); - uint32_t Size = static_cast(StringTable.size()); - support::endian::write( - StringTable.data(), Size); - break; } Size = StringTable.size(); diff --git a/llvm/lib/Support/Path.cpp b/llvm/lib/Support/Path.cpp index c6573331..7fd17b72 100644 --- a/llvm/lib/Support/Path.cpp +++ b/llvm/lib/Support/Path.cpp @@ -11,8 +11,6 @@ // //===----------------------------------------------------------------------===// -#include "llvm/Support/COFF.h" -#include "llvm/Support/MachO.h" #include "llvm/Support/Endian.h" #include "llvm/Support/Errc.h" #include "llvm/Support/ErrorHandling.h" @@ -955,34 +953,6 @@ file_magic identify_magic(StringRef Magic) { if (Magic.size() < 4) return file_magic::unknown; switch ((unsigned char)Magic[0]) { - case 0x00: { - // COFF bigobj or short import library file - if (Magic[1] == (char)0x00 && Magic[2] == (char)0xff && - Magic[3] == (char)0xff) { - size_t MinSize = offsetof(COFF::BigObjHeader, UUID) + sizeof(COFF::BigObjMagic); - if (Magic.size() < MinSize) - return file_magic::coff_import_library; - - int BigObjVersion = read16le( - Magic.data() + offsetof(COFF::BigObjHeader, Version)); - if (BigObjVersion < COFF::BigObjHeader::MinBigObjectVersion) - return file_magic::coff_import_library; - - const char *Start = Magic.data() + offsetof(COFF::BigObjHeader, UUID); - if (memcmp(Start, COFF::BigObjMagic, sizeof(COFF::BigObjMagic)) != 0) - return file_magic::coff_import_library; - return file_magic::coff_object; - } - // Windows resource file - const char Expected[] = { 0, 0, 0, 0, '\x20', 0, 0, 0, '\xff' }; - if (Magic.size() >= sizeof(Expected) && - memcmp(Magic.data(), Expected, sizeof(Expected)) == 0) - return file_magic::windows_resource; - // 0x0000 = COFF unknown machine type - if (Magic[1] == 0) - return file_magic::coff_object; - break; - } case 0xDE: // 0x0B17C0DE = BC wraper if (Magic[1] == (char)0xC0 && Magic[2] == (char)0x17 && Magic[3] == (char)0x0B) @@ -1018,94 +988,6 @@ file_magic identify_magic(StringRef Magic) { return file_magic::elf; } break; - - case 0xCA: - if (Magic[1] == char(0xFE) && Magic[2] == char(0xBA) && - Magic[3] == char(0xBE)) { - // This is complicated by an overlap with Java class files. - // See the Mach-O section in /usr/share/file/magic for details. - if (Magic.size() >= 8 && Magic[7] < 43) - return file_magic::macho_universal_binary; - } - break; - - // The two magic numbers for mach-o are: - // 0xfeedface - 32-bit mach-o - // 0xfeedfacf - 64-bit mach-o - case 0xFE: - case 0xCE: - case 0xCF: { - uint16_t type = 0; - if (Magic[0] == char(0xFE) && Magic[1] == char(0xED) && - Magic[2] == char(0xFA) && - (Magic[3] == char(0xCE) || Magic[3] == char(0xCF))) { - /* Native endian */ - size_t MinSize; - if (Magic[3] == char(0xCE)) - MinSize = sizeof(MachO::mach_header); - else - MinSize = sizeof(MachO::mach_header_64); - if (Magic.size() >= MinSize) - type = Magic[12] << 24 | Magic[13] << 12 | Magic[14] << 8 | Magic[15]; - } else if ((Magic[0] == char(0xCE) || Magic[0] == char(0xCF)) && - Magic[1] == char(0xFA) && Magic[2] == char(0xED) && - Magic[3] == char(0xFE)) { - /* Reverse endian */ - size_t MinSize; - if (Magic[0] == char(0xCE)) - MinSize = sizeof(MachO::mach_header); - else - MinSize = sizeof(MachO::mach_header_64); - if (Magic.size() >= MinSize) - type = Magic[15] << 24 | Magic[14] << 12 |Magic[13] << 8 | Magic[12]; - } - switch (type) { - default: break; - case 1: return file_magic::macho_object; - case 2: return file_magic::macho_executable; - case 3: return file_magic::macho_fixed_virtual_memory_shared_lib; - case 4: return file_magic::macho_core; - case 5: return file_magic::macho_preload_executable; - case 6: return file_magic::macho_dynamically_linked_shared_lib; - case 7: return file_magic::macho_dynamic_linker; - case 8: return file_magic::macho_bundle; - case 9: return file_magic::macho_dynamically_linked_shared_lib_stub; - case 10: return file_magic::macho_dsym_companion; - case 11: return file_magic::macho_kext_bundle; - } - break; - } - case 0xF0: // PowerPC Windows - case 0x83: // Alpha 32-bit - case 0x84: // Alpha 64-bit - case 0x66: // MPS R4000 Windows - case 0x50: // mc68K - case 0x4c: // 80386 Windows - case 0xc4: // ARMNT Windows - if (Magic[1] == 0x01) - return file_magic::coff_object; - - case 0x90: // PA-RISC Windows - case 0x68: // mc68K Windows - if (Magic[1] == 0x02) - return file_magic::coff_object; - break; - - case 'M': // Possible MS-DOS stub on Windows PE file - if (Magic[1] == 'Z') { - uint32_t off = read32le(Magic.data() + 0x3c); - // PE/COFF file, either EXE or DLL. - if (off < Magic.size() && - memcmp(Magic.data()+off, COFF::PEMagic, sizeof(COFF::PEMagic)) == 0) - return file_magic::pecoff_executable; - } - break; - - case 0x64: // x86-64 Windows. - if (Magic[1] == char(0x86)) - return file_magic::coff_object; - break; - default: break; } diff --git a/llvm/lib/Support/Triple.cpp b/llvm/lib/Support/Triple.cpp index 5099cd52..6154a824 100644 --- a/llvm/lib/Support/Triple.cpp +++ b/llvm/lib/Support/Triple.cpp @@ -462,14 +462,6 @@ static Triple::EnvironmentType parseEnvironment(StringRef EnvironmentName) { .Default(Triple::UnknownEnvironment); } -static Triple::ObjectFormatType parseFormat(StringRef EnvironmentName) { - return StringSwitch(EnvironmentName) - .EndsWith("coff", Triple::COFF) - .EndsWith("elf", Triple::ELF) - .EndsWith("macho", Triple::MachO) - .Default(Triple::UnknownObjectFormat); -} - static Triple::SubArchType parseSubArch(StringRef SubArchName) { StringRef ARMSubArch = ARM::getCanonicalArchName(SubArchName); @@ -530,84 +522,13 @@ static Triple::SubArchType parseSubArch(StringRef SubArchName) { } } -static const char *getObjectFormatTypeName(Triple::ObjectFormatType Kind) { - switch (Kind) { - case Triple::UnknownObjectFormat: return ""; - case Triple::COFF: return "coff"; - case Triple::ELF: return "elf"; - case Triple::MachO: return "macho"; - } - llvm_unreachable("unknown object format type"); -} - -static Triple::ObjectFormatType getDefaultFormat(const Triple &T) { - switch (T.getArch()) { - case Triple::UnknownArch: - case Triple::aarch64: - case Triple::arm: - case Triple::thumb: - case Triple::x86: - case Triple::x86_64: - if (T.isOSDarwin()) - return Triple::MachO; - else if (T.isOSWindows()) - return Triple::COFF; - return Triple::ELF; - - case Triple::aarch64_be: - case Triple::amdgcn: - case Triple::amdil: - case Triple::amdil64: - case Triple::armeb: - case Triple::avr: - case Triple::bpfeb: - case Triple::bpfel: - case Triple::hexagon: - case Triple::hsail: - case Triple::hsail64: - case Triple::kalimba: - case Triple::le32: - case Triple::le64: - case Triple::mips: - case Triple::mips64: - case Triple::mips64el: - case Triple::mipsel: - case Triple::msp430: - case Triple::nvptx: - case Triple::nvptx64: - case Triple::ppc64le: - case Triple::r600: - case Triple::shave: - case Triple::sparc: - case Triple::sparcel: - case Triple::sparcv9: - case Triple::spir: - case Triple::spir64: - case Triple::systemz: - case Triple::tce: - case Triple::thumbeb: - case Triple::wasm32: - case Triple::wasm64: - case Triple::xcore: - return Triple::ELF; - - case Triple::ppc: - case Triple::ppc64: - if (T.isOSDarwin()) - return Triple::MachO; - return Triple::ELF; - } - llvm_unreachable("unknown architecture"); -} - /// \brief Construct a triple from the string representation provided. /// /// This stores the string representation and parses the various pieces into /// enum members. Triple::Triple(const Twine &Str) : Data(Str.str()), Arch(UnknownArch), SubArch(NoSubArch), - Vendor(UnknownVendor), OS(UnknownOS), Environment(UnknownEnvironment), - ObjectFormat(UnknownObjectFormat) { + Vendor(UnknownVendor), OS(UnknownOS), Environment(UnknownEnvironment) { // Do minimal parsing by hand here. SmallVector Components; StringRef(Data).split(Components, '-', /*MaxSplit*/ 3); @@ -620,13 +541,10 @@ Triple::Triple(const Twine &Str) OS = parseOS(Components[2]); if (Components.size() > 3) { Environment = parseEnvironment(Components[3]); - ObjectFormat = parseFormat(Components[3]); } } } } - if (ObjectFormat == UnknownObjectFormat) - ObjectFormat = getDefaultFormat(*this); } /// \brief Construct a triple from string representations of the architecture, @@ -641,8 +559,7 @@ Triple::Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr) SubArch(parseSubArch(ArchStr.str())), Vendor(parseVendor(VendorStr.str())), OS(parseOS(OSStr.str())), - Environment(), ObjectFormat(Triple::UnknownObjectFormat) { - ObjectFormat = getDefaultFormat(*this); + Environment() { } /// \brief Construct a triple from string representations of the architecture, @@ -658,10 +575,7 @@ Triple::Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr, SubArch(parseSubArch(ArchStr.str())), Vendor(parseVendor(VendorStr.str())), OS(parseOS(OSStr.str())), - Environment(parseEnvironment(EnvironmentStr.str())), - ObjectFormat(parseFormat(EnvironmentStr.str())) { - if (ObjectFormat == Triple::UnknownObjectFormat) - ObjectFormat = getDefaultFormat(*this); + Environment(parseEnvironment(EnvironmentStr.str())) { } std::string Triple::normalize(StringRef Str) { @@ -692,9 +606,6 @@ std::string Triple::normalize(StringRef Str) { EnvironmentType Environment = UnknownEnvironment; if (Components.size() > 3) Environment = parseEnvironment(Components[3]); - ObjectFormatType ObjectFormat = UnknownObjectFormat; - if (Components.size() > 4) - ObjectFormat = parseFormat(Components[4]); // Note which components are already in their final position. These will not // be moved. @@ -738,10 +649,6 @@ std::string Triple::normalize(StringRef Str) { case 3: Environment = parseEnvironment(Comp); Valid = Environment != UnknownEnvironment; - if (!Valid) { - ObjectFormat = parseFormat(Comp); - Valid = ObjectFormat != UnknownObjectFormat; - } break; } if (!Valid) @@ -818,10 +725,7 @@ std::string Triple::normalize(StringRef Str) { Components.resize(4); Components[2] = "windows"; if (Environment == UnknownEnvironment) { - if (ObjectFormat == UnknownObjectFormat || ObjectFormat == Triple::COFF) - Components[3] = "msvc"; - else - Components[3] = getObjectFormatTypeName(ObjectFormat); + Components[3] = "elf"; } } else if (IsMinGW32) { Components.resize(4); @@ -834,10 +738,8 @@ std::string Triple::normalize(StringRef Str) { } if (IsMinGW32 || IsCygwin || (OS == Triple::Win32 && Environment != UnknownEnvironment)) { - if (ObjectFormat != UnknownObjectFormat && ObjectFormat != Triple::COFF) { - Components.resize(5); - Components[4] = getObjectFormatTypeName(ObjectFormat); - } + Components.resize(5); + Components[4] = "elf"; } // Stick the corrected components back together to form the normalized string. @@ -1039,19 +941,8 @@ void Triple::setOS(OSType Kind) { } void Triple::setEnvironment(EnvironmentType Kind) { - if (ObjectFormat == getDefaultFormat(*this)) - return setEnvironmentName(getEnvironmentTypeName(Kind)); - setEnvironmentName((getEnvironmentTypeName(Kind) + Twine("-") + - getObjectFormatTypeName(ObjectFormat)).str()); -} - -void Triple::setObjectFormat(ObjectFormatType Kind) { - if (Environment == UnknownEnvironment) - return setEnvironmentName(getObjectFormatTypeName(Kind)); - - setEnvironmentName((getEnvironmentTypeName(Environment) + Twine("-") + - getObjectFormatTypeName(Kind)).str()); + "elf").str()); } void Triple::setArchName(StringRef Str) { diff --git a/llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp b/llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp index 391f411f..c0745b7b 100644 --- a/llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp +++ b/llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp @@ -4206,11 +4206,6 @@ bool AArch64AsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode, /// ParseDirective parses the arm specific directives bool AArch64AsmParser::ParseDirective(AsmToken DirectiveID) { - const MCObjectFileInfo::Environment Format = - getContext().getObjectFileInfo()->getObjectFileType(); - bool IsMachO = Format == MCObjectFileInfo::IsMachO; - bool IsCOFF = Format == MCObjectFileInfo::IsCOFF; - StringRef IDVal = DirectiveID.getIdentifier(); SMLoc Loc = DirectiveID.getLoc(); if (IDVal == ".hword") @@ -4225,11 +4220,8 @@ bool AArch64AsmParser::ParseDirective(AsmToken DirectiveID) { return parseDirectiveLtorg(Loc); if (IDVal == ".unreq") return parseDirectiveUnreq(Loc); - - if (!IsMachO && !IsCOFF) { - if (IDVal == ".inst") - return parseDirectiveInst(Loc); - } + if (IDVal == ".inst") + return parseDirectiveInst(Loc); return parseDirectiveLOH(IDVal, Loc); } diff --git a/llvm/lib/Target/AArch64/MCTargetDesc/AArch64AsmBackend.cpp b/llvm/lib/Target/AArch64/MCTargetDesc/AArch64AsmBackend.cpp index 10be82d8..ef3f0b19 100644 --- a/llvm/lib/Target/AArch64/MCTargetDesc/AArch64AsmBackend.cpp +++ b/llvm/lib/Target/AArch64/MCTargetDesc/AArch64AsmBackend.cpp @@ -18,10 +18,8 @@ #include "llvm/MC/MCFixupKindInfo.h" #include "llvm/MC/MCObjectWriter.h" #include "llvm/MC/MCSectionELF.h" -#include "llvm/MC/MCSectionMachO.h" #include "llvm/MC/MCValue.h" #include "llvm/Support/ErrorHandling.h" -#include "llvm/Support/MachO.h" using namespace llvm; namespace { @@ -402,7 +400,6 @@ MCAsmBackend *llvm::createAArch64leAsmBackend(const Target &T, const MCRegisterInfo &MRI, const Triple &TheTriple, StringRef CPU) { - assert(TheTriple.isOSBinFormatELF() && "Expect either MachO or ELF target"); uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS()); return new ELFAArch64AsmBackend(T, OSABI, /*IsLittleEndian=*/true); } @@ -411,8 +408,6 @@ MCAsmBackend *llvm::createAArch64beAsmBackend(const Target &T, const MCRegisterInfo &MRI, const Triple &TheTriple, StringRef CPU) { - assert(TheTriple.isOSBinFormatELF() && - "Big endian is only supported for ELF targets!"); uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS()); return new ELFAArch64AsmBackend(T, OSABI, /*IsLittleEndian=*/false); diff --git a/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.cpp b/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.cpp index f060b6d8..ca1876f0 100644 --- a/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.cpp +++ b/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.cpp @@ -27,39 +27,6 @@ enum AsmWriterVariantTy { static AsmWriterVariantTy AsmWriterVariant = Default; -AArch64MCAsmInfoDarwin::AArch64MCAsmInfoDarwin() { - // We prefer NEON instructions to be printed in the short form. - AssemblerDialect = AsmWriterVariant == Default ? 1 : AsmWriterVariant; - - PrivateGlobalPrefix = "L"; - PrivateLabelPrefix = "L"; - SeparatorString = "%%"; - CommentString = ";"; - PointerSize = CalleeSaveStackSlotSize = 8; - - AlignmentIsInBytes = false; - UsesELFSectionDirectiveForBSS = true; - SupportsDebugInformation = true; - UseDataRegionDirectives = true; - - ExceptionsType = ExceptionHandling::DwarfCFI; -} - -const MCExpr *AArch64MCAsmInfoDarwin::getExprForPersonalitySymbol( - const MCSymbol *Sym, unsigned Encoding, MCStreamer &Streamer) const { - // On Darwin, we can reference dwarf symbols with foo@GOT-., which - // is an indirect pc-relative reference. The default implementation - // won't reference using the GOT, so we need this target-specific - // version. - MCContext &Context = Streamer.getContext(); - const MCExpr *Res = - MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_GOT, Context); - MCSymbol *PCSym = Context.createTempSymbol(); - Streamer.EmitLabel(PCSym); - const MCExpr *PC = MCSymbolRefExpr::create(PCSym, Context); - return MCBinaryExpr::createSub(Res, PC, Context); -} - AArch64MCAsmInfoELF::AArch64MCAsmInfoELF(const Triple &T) { if (T.getArch() == Triple::aarch64_be) IsLittleEndian = false; diff --git a/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.h b/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.h index 253cd30f..b73d7160 100644 --- a/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.h +++ b/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.h @@ -14,7 +14,6 @@ #ifndef LLVM_LIB_TARGET_AARCH64_MCTARGETDESC_AARCH64MCASMINFO_H #define LLVM_LIB_TARGET_AARCH64_MCTARGETDESC_AARCH64MCASMINFO_H -#include "llvm/MC/MCAsmInfoDarwin.h" #include "llvm/MC/MCAsmInfoELF.h" namespace llvm { @@ -22,13 +21,6 @@ class MCStreamer; class Target; class Triple; -struct AArch64MCAsmInfoDarwin : public MCAsmInfoDarwin { - explicit AArch64MCAsmInfoDarwin(); - const MCExpr * - getExprForPersonalitySymbol(const MCSymbol *Sym, unsigned Encoding, - MCStreamer &Streamer) const override; -}; - struct AArch64MCAsmInfoELF : public MCAsmInfoELF { explicit AArch64MCAsmInfoELF(const Triple &T); }; diff --git a/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.cpp b/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.cpp index adae17f1..39d937bf 100644 --- a/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.cpp +++ b/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.cpp @@ -55,13 +55,7 @@ static MCRegisterInfo *createAArch64MCRegisterInfo(const Triple &Triple) { static MCAsmInfo *createAArch64MCAsmInfo(const MCRegisterInfo &MRI, const Triple &TheTriple) { - MCAsmInfo *MAI; - if (TheTriple.isOSBinFormatMachO()) - MAI = new AArch64MCAsmInfoDarwin(); - else { - assert(TheTriple.isOSBinFormatELF() && "Only expect Darwin or ELF"); - MAI = new AArch64MCAsmInfoELF(TheTriple); - } + MCAsmInfo *MAI = new AArch64MCAsmInfoELF(TheTriple); // Initial state of the frame pointer is SP. unsigned Reg = MRI.getDwarfRegNum(AArch64::SP, true); diff --git a/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp b/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp index b700aaf9..89cc9e68 100644 --- a/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp +++ b/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp @@ -38,7 +38,6 @@ #include "llvm/MC/MCSymbol.h" #include "llvm/Support/ARMBuildAttributes.h" #include "llvm/Support/ARMEHABI.h" -#include "llvm/Support/COFF.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ELF.h" #include "llvm/Support/MathExtras.h" @@ -5274,17 +5273,15 @@ bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) { } enum { - COFF = (1 << MCObjectFileInfo::IsCOFF), ELF = (1 << MCObjectFileInfo::IsELF), - MACHO = (1 << MCObjectFileInfo::IsMachO) }; static const struct PrefixEntry { const char *Spelling; ARMMCExpr::VariantKind VariantKind; uint8_t SupportedFormats; } PrefixEntries[] = { - { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO }, - { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO }, + { "lower16", ARMMCExpr::VK_ARM_LO16, ELF}, + { "upper16", ARMMCExpr::VK_ARM_HI16, ELF}, }; StringRef IDVal = Parser.getTok().getIdentifier(); @@ -5301,15 +5298,9 @@ bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) { uint8_t CurrentFormat; switch (getContext().getObjectFileInfo()->getObjectFileType()) { - case MCObjectFileInfo::IsMachO: - CurrentFormat = MACHO; - break; case MCObjectFileInfo::IsELF: CurrentFormat = ELF; break; - case MCObjectFileInfo::IsCOFF: - CurrentFormat = COFF; - break; } if (~Prefix->SupportedFormats & CurrentFormat) { @@ -8807,11 +8798,6 @@ bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode, /// parseDirective parses the arm specific directives bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) { - const MCObjectFileInfo::Environment Format = - getContext().getObjectFileInfo()->getObjectFileType(); - bool IsMachO = Format == MCObjectFileInfo::IsMachO; - bool IsCOFF = Format == MCObjectFileInfo::IsCOFF; - StringRef IDVal = DirectiveID.getIdentifier(); if (IDVal == ".word") return parseLiteralValues(4, DirectiveID.getLoc()); @@ -8861,29 +8847,26 @@ bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) { return parseDirectiveAlign(DirectiveID.getLoc()); else if (IDVal == ".thumb_set") return parseDirectiveThumbSet(DirectiveID.getLoc()); - - if (!IsMachO && !IsCOFF) { - if (IDVal == ".arch") - return parseDirectiveArch(DirectiveID.getLoc()); - else if (IDVal == ".cpu") - return parseDirectiveCPU(DirectiveID.getLoc()); - else if (IDVal == ".eabi_attribute") - return parseDirectiveEabiAttr(DirectiveID.getLoc()); - else if (IDVal == ".fpu") - return parseDirectiveFPU(DirectiveID.getLoc()); - else if (IDVal == ".fnstart") - return parseDirectiveFnStart(DirectiveID.getLoc()); - else if (IDVal == ".inst") - return parseDirectiveInst(DirectiveID.getLoc()); - else if (IDVal == ".inst.n") - return parseDirectiveInst(DirectiveID.getLoc(), 'n'); - else if (IDVal == ".inst.w") - return parseDirectiveInst(DirectiveID.getLoc(), 'w'); - else if (IDVal == ".object_arch") - return parseDirectiveObjectArch(DirectiveID.getLoc()); - else if (IDVal == ".tlsdescseq") - return parseDirectiveTLSDescSeq(DirectiveID.getLoc()); - } + else if (IDVal == ".arch") + return parseDirectiveArch(DirectiveID.getLoc()); + else if (IDVal == ".cpu") + return parseDirectiveCPU(DirectiveID.getLoc()); + else if (IDVal == ".eabi_attribute") + return parseDirectiveEabiAttr(DirectiveID.getLoc()); + else if (IDVal == ".fpu") + return parseDirectiveFPU(DirectiveID.getLoc()); + else if (IDVal == ".fnstart") + return parseDirectiveFnStart(DirectiveID.getLoc()); + else if (IDVal == ".inst") + return parseDirectiveInst(DirectiveID.getLoc()); + else if (IDVal == ".inst.n") + return parseDirectiveInst(DirectiveID.getLoc(), 'n'); + else if (IDVal == ".inst.w") + return parseDirectiveInst(DirectiveID.getLoc(), 'w'); + else if (IDVal == ".object_arch") + return parseDirectiveObjectArch(DirectiveID.getLoc()); + else if (IDVal == ".tlsdescseq") + return parseDirectiveTLSDescSeq(DirectiveID.getLoc()); return true; } @@ -8975,26 +8958,6 @@ void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) { /// ::= .thumbfunc symbol_name bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) { MCAsmParser &Parser = getParser(); - const auto Format = getContext().getObjectFileInfo()->getObjectFileType(); - bool IsMachO = Format == MCObjectFileInfo::IsMachO; - - // Darwin asm has (optionally) function name after .thumb_func direction - // ELF doesn't - if (IsMachO) { - const AsmToken &Tok = Parser.getTok(); - if (Tok.isNot(AsmToken::EndOfStatement)) { - if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String)) { - Error(L, "unexpected token in .thumb_func directive"); - return false; - } - - MCSymbol *Func = - getParser().getContext().getOrCreateSymbol(Tok.getIdentifier()); - getParser().getStreamer().EmitThumbFunc(Func); - Parser.Lex(); // Consume the identifier token. - return false; - } - } if (getLexer().isNot(AsmToken::EndOfStatement)) { Error(Parser.getTok().getLoc(), "unexpected token in directive"); diff --git a/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp b/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp index b96b2c75..fba75385 100644 --- a/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp +++ b/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp @@ -24,14 +24,12 @@ #include "llvm/MC/MCObjectWriter.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSectionELF.h" -#include "llvm/MC/MCSectionMachO.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/MCValue.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ELF.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Format.h" -#include "llvm/Support/MachO.h" #include "llvm/Support/TargetParser.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; @@ -872,14 +870,8 @@ MCAsmBackend *llvm::createARMAsmBackend(const Target &T, const MCRegisterInfo &MRI, const Triple &TheTriple, StringRef CPU, bool isLittle) { - switch (TheTriple.getObjectFormat()) { - default: - llvm_unreachable("unsupported object format"); - case Triple::ELF: - assert(TheTriple.isOSBinFormatELF() && "using ELF for non-ELF target"); - uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS()); - return new ARMAsmBackendELF(T, TheTriple, OSABI, isLittle); - } + uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS()); + return new ARMAsmBackendELF(T, TheTriple, OSABI, isLittle); } MCAsmBackend *llvm::createARMLEAsmBackend(const Target &T, diff --git a/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.cpp b/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.cpp index 1a4a9914..a7911060 100644 --- a/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.cpp +++ b/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.cpp @@ -16,27 +16,6 @@ using namespace llvm; -ARMMCAsmInfoDarwin::ARMMCAsmInfoDarwin(const Triple &TheTriple) { - if ((TheTriple.getArch() == Triple::armeb) || - (TheTriple.getArch() == Triple::thumbeb)) - IsLittleEndian = false; - - Data64bitsDirective = nullptr; - CommentString = "@"; - Code16Directive = ".code\t16"; - Code32Directive = ".code\t32"; - UseDataRegionDirectives = true; - - SupportsDebugInformation = true; - - // Exceptions handling - ExceptionsType = (TheTriple.isOSDarwin() && !TheTriple.isWatchABI()) - ? ExceptionHandling::SjLj - : ExceptionHandling::DwarfCFI; - - UseIntegratedAssembler = true; -} - ARMELFMCAsmInfo::ARMELFMCAsmInfo(const Triple &TheTriple) { if ((TheTriple.getArch() == Triple::armeb) || (TheTriple.getArch() == Triple::thumbeb)) @@ -78,29 +57,3 @@ void ARMELFMCAsmInfo::setUseIntegratedAssembler(bool Value) { DwarfRegNumForCFI = true; } } - -ARMCOFFMCAsmInfoMicrosoft::ARMCOFFMCAsmInfoMicrosoft() { - AlignmentIsInBytes = false; - - PrivateGlobalPrefix = "$M"; - PrivateLabelPrefix = "$M"; -} - -ARMCOFFMCAsmInfoGNU::ARMCOFFMCAsmInfoGNU() { - AlignmentIsInBytes = false; - HasSingleParameterDotFile = true; - - CommentString = "@"; - Code16Directive = ".code\t16"; - Code32Directive = ".code\t32"; - PrivateGlobalPrefix = ".L"; - PrivateLabelPrefix = ".L"; - - SupportsDebugInformation = true; - ExceptionsType = ExceptionHandling::None; - UseParensForSymbolVariant = true; - - UseIntegratedAssembler = false; - DwarfRegNumForCFI = true; -} - diff --git a/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.h b/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.h index 578cd591..6e981a14 100644 --- a/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.h +++ b/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.h @@ -14,18 +14,11 @@ #ifndef LLVM_LIB_TARGET_ARM_MCTARGETDESC_ARMMCASMINFO_H #define LLVM_LIB_TARGET_ARM_MCTARGETDESC_ARMMCASMINFO_H -#include "llvm/MC/MCAsmInfoCOFF.h" -#include "llvm/MC/MCAsmInfoDarwin.h" #include "llvm/MC/MCAsmInfoELF.h" namespace llvm { class Triple; -class ARMMCAsmInfoDarwin : public MCAsmInfoDarwin { -public: - explicit ARMMCAsmInfoDarwin(const Triple &TheTriple); -}; - class ARMELFMCAsmInfo : public MCAsmInfoELF { public: explicit ARMELFMCAsmInfo(const Triple &TT); @@ -33,16 +26,6 @@ class ARMELFMCAsmInfo : public MCAsmInfoELF { void setUseIntegratedAssembler(bool Value) override; }; -class ARMCOFFMCAsmInfoMicrosoft : public MCAsmInfoMicrosoft { -public: - explicit ARMCOFFMCAsmInfoMicrosoft(); -}; - -class ARMCOFFMCAsmInfoGNU : public MCAsmInfoGNUCOFF { -public: - explicit ARMCOFFMCAsmInfoGNU(); -}; - } // namespace llvm #endif diff --git a/llvm/lib/Target/ARM/MCTargetDesc/ARMMCCodeEmitter.cpp b/llvm/lib/Target/ARM/MCTargetDesc/ARMMCCodeEmitter.cpp index 78ccc6ef..a9498e9d 100644 --- a/llvm/lib/Target/ARM/MCTargetDesc/ARMMCCodeEmitter.cpp +++ b/llvm/lib/Target/ARM/MCTargetDesc/ARMMCCodeEmitter.cpp @@ -53,10 +53,6 @@ class ARMMCCodeEmitter : public MCCodeEmitter { bool isThumb2(const MCSubtargetInfo &STI) const { return isThumb(STI) && STI.getFeatureBits()[ARM::FeatureThumb2]; } - bool isTargetMachO(const MCSubtargetInfo &STI) const { - const Triple &TT = STI.getTargetTriple(); - return TT.isOSBinFormatMachO(); - } unsigned getMachineSoImmOpValue(unsigned SoImm) const; diff --git a/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp b/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp index 9529faf2..4665cd7d 100644 --- a/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp +++ b/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp @@ -182,17 +182,7 @@ static MCRegisterInfo *createARMMCRegisterInfo(const Triple &Triple) { static MCAsmInfo *createARMMCAsmInfo(const MCRegisterInfo &MRI, const Triple &TheTriple) { - MCAsmInfo *MAI; - if (TheTriple.isOSDarwin() || TheTriple.isOSBinFormatMachO()) - MAI = new ARMMCAsmInfoDarwin(TheTriple); - else if (TheTriple.isWindowsMSVCEnvironment()) - MAI = new ARMCOFFMCAsmInfoMicrosoft(); - else if (TheTriple.isOSWindows()) - MAI = new ARMCOFFMCAsmInfoGNU(); - else - MAI = new ARMELFMCAsmInfo(TheTriple); - - return MAI; + return new ARMELFMCAsmInfo(TheTriple); } // Force static initialization. diff --git a/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.h b/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.h index 2e5b7107..ba8fdbe0 100644 --- a/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.h +++ b/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.h @@ -81,21 +81,10 @@ MCAsmBackend *createThumbBEAsmBackend(const Target &T, const MCRegisterInfo &MRI, const Triple &TT, StringRef CPU); -// Construct a PE/COFF machine code streamer which will generate a PE/COFF -// object file. -MCStreamer *createARMWinCOFFStreamer(MCContext &Context, MCAsmBackend &MAB, - raw_pwrite_stream &OS, - MCCodeEmitter *Emitter, bool RelaxAll, - bool IncrementalLinkerCompatible); - /// Construct an ELF Mach-O object writer. MCObjectWriter *createARMELFObjectWriter(raw_pwrite_stream &OS, uint8_t OSABI, bool IsLittleEndian); -/// Construct an ARM PE/COFF object writer. -MCObjectWriter *createARMWinCOFFObjectWriter(raw_pwrite_stream &OS, - bool Is64Bit); - /// Construct ARM Mach-O relocation info. MCRelocationInfo *createARMMachORelocationInfo(MCContext &Ctx); } // End llvm namespace diff --git a/llvm/lib/Target/ARM/MCTargetDesc/CMakeLists.txt b/llvm/lib/Target/ARM/MCTargetDesc/CMakeLists.txt index 24218a65..54912847 100644 --- a/llvm/lib/Target/ARM/MCTargetDesc/CMakeLists.txt +++ b/llvm/lib/Target/ARM/MCTargetDesc/CMakeLists.txt @@ -6,6 +6,5 @@ add_llvm_library(LLVMARMDesc ARMMCCodeEmitter.cpp ARMMCExpr.cpp ARMMCTargetDesc.cpp - ARMWinCOFFObjectWriter.cpp ARMTargetStreamer.cpp ) diff --git a/llvm/lib/Target/PowerPC/AsmParser/PPCAsmParser.cpp b/llvm/lib/Target/PowerPC/AsmParser/PPCAsmParser.cpp index 3dad04f3..ce076190 100644 --- a/llvm/lib/Target/PowerPC/AsmParser/PPCAsmParser.cpp +++ b/llvm/lib/Target/PowerPC/AsmParser/PPCAsmParser.cpp @@ -247,13 +247,11 @@ struct PPCOperand; class PPCAsmParser : public MCTargetAsmParser { const MCInstrInfo &MII; bool IsPPC64; - bool IsDarwin; void Warning(SMLoc L, const Twine &Msg) { getParser().Warning(L, Msg); } bool Error(SMLoc L, const Twine &Msg) { return getParser().Error(L, Msg); } bool isPPC64() const { return IsPPC64; } - bool isDarwin() const { return IsDarwin; } bool MatchRegisterName(const AsmToken &Tok, unsigned &RegNo, int64_t &IntVal); @@ -264,14 +262,12 @@ class PPCAsmParser : public MCTargetAsmParser { PPCMCExpr::VariantKind &Variant); const MCExpr *FixupVariantKind(const MCExpr *E); bool ParseExpression(const MCExpr *&EVal); - bool ParseDarwinExpression(const MCExpr *&EVal); bool ParseOperand(OperandVector &Operands); bool ParseDirectiveWord(unsigned Size, SMLoc L); bool ParseDirectiveTC(unsigned Size, SMLoc L); bool ParseDirectiveMachine(SMLoc L); - bool ParseDarwinDirectiveMachine(SMLoc L); bool ParseDirectiveAbiVersion(SMLoc L); bool ParseDirectiveLocalEntry(SMLoc L); @@ -299,7 +295,6 @@ class PPCAsmParser : public MCTargetAsmParser { Triple TheTriple(STI.getTargetTriple()); IsPPC64 = (TheTriple.getArch() == Triple::ppc64 || TheTriple.getArch() == Triple::ppc64le); - IsDarwin = TheTriple.isMacOSX(); // Initialize the set of available features. setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits())); } @@ -1442,9 +1437,6 @@ FixupVariantKind(const MCExpr *E) { bool PPCAsmParser:: ParseExpression(const MCExpr *&EVal) { - if (isDarwin()) - return ParseDarwinExpression(EVal); - // (ELF Platforms) // Handle \code @l/@ha \endcode if (getParser().parseExpression(EVal)) @@ -1455,55 +1447,8 @@ ParseExpression(const MCExpr *&EVal) { PPCMCExpr::VariantKind Variant; const MCExpr *E = ExtractModifierFromExpr(EVal, Variant); if (E) - EVal = PPCMCExpr::create(Variant, E, false, getParser().getContext()); - - return false; -} - -/// ParseDarwinExpression. (MachO Platforms) -/// This differs from the default "parseExpression" in that it handles detection -/// of the \code hi16(), ha16() and lo16() \endcode modifiers. At present, -/// parseExpression() doesn't recognise the modifiers when in the Darwin/MachO -/// syntax form so it is done here. TODO: Determine if there is merit in arranging -/// for this to be done at a higher level. -bool PPCAsmParser:: -ParseDarwinExpression(const MCExpr *&EVal) { - MCAsmParser &Parser = getParser(); - PPCMCExpr::VariantKind Variant = PPCMCExpr::VK_PPC_None; - switch (getLexer().getKind()) { - default: - break; - case AsmToken::Identifier: - // Compiler-generated Darwin identifiers begin with L,l,_ or "; thus - // something starting with any other char should be part of the - // asm syntax. If handwritten asm includes an identifier like lo16, - // then all bets are off - but no-one would do that, right? - StringRef poss = Parser.getTok().getString(); - if (poss.equals_lower("lo16")) { - Variant = PPCMCExpr::VK_PPC_LO; - } else if (poss.equals_lower("hi16")) { - Variant = PPCMCExpr::VK_PPC_HI; - } else if (poss.equals_lower("ha16")) { - Variant = PPCMCExpr::VK_PPC_HA; - } - if (Variant != PPCMCExpr::VK_PPC_None) { - Parser.Lex(); // Eat the xx16 - if (getLexer().isNot(AsmToken::LParen)) - return Error(Parser.getTok().getLoc(), "expected '('"); - Parser.Lex(); // Eat the '(' - } - break; - } - - if (getParser().parseExpression(EVal)) - return true; + EVal = PPCMCExpr::create(Variant, E, getParser().getContext()); - if (Variant != PPCMCExpr::VK_PPC_None) { - if (getLexer().isNot(AsmToken::RParen)) - return Error(Parser.getTok().getLoc(), "expected ')'"); - Parser.Lex(); // Eat the ')' - EVal = PPCMCExpr::create(Variant, EVal, false, getParser().getContext()); - } return false; } @@ -1531,22 +1476,9 @@ bool PPCAsmParser::ParseOperand(OperandVector &Operands) { } return Error(S, "invalid register name"); - case AsmToken::Identifier: - // Note that non-register-name identifiers from the compiler will begin - // with '_', 'L'/'l' or '"'. Of course, handwritten asm could include - // identifiers like r31foo - so we fall through in the event that parsing - // a register name fails. - if (isDarwin()) { - unsigned RegNo; - int64_t IntVal; - if (!MatchRegisterName(Parser.getTok(), RegNo, IntVal)) { - Parser.Lex(); // Eat the identifier token. - Operands.push_back(PPCOperand::CreateImm(IntVal, S, E, isPPC64())); - return false; - } - } // Fall-through to process non-register-name identifiers as expression. // All other expressions + case AsmToken::Identifier: case AsmToken::LParen: case AsmToken::Plus: case AsmToken::Minus: @@ -1601,24 +1533,9 @@ bool PPCAsmParser::ParseOperand(OperandVector &Operands) { break; case AsmToken::Integer: - if (!isDarwin()) { - if (getParser().parseAbsoluteExpression(IntVal) || - IntVal < 0 || IntVal > 31) - return Error(S, "invalid register number"); - } else { - return Error(S, "unexpected integer value"); - } - break; - - case AsmToken::Identifier: - if (isDarwin()) { - unsigned RegNo; - if (!MatchRegisterName(Parser.getTok(), RegNo, IntVal)) { - Parser.Lex(); // Eat the identifier token. - break; - } - } - // Fall-through.. + if (getParser().parseAbsoluteExpression(IntVal) || + IntVal < 0 || IntVal > 31) + return Error(S, "invalid register number"); default: return Error(S, "invalid memory operand"); @@ -1712,23 +1629,18 @@ bool PPCAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name, /// ParseDirective parses the PPC specific directives bool PPCAsmParser::ParseDirective(AsmToken DirectiveID) { StringRef IDVal = DirectiveID.getIdentifier(); - if (!isDarwin()) { - if (IDVal == ".word") - return ParseDirectiveWord(2, DirectiveID.getLoc()); - if (IDVal == ".llong") - return ParseDirectiveWord(8, DirectiveID.getLoc()); - if (IDVal == ".tc") - return ParseDirectiveTC(isPPC64()? 8 : 4, DirectiveID.getLoc()); - if (IDVal == ".machine") - return ParseDirectiveMachine(DirectiveID.getLoc()); - if (IDVal == ".abiversion") - return ParseDirectiveAbiVersion(DirectiveID.getLoc()); - if (IDVal == ".localentry") - return ParseDirectiveLocalEntry(DirectiveID.getLoc()); - } else { - if (IDVal == ".machine") - return ParseDarwinDirectiveMachine(DirectiveID.getLoc()); - } + if (IDVal == ".word") + return ParseDirectiveWord(2, DirectiveID.getLoc()); + if (IDVal == ".llong") + return ParseDirectiveWord(8, DirectiveID.getLoc()); + if (IDVal == ".tc") + return ParseDirectiveTC(isPPC64()? 8 : 4, DirectiveID.getLoc()); + if (IDVal == ".machine") + return ParseDirectiveMachine(DirectiveID.getLoc()); + if (IDVal == ".abiversion") + return ParseDirectiveAbiVersion(DirectiveID.getLoc()); + if (IDVal == ".localentry") + return ParseDirectiveLocalEntry(DirectiveID.getLoc()); return true; } @@ -1822,44 +1734,6 @@ bool PPCAsmParser::ParseDirectiveMachine(SMLoc L) { return false; } -/// ParseDarwinDirectiveMachine (Mach-o platforms) -/// ::= .machine cpu-identifier -bool PPCAsmParser::ParseDarwinDirectiveMachine(SMLoc L) { - MCAsmParser &Parser = getParser(); - if (getLexer().isNot(AsmToken::Identifier) && - getLexer().isNot(AsmToken::String)) { - Error(L, "unexpected token in directive"); - return false; - } - - StringRef CPU = Parser.getTok().getIdentifier(); - Parser.Lex(); - - // FIXME: this is only the 'default' set of cpu variants. - // However we don't act on this information at present, this is simply - // allowing parsing to proceed with minimal sanity checking. - if (CPU != "ppc7400" && CPU != "ppc" && CPU != "ppc64") { - Error(L, "unrecognized cpu type"); - return false; - } - - if (isPPC64() && (CPU == "ppc7400" || CPU == "ppc")) { - Error(L, "wrong cpu type specified for 64bit"); - return false; - } - if (!isPPC64() && CPU == "ppc64") { - Error(L, "wrong cpu type specified for 32bit"); - return false; - } - - if (getLexer().isNot(AsmToken::EndOfStatement)) { - Error(L, "unexpected token in directive"); - return false; - } - - return false; -} - /// ParseDirectiveAbiVersion /// ::= .abiversion constant-expression bool PPCAsmParser::ParseDirectiveAbiVersion(SMLoc L) { @@ -1962,19 +1836,19 @@ PPCAsmParser::applyModifierToExpr(const MCExpr *E, MCContext &Ctx) { switch (Variant) { case MCSymbolRefExpr::VK_PPC_LO: - return PPCMCExpr::create(PPCMCExpr::VK_PPC_LO, E, false, Ctx); + return PPCMCExpr::create(PPCMCExpr::VK_PPC_LO, E, Ctx); case MCSymbolRefExpr::VK_PPC_HI: - return PPCMCExpr::create(PPCMCExpr::VK_PPC_HI, E, false, Ctx); + return PPCMCExpr::create(PPCMCExpr::VK_PPC_HI, E, Ctx); case MCSymbolRefExpr::VK_PPC_HA: - return PPCMCExpr::create(PPCMCExpr::VK_PPC_HA, E, false, Ctx); + return PPCMCExpr::create(PPCMCExpr::VK_PPC_HA, E, Ctx); case MCSymbolRefExpr::VK_PPC_HIGHER: - return PPCMCExpr::create(PPCMCExpr::VK_PPC_HIGHER, E, false, Ctx); + return PPCMCExpr::create(PPCMCExpr::VK_PPC_HIGHER, E, Ctx); case MCSymbolRefExpr::VK_PPC_HIGHERA: - return PPCMCExpr::create(PPCMCExpr::VK_PPC_HIGHERA, E, false, Ctx); + return PPCMCExpr::create(PPCMCExpr::VK_PPC_HIGHERA, E, Ctx); case MCSymbolRefExpr::VK_PPC_HIGHEST: - return PPCMCExpr::create(PPCMCExpr::VK_PPC_HIGHEST, E, false, Ctx); + return PPCMCExpr::create(PPCMCExpr::VK_PPC_HIGHEST, E, Ctx); case MCSymbolRefExpr::VK_PPC_HIGHESTA: - return PPCMCExpr::create(PPCMCExpr::VK_PPC_HIGHESTA, E, false, Ctx); + return PPCMCExpr::create(PPCMCExpr::VK_PPC_HIGHESTA, E, Ctx); default: return nullptr; } diff --git a/llvm/lib/Target/PowerPC/MCTargetDesc/PPCAsmBackend.cpp b/llvm/lib/Target/PowerPC/MCTargetDesc/PPCAsmBackend.cpp index c56b1e38..039cc555 100644 --- a/llvm/lib/Target/PowerPC/MCTargetDesc/PPCAsmBackend.cpp +++ b/llvm/lib/Target/PowerPC/MCTargetDesc/PPCAsmBackend.cpp @@ -14,12 +14,10 @@ #include "llvm/MC/MCELFObjectWriter.h" #include "llvm/MC/MCFixupKindInfo.h" #include "llvm/MC/MCObjectWriter.h" -#include "llvm/MC/MCSectionMachO.h" #include "llvm/MC/MCSymbolELF.h" #include "llvm/MC/MCValue.h" #include "llvm/Support/ELF.h" #include "llvm/Support/ErrorHandling.h" -#include "llvm/Support/MachO.h" #include "llvm/Support/TargetRegistry.h" using namespace llvm; diff --git a/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.cpp b/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.cpp index 2cdfce0a..89474e6d 100644 --- a/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.cpp +++ b/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.cpp @@ -16,30 +16,6 @@ using namespace llvm; -PPCMCAsmInfoDarwin::PPCMCAsmInfoDarwin(bool is64Bit, const Triple& T) { - if (is64Bit) { - PointerSize = CalleeSaveStackSlotSize = 8; - } - IsLittleEndian = false; - - CommentString = ";"; - ExceptionsType = ExceptionHandling::DwarfCFI; - - if (!is64Bit) - Data64bitsDirective = nullptr; // We can't emit a 64-bit unit in PPC32 mode. - - AssemblerDialect = 1; // New-Style mnemonics. - SupportsDebugInformation= true; // Debug information. - - // The installed assembler for OSX < 10.6 lacks some directives. - // FIXME: this should really be a check on the assembler characteristics - // rather than OS version - if (T.isMacOSX() && T.isMacOSXVersionLT(10, 6)) - HasWeakDefCanBeHiddenDirective = false; - - UseIntegratedAssembler = true; -} - PPCELFMCAsmInfo::PPCELFMCAsmInfo(bool is64Bit, const Triple& T) { // FIXME: This is not always needed. For example, it is not needed in the // v2 abi. diff --git a/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.h b/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.h index 796c1116..4bf9b8bc 100644 --- a/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.h +++ b/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.h @@ -14,17 +14,11 @@ #ifndef LLVM_LIB_TARGET_POWERPC_MCTARGETDESC_PPCMCASMINFO_H #define LLVM_LIB_TARGET_POWERPC_MCTARGETDESC_PPCMCASMINFO_H -#include "llvm/MC/MCAsmInfoDarwin.h" #include "llvm/MC/MCAsmInfoELF.h" namespace llvm { class Triple; -class PPCMCAsmInfoDarwin : public MCAsmInfoDarwin { -public: - explicit PPCMCAsmInfoDarwin(bool is64Bit, const Triple &); -}; - class PPCELFMCAsmInfo : public MCAsmInfoELF { public: explicit PPCELFMCAsmInfo(bool is64Bit, const Triple &); diff --git a/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCExpr.cpp b/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCExpr.cpp index 6b97d4c1..e7925857 100644 --- a/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCExpr.cpp +++ b/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCExpr.cpp @@ -20,35 +20,22 @@ using namespace llvm; const PPCMCExpr* PPCMCExpr::create(VariantKind Kind, const MCExpr *Expr, - bool isDarwin, MCContext &Ctx) { - return new (Ctx) PPCMCExpr(Kind, Expr, isDarwin); + MCContext &Ctx) { + return new (Ctx) PPCMCExpr(Kind, Expr); } void PPCMCExpr::printImpl(raw_ostream &OS, const MCAsmInfo *MAI) const { - if (isDarwinSyntax()) { - switch (Kind) { - default: llvm_unreachable("Invalid kind!"); - case VK_PPC_LO: OS << "lo16"; break; - case VK_PPC_HI: OS << "hi16"; break; - case VK_PPC_HA: OS << "ha16"; break; - } - - OS << '('; - getSubExpr()->print(OS, MAI); - OS << ')'; - } else { - getSubExpr()->print(OS, MAI); + getSubExpr()->print(OS, MAI); - switch (Kind) { - default: llvm_unreachable("Invalid kind!"); - case VK_PPC_LO: OS << "@l"; break; - case VK_PPC_HI: OS << "@h"; break; - case VK_PPC_HA: OS << "@ha"; break; - case VK_PPC_HIGHER: OS << "@higher"; break; - case VK_PPC_HIGHERA: OS << "@highera"; break; - case VK_PPC_HIGHEST: OS << "@highest"; break; - case VK_PPC_HIGHESTA: OS << "@highesta"; break; - } + switch (Kind) { + default: llvm_unreachable("Invalid kind!"); + case VK_PPC_LO: OS << "@l"; break; + case VK_PPC_HI: OS << "@h"; break; + case VK_PPC_HA: OS << "@ha"; break; + case VK_PPC_HIGHER: OS << "@higher"; break; + case VK_PPC_HIGHERA: OS << "@highera"; break; + case VK_PPC_HIGHEST: OS << "@highest"; break; + case VK_PPC_HIGHESTA: OS << "@highesta"; break; } } diff --git a/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCExpr.h b/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCExpr.h index d42a111c..a6b50567 100644 --- a/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCExpr.h +++ b/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCExpr.h @@ -32,33 +32,32 @@ class PPCMCExpr : public MCTargetExpr { private: const VariantKind Kind; const MCExpr *Expr; - bool IsDarwin; int64_t evaluateAsInt64(int64_t Value) const; - explicit PPCMCExpr(VariantKind Kind, const MCExpr *Expr, bool IsDarwin) - : Kind(Kind), Expr(Expr), IsDarwin(IsDarwin) {} + explicit PPCMCExpr(VariantKind Kind, const MCExpr *Expr) + : Kind(Kind), Expr(Expr) {} public: /// @name Construction /// @{ static const PPCMCExpr *create(VariantKind Kind, const MCExpr *Expr, - bool isDarwin, MCContext &Ctx); + MCContext &Ctx); static const PPCMCExpr *createLo(const MCExpr *Expr, - bool isDarwin, MCContext &Ctx) { - return create(VK_PPC_LO, Expr, isDarwin, Ctx); + MCContext &Ctx) { + return create(VK_PPC_LO, Expr, Ctx); } static const PPCMCExpr *createHi(const MCExpr *Expr, - bool isDarwin, MCContext &Ctx) { - return create(VK_PPC_HI, Expr, isDarwin, Ctx); + MCContext &Ctx) { + return create(VK_PPC_HI, Expr, Ctx); } static const PPCMCExpr *createHa(const MCExpr *Expr, - bool isDarwin, MCContext &Ctx) { - return create(VK_PPC_HA, Expr, isDarwin, Ctx); + MCContext &Ctx) { + return create(VK_PPC_HA, Expr, Ctx); } /// @} @@ -71,10 +70,6 @@ class PPCMCExpr : public MCTargetExpr { /// getSubExpr - Get the child of this expression. const MCExpr *getSubExpr() const { return Expr; } - /// isDarwinSyntax - True if expression is to be printed using Darwin syntax. - bool isDarwinSyntax() const { return IsDarwin; } - - /// @} void printImpl(raw_ostream &OS, const MCAsmInfo *MAI) const override; diff --git a/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.cpp b/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.cpp index d08a8113..a23dc724 100644 --- a/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.cpp +++ b/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.cpp @@ -71,11 +71,7 @@ static MCAsmInfo *createPPCMCAsmInfo(const MCRegisterInfo &MRI, bool isPPC64 = (TheTriple.getArch() == Triple::ppc64 || TheTriple.getArch() == Triple::ppc64le); - MCAsmInfo *MAI; - if (TheTriple.isOSDarwin()) - MAI = new PPCMCAsmInfoDarwin(isPPC64, TheTriple); - else - MAI = new PPCELFMCAsmInfo(isPPC64, TheTriple); + MCAsmInfo *MAI = new PPCELFMCAsmInfo(isPPC64, TheTriple); // Initial state of the frame pointer is R1. unsigned Reg = isPPC64 ? PPC::X1 : PPC::R1; @@ -175,24 +171,6 @@ class PPCTargetELFStreamer : public PPCTargetStreamer { Symbol->setOther(Other); } }; - -class PPCTargetMachOStreamer : public PPCTargetStreamer { -public: - PPCTargetMachOStreamer(MCStreamer &S) : PPCTargetStreamer(S) {} - void emitTCEntry(const MCSymbol &S) override { - llvm_unreachable("Unknown pseudo-op: .tc"); - } - void emitMachine(StringRef CPU) override { - // FIXME: We should update the CPUType, CPUSubType in the Object file if - // the new values are different from the defaults. - } - void emitAbiVersion(int AbiVersion) override { - llvm_unreachable("Unknown pseudo-op: .abiversion"); - } - void emitLocalEntry(MCSymbolELF *S, const MCExpr *LocalOffset) override { - llvm_unreachable("Unknown pseudo-op: .localentry"); - } -}; } extern "C" void LLVMInitializePowerPCTargetMC() { diff --git a/llvm/lib/Target/X86/MCTargetDesc/CMakeLists.txt b/llvm/lib/Target/X86/MCTargetDesc/CMakeLists.txt index 49b3d4ac..3924ed6a 100644 --- a/llvm/lib/Target/X86/MCTargetDesc/CMakeLists.txt +++ b/llvm/lib/Target/X86/MCTargetDesc/CMakeLists.txt @@ -5,5 +5,4 @@ add_llvm_library(LLVMX86Desc X86MCCodeEmitter.cpp X86MachObjectWriter.cpp X86ELFObjectWriter.cpp - X86WinCOFFObjectWriter.cpp ) diff --git a/llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp b/llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp index 985b139b..100a9954 100644 --- a/llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp +++ b/llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp @@ -17,12 +17,9 @@ #include "llvm/MC/MCInst.h" #include "llvm/MC/MCObjectWriter.h" #include "llvm/MC/MCRegisterInfo.h" -#include "llvm/MC/MCSectionCOFF.h" #include "llvm/MC/MCSectionELF.h" -#include "llvm/MC/MCSectionMachO.h" #include "llvm/Support/ELF.h" #include "llvm/Support/ErrorHandling.h" -#include "llvm/Support/MachO.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; @@ -437,327 +434,6 @@ namespace CU { }; } // end CU namespace - -class DarwinX86AsmBackend : public X86AsmBackend { - const MCRegisterInfo &MRI; - - /// \brief Number of registers that can be saved in a compact unwind encoding. - enum { CU_NUM_SAVED_REGS = 6 }; - - mutable unsigned SavedRegs[CU_NUM_SAVED_REGS]; - bool Is64Bit; - - unsigned OffsetSize; ///< Offset of a "push" instruction. - unsigned MoveInstrSize; ///< Size of a "move" instruction. - unsigned StackDivide; ///< Amount to adjust stack size by. -protected: - /// \brief Size of a "push" instruction for the given register. - unsigned PushInstrSize(unsigned Reg) const { - switch (Reg) { - case X86::EBX: - case X86::ECX: - case X86::EDX: - case X86::EDI: - case X86::ESI: - case X86::EBP: - case X86::RBX: - case X86::RBP: - return 1; - case X86::R12: - case X86::R13: - case X86::R14: - case X86::R15: - return 2; - } - return 1; - } - - /// \brief Implementation of algorithm to generate the compact unwind encoding - /// for the CFI instructions. - uint32_t - generateCompactUnwindEncodingImpl(ArrayRef Instrs) const { - if (Instrs.empty()) return 0; - - // Reset the saved registers. - unsigned SavedRegIdx = 0; - memset(SavedRegs, 0, sizeof(SavedRegs)); - - bool HasFP = false; - - // Encode that we are using EBP/RBP as the frame pointer. - uint32_t CompactUnwindEncoding = 0; - - unsigned SubtractInstrIdx = Is64Bit ? 3 : 2; - unsigned InstrOffset = 0; - unsigned StackAdjust = 0; - unsigned StackSize = 0; - unsigned PrevStackSize = 0; - unsigned NumDefCFAOffsets = 0; - - for (unsigned i = 0, e = Instrs.size(); i != e; ++i) { - const MCCFIInstruction &Inst = Instrs[i]; - - switch (Inst.getOperation()) { - default: - // Any other CFI directives indicate a frame that we aren't prepared - // to represent via compact unwind, so just bail out. - return 0; - case MCCFIInstruction::OpDefCfaRegister: { - // Defines a frame pointer. E.g. - // - // movq %rsp, %rbp - // L0: - // .cfi_def_cfa_register %rbp - // - HasFP = true; - assert(MRI.getLLVMRegNum(Inst.getRegister(), true) == - (Is64Bit ? X86::RBP : X86::EBP) && "Invalid frame pointer!"); - - // Reset the counts. - memset(SavedRegs, 0, sizeof(SavedRegs)); - StackAdjust = 0; - SavedRegIdx = 0; - InstrOffset += MoveInstrSize; - break; - } - case MCCFIInstruction::OpDefCfaOffset: { - // Defines a new offset for the CFA. E.g. - // - // With frame: - // - // pushq %rbp - // L0: - // .cfi_def_cfa_offset 16 - // - // Without frame: - // - // subq $72, %rsp - // L0: - // .cfi_def_cfa_offset 80 - // - PrevStackSize = StackSize; - StackSize = std::abs(Inst.getOffset()) / StackDivide; - ++NumDefCFAOffsets; - break; - } - case MCCFIInstruction::OpOffset: { - // Defines a "push" of a callee-saved register. E.g. - // - // pushq %r15 - // pushq %r14 - // pushq %rbx - // L0: - // subq $120, %rsp - // L1: - // .cfi_offset %rbx, -40 - // .cfi_offset %r14, -32 - // .cfi_offset %r15, -24 - // - if (SavedRegIdx == CU_NUM_SAVED_REGS) - // If there are too many saved registers, we cannot use a compact - // unwind encoding. - return CU::UNWIND_MODE_DWARF; - - unsigned Reg = MRI.getLLVMRegNum(Inst.getRegister(), true); - SavedRegs[SavedRegIdx++] = Reg; - StackAdjust += OffsetSize; - InstrOffset += PushInstrSize(Reg); - break; - } - } - } - - StackAdjust /= StackDivide; - - if (HasFP) { - if ((StackAdjust & 0xFF) != StackAdjust) - // Offset was too big for a compact unwind encoding. - return CU::UNWIND_MODE_DWARF; - - // Get the encoding of the saved registers when we have a frame pointer. - uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame(); - if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF; - - CompactUnwindEncoding |= CU::UNWIND_MODE_BP_FRAME; - CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16; - CompactUnwindEncoding |= RegEnc & CU::UNWIND_BP_FRAME_REGISTERS; - } else { - // If the amount of the stack allocation is the size of a register, then - // we "push" the RAX/EAX register onto the stack instead of adjusting the - // stack pointer with a SUB instruction. We don't support the push of the - // RAX/EAX register with compact unwind. So we check for that situation - // here. - if ((NumDefCFAOffsets == SavedRegIdx + 1 && - StackSize - PrevStackSize == 1) || - (Instrs.size() == 1 && NumDefCFAOffsets == 1 && StackSize == 2)) - return CU::UNWIND_MODE_DWARF; - - SubtractInstrIdx += InstrOffset; - ++StackAdjust; - - if ((StackSize & 0xFF) == StackSize) { - // Frameless stack with a small stack size. - CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IMMD; - - // Encode the stack size. - CompactUnwindEncoding |= (StackSize & 0xFF) << 16; - } else { - if ((StackAdjust & 0x7) != StackAdjust) - // The extra stack adjustments are too big for us to handle. - return CU::UNWIND_MODE_DWARF; - - // Frameless stack with an offset too large for us to encode compactly. - CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IND; - - // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP' - // instruction. - CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16; - - // Encode any extra stack stack adjustments (done via push - // instructions). - CompactUnwindEncoding |= (StackAdjust & 0x7) << 13; - } - - // Encode the number of registers saved. (Reverse the list first.) - std::reverse(&SavedRegs[0], &SavedRegs[SavedRegIdx]); - CompactUnwindEncoding |= (SavedRegIdx & 0x7) << 10; - - // Get the encoding of the saved registers when we don't have a frame - // pointer. - uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegIdx); - if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF; - - // Encode the register encoding. - CompactUnwindEncoding |= - RegEnc & CU::UNWIND_FRAMELESS_STACK_REG_PERMUTATION; - } - - return CompactUnwindEncoding; - } - -private: - /// \brief Get the compact unwind number for a given register. The number - /// corresponds to the enum lists in compact_unwind_encoding.h. - int getCompactUnwindRegNum(unsigned Reg) const { - static const MCPhysReg CU32BitRegs[7] = { - X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0 - }; - static const MCPhysReg CU64BitRegs[] = { - X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0 - }; - const MCPhysReg *CURegs = Is64Bit ? CU64BitRegs : CU32BitRegs; - for (int Idx = 1; *CURegs; ++CURegs, ++Idx) - if (*CURegs == Reg) - return Idx; - - return -1; - } - - /// \brief Return the registers encoded for a compact encoding with a frame - /// pointer. - uint32_t encodeCompactUnwindRegistersWithFrame() const { - // Encode the registers in the order they were saved --- 3-bits per - // register. The list of saved registers is assumed to be in reverse - // order. The registers are numbered from 1 to CU_NUM_SAVED_REGS. - uint32_t RegEnc = 0; - for (int i = 0, Idx = 0; i != CU_NUM_SAVED_REGS; ++i) { - unsigned Reg = SavedRegs[i]; - if (Reg == 0) break; - - int CURegNum = getCompactUnwindRegNum(Reg); - if (CURegNum == -1) return ~0U; - - // Encode the 3-bit register number in order, skipping over 3-bits for - // each register. - RegEnc |= (CURegNum & 0x7) << (Idx++ * 3); - } - - assert((RegEnc & 0x3FFFF) == RegEnc && - "Invalid compact register encoding!"); - return RegEnc; - } - - /// \brief Create the permutation encoding used with frameless stacks. It is - /// passed the number of registers to be saved and an array of the registers - /// saved. - uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned RegCount) const { - // The saved registers are numbered from 1 to 6. In order to encode the - // order in which they were saved, we re-number them according to their - // place in the register order. The re-numbering is relative to the last - // re-numbered register. E.g., if we have registers {6, 2, 4, 5} saved in - // that order: - // - // Orig Re-Num - // ---- ------ - // 6 6 - // 2 2 - // 4 3 - // 5 3 - // - for (unsigned i = 0; i < RegCount; ++i) { - int CUReg = getCompactUnwindRegNum(SavedRegs[i]); - if (CUReg == -1) return ~0U; - SavedRegs[i] = CUReg; - } - - // Reverse the list. - std::reverse(&SavedRegs[0], &SavedRegs[CU_NUM_SAVED_REGS]); - - uint32_t RenumRegs[CU_NUM_SAVED_REGS]; - for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i){ - unsigned Countless = 0; - for (unsigned j = CU_NUM_SAVED_REGS - RegCount; j < i; ++j) - if (SavedRegs[j] < SavedRegs[i]) - ++Countless; - - RenumRegs[i] = SavedRegs[i] - Countless - 1; - } - - // Take the renumbered values and encode them into a 10-bit number. - uint32_t permutationEncoding = 0; - switch (RegCount) { - case 6: - permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1] - + 6 * RenumRegs[2] + 2 * RenumRegs[3] - + RenumRegs[4]; - break; - case 5: - permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2] - + 6 * RenumRegs[3] + 2 * RenumRegs[4] - + RenumRegs[5]; - break; - case 4: - permutationEncoding |= 60 * RenumRegs[2] + 12 * RenumRegs[3] - + 3 * RenumRegs[4] + RenumRegs[5]; - break; - case 3: - permutationEncoding |= 20 * RenumRegs[3] + 4 * RenumRegs[4] - + RenumRegs[5]; - break; - case 2: - permutationEncoding |= 5 * RenumRegs[4] + RenumRegs[5]; - break; - case 1: - permutationEncoding |= RenumRegs[5]; - break; - } - - assert((permutationEncoding & 0x3FF) == permutationEncoding && - "Invalid compact register encoding!"); - return permutationEncoding; - } - -public: - DarwinX86AsmBackend(const Target &T, const MCRegisterInfo &MRI, StringRef CPU, - bool Is64Bit) - : X86AsmBackend(T, CPU), MRI(MRI), Is64Bit(Is64Bit) { - memset(SavedRegs, 0, sizeof(SavedRegs)); - OffsetSize = Is64Bit ? 8 : 4; - MoveInstrSize = Is64Bit ? 3 : 2; - StackDivide = Is64Bit ? 8 : 4; - } -}; - } // end anonymous namespace MCAsmBackend *llvm::createX86_32AsmBackend(const Target &T, diff --git a/llvm/lib/Target/X86/MCTargetDesc/X86BaseInfo.h b/llvm/lib/Target/X86/MCTargetDesc/X86BaseInfo.h index 9ff85b91..94c7a048 100644 --- a/llvm/lib/Target/X86/MCTargetDesc/X86BaseInfo.h +++ b/llvm/lib/Target/X86/MCTargetDesc/X86BaseInfo.h @@ -217,13 +217,7 @@ namespace X86II { /// is some TLS offset from the picbase. /// /// This is the 32-bit TLS offset for Darwin TLS in PIC mode. - MO_TLVP_PIC_BASE, - - /// MO_SECREL - On a symbol operand this indicates that the immediate is - /// the offset from beginning of section. - /// - /// This is the TLS offset for the COFF/Windows TLS mechanism. - MO_SECREL + MO_TLVP_PIC_BASE }; enum : uint64_t { diff --git a/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.cpp b/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.cpp index 1e9c8b6b..b1a69579 100644 --- a/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.cpp +++ b/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.cpp @@ -29,51 +29,6 @@ enum AsmWriterFlavorTy { static AsmWriterFlavorTy AsmWriterFlavor = Intel; // ATT -static bool MarkedJTDataRegions = false; - -X86MCAsmInfoDarwin::X86MCAsmInfoDarwin(const Triple &T) { - bool is64Bit = T.getArch() == Triple::x86_64; - if (is64Bit) - PointerSize = CalleeSaveStackSlotSize = 8; - - AssemblerDialect = AsmWriterFlavor; - - TextAlignFillValue = 0x90; - - if (!is64Bit) - Data64bitsDirective = nullptr; // we can't emit a 64-bit unit - - // Use ## as a comment string so that .s files generated by llvm can go - // through the GCC preprocessor without causing an error. This is needed - // because "clang foo.s" runs the C preprocessor, which is usually reserved - // for .S files on other systems. Perhaps this is because the file system - // wasn't always case preserving or something. - CommentString = "##"; - - SupportsDebugInformation = true; - UseDataRegionDirectives = MarkedJTDataRegions; - - // Exceptions handling - ExceptionsType = ExceptionHandling::DwarfCFI; - - // old assembler lacks some directives - // FIXME: this should really be a check on the assembler characteristics - // rather than OS version - if (T.isMacOSX() && T.isMacOSXVersionLT(10, 6)) - HasWeakDefCanBeHiddenDirective = false; - - // Assume ld64 is new enough that the abs-ified FDE relocs may be used - // (actually, must, since otherwise the non-extern relocations we produce - // overwhelm ld64's tiny little mind and it fails). - DwarfFDESymbolsUseAbsDiff = true; - - UseIntegratedAssembler = true; -} - -X86_64MCAsmInfoDarwin::X86_64MCAsmInfoDarwin(const Triple &Triple) - : X86MCAsmInfoDarwin(Triple) { -} - X86ELFMCAsmInfo::X86ELFMCAsmInfo(const Triple &T) { bool is64Bit = T.getArch() == Triple::x86_64; bool isX32 = T.getEnvironment() == Triple::GNUX32; @@ -100,57 +55,3 @@ X86ELFMCAsmInfo::X86ELFMCAsmInfo(const Triple &T) { // Clang also enabled it when the OS is Solaris but that is redundant here. UseIntegratedAssembler = true; } - -const MCExpr * -X86_64MCAsmInfoDarwin::getExprForPersonalitySymbol(const MCSymbol *Sym, - unsigned Encoding, - MCStreamer &Streamer) const { - MCContext &Context = Streamer.getContext(); - const MCExpr *Res = - MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_GOTPCREL, Context); - const MCExpr *Four = MCConstantExpr::create(4, Context); - return MCBinaryExpr::createAdd(Res, Four, Context); -} - -X86MCAsmInfoMicrosoft::X86MCAsmInfoMicrosoft(const Triple &Triple) { - if (Triple.getArch() == Triple::x86_64) { - PrivateGlobalPrefix = ".L"; - PrivateLabelPrefix = ".L"; - PointerSize = 8; - WinEHEncodingType = WinEH::EncodingType::Itanium; - } else { - // 32-bit X86 doesn't use CFI, so this isn't a real encoding type. It's just - // a place holder that the Windows EHStreamer looks for to suppress CFI - // output. In particular, usesWindowsCFI() returns false. - WinEHEncodingType = WinEH::EncodingType::X86; - } - - ExceptionsType = ExceptionHandling::WinEH; - - AssemblerDialect = AsmWriterFlavor; - - TextAlignFillValue = 0x90; - - AllowAtInName = true; - - UseIntegratedAssembler = true; -} - -X86MCAsmInfoGNUCOFF::X86MCAsmInfoGNUCOFF(const Triple &Triple) { - assert(Triple.isOSWindows() && "Windows is the only supported COFF target"); - if (Triple.getArch() == Triple::x86_64) { - PrivateGlobalPrefix = ".L"; - PrivateLabelPrefix = ".L"; - PointerSize = 8; - WinEHEncodingType = WinEH::EncodingType::Itanium; - ExceptionsType = ExceptionHandling::WinEH; - } else { - ExceptionsType = ExceptionHandling::DwarfCFI; - } - - AssemblerDialect = AsmWriterFlavor; - - TextAlignFillValue = 0x90; - - UseIntegratedAssembler = true; -} diff --git a/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.h b/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.h index 6e070833..b2fc9355 100644 --- a/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.h +++ b/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.h @@ -15,39 +15,15 @@ #define LLVM_LIB_TARGET_X86_MCTARGETDESC_X86MCASMINFO_H #include "llvm/MC/MCAsmInfo.h" -#include "llvm/MC/MCAsmInfoCOFF.h" -#include "llvm/MC/MCAsmInfoDarwin.h" #include "llvm/MC/MCAsmInfoELF.h" namespace llvm { class Triple; -class X86MCAsmInfoDarwin : public MCAsmInfoDarwin { -public: - explicit X86MCAsmInfoDarwin(const Triple &Triple); -}; - -struct X86_64MCAsmInfoDarwin : public X86MCAsmInfoDarwin { - explicit X86_64MCAsmInfoDarwin(const Triple &Triple); - const MCExpr * - getExprForPersonalitySymbol(const MCSymbol *Sym, unsigned Encoding, - MCStreamer &Streamer) const override; -}; - class X86ELFMCAsmInfo : public MCAsmInfoELF { public: explicit X86ELFMCAsmInfo(const Triple &Triple); }; - -class X86MCAsmInfoMicrosoft : public MCAsmInfoMicrosoft { -public: - explicit X86MCAsmInfoMicrosoft(const Triple &Triple); -}; - -class X86MCAsmInfoGNUCOFF : public MCAsmInfoGNUCOFF { -public: - explicit X86MCAsmInfoGNUCOFF(const Triple &Triple); -}; } // namespace llvm #endif diff --git a/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.cpp b/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.cpp index 46f3e0dc..c0e46dd6 100644 --- a/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.cpp +++ b/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.cpp @@ -54,8 +54,6 @@ unsigned X86_MC::getDwarfRegFlavour(const Triple &TT, bool isEH) { if (TT.getArch() == Triple::x86_64) return DWARFFlavour::X86_64; - if (TT.isOSDarwin()) - return isEH ? DWARFFlavour::X86_32_DarwinEH : DWARFFlavour::X86_32_Generic; if (TT.isOSCygMing()) // Unsupported by now, just quick fallback return DWARFFlavour::X86_32_Generic; @@ -109,25 +107,7 @@ static MCAsmInfo *createX86MCAsmInfo(const MCRegisterInfo &MRI, const Triple &TheTriple) { bool is64Bit = TheTriple.getArch() == Triple::x86_64; - MCAsmInfo *MAI; - if (TheTriple.isOSBinFormatMachO()) { - if (is64Bit) - MAI = new X86_64MCAsmInfoDarwin(TheTriple); - else - MAI = new X86MCAsmInfoDarwin(TheTriple); - } else if (TheTriple.isOSBinFormatELF()) { - // Force the use of an ELF container. - MAI = new X86ELFMCAsmInfo(TheTriple); - } else if (TheTriple.isWindowsMSVCEnvironment() || - TheTriple.isWindowsCoreCLREnvironment()) { - MAI = new X86MCAsmInfoMicrosoft(TheTriple); - } else if (TheTriple.isOSCygMing() || - TheTriple.isWindowsItaniumEnvironment()) { - MAI = new X86MCAsmInfoGNUCOFF(TheTriple); - } else { - // The default is ELF. - MAI = new X86ELFMCAsmInfo(TheTriple); - } + MCAsmInfo *MAI = new X86ELFMCAsmInfo(TheTriple); // Initialize initial frame state. // Calculate amount of bytes used for return address storing diff --git a/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.h b/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.h index ddea7844..82dec5ab 100644 --- a/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.h +++ b/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.h @@ -74,14 +74,6 @@ MCAsmBackend *createX86_32AsmBackend(const Target &T, const MCRegisterInfo &MRI, MCAsmBackend *createX86_64AsmBackend(const Target &T, const MCRegisterInfo &MRI, const Triple &TT, StringRef CPU); -/// Construct an X86 Windows COFF machine code streamer which will generate -/// PE/COFF format object files. -/// -/// Takes ownership of \p AB and \p CE. -MCStreamer *createX86WinCOFFStreamer(MCContext &C, MCAsmBackend &AB, - raw_pwrite_stream &OS, MCCodeEmitter *CE, - bool RelaxAll, bool IncrementalLinkerCompatible); - /// Construct an X86 Mach-O object writer. MCObjectWriter *createX86MachObjectWriter(raw_pwrite_stream &OS, bool Is64Bit, uint32_t CPUType,