Index: head/contrib/llvm/include/llvm/CodeGen/AsmPrinter.h =================================================================== --- head/contrib/llvm/include/llvm/CodeGen/AsmPrinter.h (revision 317457) +++ head/contrib/llvm/include/llvm/CodeGen/AsmPrinter.h (revision 317458) @@ -1,601 +1,615 @@ //===-- llvm/CodeGen/AsmPrinter.h - AsmPrinter Framework --------*- 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 a class to be used as the base class for target specific // asm writers. This class primarily handles common functionality used by // all asm writers. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_ASMPRINTER_H #define LLVM_CODEGEN_ASMPRINTER_H #include "llvm/ADT/MapVector.h" #include "llvm/ADT/Twine.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/DwarfStringPoolEntry.h" #include "llvm/IR/InlineAsm.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/SourceMgr.h" namespace llvm { class AsmPrinterHandler; class BlockAddress; class ByteStreamer; class GCStrategy; class Constant; class ConstantArray; class DIE; class DIEAbbrev; class GCMetadataPrinter; class GlobalIndirectSymbol; class GlobalValue; class GlobalVariable; class MachineBasicBlock; class MachineFunction; class MachineInstr; class MachineLocation; class MachineLoopInfo; class MachineLoop; class MachineConstantPoolValue; class MachineJumpTableInfo; class MachineModuleInfo; class MCAsmInfo; class MCCFIInstruction; class MCContext; class MCExpr; class MCInst; class MCSection; class MCStreamer; class MCSubtargetInfo; class MCSymbol; class MCTargetOptions; class MDNode; class DwarfDebug; class Mangler; class TargetLoweringObjectFile; class DataLayout; class TargetMachine; /// This class is intended to be used as a driving class for all asm writers. class AsmPrinter : public MachineFunctionPass { public: /// Target machine description. /// TargetMachine &TM; /// Target Asm Printer information. /// const MCAsmInfo *MAI; /// This is the context for the output file that we are streaming. This owns /// all of the global MC-related objects for the generated translation unit. MCContext &OutContext; /// This is the MCStreamer object for the file we are generating. This /// contains the transient state for the current translation unit that we are /// generating (such as the current section etc). std::unique_ptr OutStreamer; /// The current machine function. const MachineFunction *MF; /// This is a pointer to the current MachineModuleInfo. MachineModuleInfo *MMI; /// The symbol for the current function. This is recalculated at the beginning /// of each call to runOnMachineFunction(). /// MCSymbol *CurrentFnSym; /// The symbol used to represent the start of the current function for the /// purpose of calculating its size (e.g. using the .size directive). By /// default, this is equal to CurrentFnSym. MCSymbol *CurrentFnSymForSize; /// Map global GOT equivalent MCSymbols to GlobalVariables and keep track of /// its number of uses by other globals. typedef std::pair GOTEquivUsePair; MapVector GlobalGOTEquivs; private: MCSymbol *CurrentFnBegin; MCSymbol *CurrentFnEnd; MCSymbol *CurExceptionSym; // The garbage collection metadata printer table. void *GCMetadataPrinters; // Really a DenseMap. /// Emit comments in assembly output if this is true. /// bool VerboseAsm; static char ID; /// If VerboseAsm is set, a pointer to the loop info for this function. MachineLoopInfo *LI; struct HandlerInfo { AsmPrinterHandler *Handler; const char *TimerName; const char *TimerDescription; const char *TimerGroupName; const char *TimerGroupDescription; HandlerInfo(AsmPrinterHandler *Handler, const char *TimerName, const char *TimerDescription, const char *TimerGroupName, const char *TimerGroupDescription) : Handler(Handler), TimerName(TimerName), TimerDescription(TimerDescription), TimerGroupName(TimerGroupName), TimerGroupDescription(TimerGroupDescription) {} }; /// A vector of all debug/EH info emitters we should use. This vector /// maintains ownership of the emitters. SmallVector Handlers; + +public: + struct SrcMgrDiagInfo { + SourceMgr SrcMgr; + const MDNode *LocInfo; + LLVMContext::InlineAsmDiagHandlerTy DiagHandler; + void *DiagContext; + }; + +private: + /// Structure for generating diagnostics for inline assembly. Only initialised + /// when necessary. + mutable std::unique_ptr DiagInfo; /// If the target supports dwarf debug info, this pointer is non-null. DwarfDebug *DD; /// If the current module uses dwarf CFI annotations strictly for debugging. bool isCFIMoveForDebugging; protected: explicit AsmPrinter(TargetMachine &TM, std::unique_ptr Streamer); public: ~AsmPrinter() override; DwarfDebug *getDwarfDebug() { return DD; } DwarfDebug *getDwarfDebug() const { return DD; } uint16_t getDwarfVersion() const; void setDwarfVersion(uint16_t Version); bool isPositionIndependent() const; /// Return true if assembly output should contain comments. /// bool isVerbose() const { return VerboseAsm; } /// Return a unique ID for the current function. /// unsigned getFunctionNumber() const; MCSymbol *getFunctionBegin() const { return CurrentFnBegin; } MCSymbol *getFunctionEnd() const { return CurrentFnEnd; } MCSymbol *getCurExceptionSym(); /// Return information about object file lowering. const TargetLoweringObjectFile &getObjFileLowering() const; /// Return information about data layout. const DataLayout &getDataLayout() const; /// Return the pointer size from the TargetMachine unsigned getPointerSize() const; /// Return information about subtarget. const MCSubtargetInfo &getSubtargetInfo() const; void EmitToStreamer(MCStreamer &S, const MCInst &Inst); /// Return the current section we are emitting to. const MCSection *getCurrentSection() const; void getNameWithPrefix(SmallVectorImpl &Name, const GlobalValue *GV) const; MCSymbol *getSymbol(const GlobalValue *GV) const; //===------------------------------------------------------------------===// // XRay instrumentation implementation. //===------------------------------------------------------------------===// public: // This describes the kind of sled we're storing in the XRay table. enum class SledKind : uint8_t { FUNCTION_ENTER = 0, FUNCTION_EXIT = 1, TAIL_CALL = 2, }; // The table will contain these structs that point to the sled, the function // containing the sled, and what kind of sled (and whether they should always // be instrumented). struct XRayFunctionEntry { const MCSymbol *Sled; const MCSymbol *Function; SledKind Kind; bool AlwaysInstrument; const class Function *Fn; void emit(int, MCStreamer *, const MCSymbol *) const; }; // All the sleds to be emitted. std::vector Sleds; // Helper function to record a given XRay sled. void recordSled(MCSymbol *Sled, const MachineInstr &MI, SledKind Kind); /// Emit a table with all XRay instrumentation points. void emitXRayTable(); //===------------------------------------------------------------------===// // MachineFunctionPass Implementation. //===------------------------------------------------------------------===// /// Record analysis usage. /// void getAnalysisUsage(AnalysisUsage &AU) const override; /// Set up the AsmPrinter when we are working on a new module. If your pass /// overrides this, it must make sure to explicitly call this implementation. bool doInitialization(Module &M) override; /// Shut down the asmprinter. If you override this in your pass, you must make /// sure to call it explicitly. bool doFinalization(Module &M) override; /// Emit the specified function out to the OutStreamer. bool runOnMachineFunction(MachineFunction &MF) override { SetupMachineFunction(MF); EmitFunctionBody(); return false; } //===------------------------------------------------------------------===// // Coarse grained IR lowering routines. //===------------------------------------------------------------------===// /// This should be called when a new MachineFunction is being processed from /// runOnMachineFunction. void SetupMachineFunction(MachineFunction &MF); /// This method emits the body and trailer for a function. void EmitFunctionBody(); void emitCFIInstruction(const MachineInstr &MI); void emitFrameAlloc(const MachineInstr &MI); enum CFIMoveType { CFI_M_None, CFI_M_EH, CFI_M_Debug }; CFIMoveType needsCFIMoves(); /// Returns false if needsCFIMoves() == CFI_M_EH for any function /// in the module. bool needsOnlyDebugCFIMoves() const { return isCFIMoveForDebugging; } bool needsSEHMoves(); /// Print to the current output stream assembly representations of the /// constants in the constant pool MCP. This is used to print out constants /// which have been "spilled to memory" by the code generator. /// virtual void EmitConstantPool(); /// Print assembly representations of the jump tables used by the current /// function to the current output stream. /// virtual void EmitJumpTableInfo(); /// Emit the specified global variable to the .s file. virtual void EmitGlobalVariable(const GlobalVariable *GV); /// Check to see if the specified global is a special global used by LLVM. If /// so, emit it and return true, otherwise do nothing and return false. bool EmitSpecialLLVMGlobal(const GlobalVariable *GV); /// Emit an alignment directive to the specified power of two boundary. For /// example, if you pass in 3 here, you will get an 8 byte alignment. If a /// global value is specified, and if that global has an explicit alignment /// requested, it will override the alignment request if required for /// correctness. /// void EmitAlignment(unsigned NumBits, const GlobalObject *GO = nullptr) const; /// Lower the specified LLVM Constant to an MCExpr. virtual const MCExpr *lowerConstant(const Constant *CV); /// \brief Print a general LLVM constant to the .s file. void EmitGlobalConstant(const DataLayout &DL, const Constant *CV); /// \brief Unnamed constant global variables solely contaning a pointer to /// another globals variable act like a global variable "proxy", or GOT /// equivalents, i.e., it's only used to hold the address of the latter. One /// optimization is to replace accesses to these proxies by using the GOT /// entry for the final global instead. Hence, we select GOT equivalent /// candidates among all the module global variables, avoid emitting them /// unnecessarily and finally replace references to them by pc relative /// accesses to GOT entries. void computeGlobalGOTEquivs(Module &M); /// \brief Constant expressions using GOT equivalent globals may not be /// eligible for PC relative GOT entry conversion, in such cases we need to /// emit the proxies we previously omitted in EmitGlobalVariable. void emitGlobalGOTEquivs(); //===------------------------------------------------------------------===// // Overridable Hooks //===------------------------------------------------------------------===// // Targets can, or in the case of EmitInstruction, must implement these to // customize output. /// This virtual method can be overridden by targets that want to emit /// something at the start of their file. virtual void EmitStartOfAsmFile(Module &) {} /// This virtual method can be overridden by targets that want to emit /// something at the end of their file. virtual void EmitEndOfAsmFile(Module &) {} /// Targets can override this to emit stuff before the first basic block in /// the function. virtual void EmitFunctionBodyStart() {} /// Targets can override this to emit stuff after the last basic block in the /// function. virtual void EmitFunctionBodyEnd() {} /// Targets can override this to emit stuff at the start of a basic block. /// By default, this method prints the label for the specified /// MachineBasicBlock, an alignment (if present) and a comment describing it /// if appropriate. virtual void EmitBasicBlockStart(const MachineBasicBlock &MBB) const; /// Targets can override this to emit stuff at the end of a basic block. virtual void EmitBasicBlockEnd(const MachineBasicBlock &MBB) {} /// Targets should implement this to emit instructions. virtual void EmitInstruction(const MachineInstr *) { llvm_unreachable("EmitInstruction not implemented"); } /// Return the symbol for the specified constant pool entry. virtual MCSymbol *GetCPISymbol(unsigned CPID) const; virtual void EmitFunctionEntryLabel(); virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV); /// Targets can override this to change how global constants that are part of /// a C++ static/global constructor list are emitted. virtual void EmitXXStructor(const DataLayout &DL, const Constant *CV) { EmitGlobalConstant(DL, CV); } /// Return true if the basic block has exactly one predecessor and the control /// transfer mechanism between the predecessor and this block is a /// fall-through. virtual bool isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const; /// Targets can override this to customize the output of IMPLICIT_DEF /// instructions in verbose mode. virtual void emitImplicitDef(const MachineInstr *MI) const; //===------------------------------------------------------------------===// // Symbol Lowering Routines. //===------------------------------------------------------------------===// public: MCSymbol *createTempSymbol(const Twine &Name) const; /// Return the MCSymbol for a private symbol with global value name as its /// base, with the specified suffix. MCSymbol *getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix) const; /// Return the MCSymbol for the specified ExternalSymbol. MCSymbol *GetExternalSymbolSymbol(StringRef Sym) const; /// Return the symbol for the specified jump table entry. MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const; /// Return the symbol for the specified jump table .set /// FIXME: privatize to AsmPrinter. MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const; /// Return the MCSymbol used to satisfy BlockAddress uses of the specified /// basic block. MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const; MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const; //===------------------------------------------------------------------===// // Emission Helper Routines. //===------------------------------------------------------------------===// public: /// This is just convenient handler for printing offsets. void printOffset(int64_t Offset, raw_ostream &OS) const; /// Emit a byte directive and value. /// void EmitInt8(int Value) const; /// Emit a short directive and value. /// void EmitInt16(int Value) const; /// Emit a long directive and value. /// void EmitInt32(int Value) const; /// Emit something like ".long Hi-Lo" where the size in bytes of the directive /// is specified by Size and Hi/Lo specify the labels. This implicitly uses /// .set if it is available. void EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, unsigned Size) const; /// Emit something like ".long Label+Offset" where the size in bytes of the /// directive is specified by Size and Label specifies the label. This /// implicitly uses .set if it is available. void EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, unsigned Size, bool IsSectionRelative = false) const; /// Emit something like ".long Label" where the size in bytes of the directive /// is specified by Size and Label specifies the label. void EmitLabelReference(const MCSymbol *Label, unsigned Size, bool IsSectionRelative = false) const { EmitLabelPlusOffset(Label, 0, Size, IsSectionRelative); } //===------------------------------------------------------------------===// // Dwarf Emission Helper Routines //===------------------------------------------------------------------===// /// Emit the specified signed leb128 value. void EmitSLEB128(int64_t Value, const char *Desc = nullptr) const; /// Emit the specified unsigned leb128 value. void EmitULEB128(uint64_t Value, const char *Desc = nullptr, unsigned PadTo = 0) const; /// Emit a .byte 42 directive that corresponds to an encoding. If verbose /// assembly output is enabled, we output comments describing the encoding. /// Desc is a string saying what the encoding is specifying (e.g. "LSDA"). void EmitEncodingByte(unsigned Val, const char *Desc = nullptr) const; /// Return the size of the encoding in bytes. unsigned GetSizeOfEncodedValue(unsigned Encoding) const; /// Emit reference to a ttype global with a specified encoding. void EmitTTypeReference(const GlobalValue *GV, unsigned Encoding) const; /// Emit a reference to a symbol for use in dwarf. Different object formats /// represent this in different ways. Some use a relocation others encode /// the label offset in its section. void emitDwarfSymbolReference(const MCSymbol *Label, bool ForceOffset = false) const; /// Emit the 4-byte offset of a string from the start of its section. /// /// When possible, emit a DwarfStringPool section offset without any /// relocations, and without using the symbol. Otherwise, defers to \a /// emitDwarfSymbolReference(). void emitDwarfStringOffset(DwarfStringPoolEntryRef S) const; /// Get the value for DW_AT_APPLE_isa. Zero if no isa encoding specified. virtual unsigned getISAEncoding() { return 0; } /// Emit the directive and value for debug thread local expression /// /// \p Value - The value to emit. /// \p Size - The size of the integer (in bytes) to emit. virtual void EmitDebugValue(const MCExpr *Value, unsigned Size) const; //===------------------------------------------------------------------===// // Dwarf Lowering Routines //===------------------------------------------------------------------===// /// \brief Emit frame instruction to describe the layout of the frame. void emitCFIInstruction(const MCCFIInstruction &Inst) const; /// \brief Emit Dwarf abbreviation table. template void emitDwarfAbbrevs(const T &Abbrevs) const { // For each abbreviation. for (const auto &Abbrev : Abbrevs) emitDwarfAbbrev(*Abbrev); // Mark end of abbreviations. EmitULEB128(0, "EOM(3)"); } void emitDwarfAbbrev(const DIEAbbrev &Abbrev) const; /// \brief Recursively emit Dwarf DIE tree. void emitDwarfDIE(const DIE &Die) const; //===------------------------------------------------------------------===// // Inline Asm Support //===------------------------------------------------------------------===// public: // These are hooks that targets can override to implement inline asm // support. These should probably be moved out of AsmPrinter someday. /// Print information related to the specified machine instr that is /// independent of the operand, and may be independent of the instr itself. /// This can be useful for portably encoding the comment character or other /// bits of target-specific knowledge into the asmstrings. The syntax used is /// ${:comment}. Targets can override this to add support for their own /// strange codes. virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS, const char *Code) const; /// Print the specified operand of MI, an INLINEASM instruction, using the /// specified assembler variant. Targets should override this to format as /// appropriate. This method can return true if the operand is erroneous. virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS); /// Print the specified operand of MI, an INLINEASM instruction, using the /// specified assembler variant as an address. Targets should override this to /// format as appropriate. This method can return true if the operand is /// erroneous. virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS); /// Let the target do anything it needs to do before emitting inlineasm. /// \p StartInfo - the subtarget info before parsing inline asm virtual void emitInlineAsmStart() const; /// Let the target do anything it needs to do after emitting inlineasm. /// This callback can be used restore the original mode in case the /// inlineasm contains directives to switch modes. /// \p StartInfo - the original subtarget info before inline asm /// \p EndInfo - the final subtarget info after parsing the inline asm, /// or NULL if the value is unknown. virtual void emitInlineAsmEnd(const MCSubtargetInfo &StartInfo, const MCSubtargetInfo *EndInfo) const; private: /// Private state for PrintSpecial() // Assign a unique ID to this machine instruction. mutable const MachineInstr *LastMI; mutable unsigned LastFn; mutable unsigned Counter; /// This method emits the header for the current function. virtual void EmitFunctionHeader(); /// Emit a blob of inline asm to the output streamer. void EmitInlineAsm(StringRef Str, const MCSubtargetInfo &STI, const MCTargetOptions &MCOptions, const MDNode *LocMDNode = nullptr, InlineAsm::AsmDialect AsmDialect = InlineAsm::AD_ATT) const; /// This method formats and emits the specified machine instruction that is an /// inline asm. void EmitInlineAsm(const MachineInstr *MI) const; //===------------------------------------------------------------------===// // Internal Implementation Details //===------------------------------------------------------------------===// /// This emits visibility information about symbol, if this is suported by the /// target. void EmitVisibility(MCSymbol *Sym, unsigned Visibility, bool IsDefinition = true) const; void EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const; void EmitJumpTableEntry(const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, unsigned uid) const; void EmitLLVMUsedList(const ConstantArray *InitList); /// Emit llvm.ident metadata in an '.ident' directive. void EmitModuleIdents(Module &M); void EmitXXStructorList(const DataLayout &DL, const Constant *List, bool isCtor); GCMetadataPrinter *GetOrCreateGCPrinter(GCStrategy &C); /// Emit GlobalAlias or GlobalIFunc. void emitGlobalIndirectSymbol(Module &M, const GlobalIndirectSymbol& GIS); }; } #endif Index: head/contrib/llvm/include/llvm/MC/MCContext.h =================================================================== --- head/contrib/llvm/include/llvm/MC/MCContext.h (revision 317457) +++ head/contrib/llvm/include/llvm/MC/MCContext.h (revision 317458) @@ -1,635 +1,640 @@ //===- MCContext.h - Machine Code Context -----------------------*- 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_MCCONTEXT_H #define LLVM_MC_MCCONTEXT_H #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/Twine.h" #include "llvm/MC/MCDwarf.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/SectionKind.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Dwarf.h" #include "llvm/Support/raw_ostream.h" #include #include #include // FIXME: Shouldn't be needed. namespace llvm { class MCAsmInfo; class MCExpr; class MCSection; class MCSymbol; class MCSymbolELF; class MCLabel; struct MCDwarfFile; class MCDwarfLoc; class MCObjectFileInfo; class MCRegisterInfo; class MCLineSection; class SMLoc; class MCSectionMachO; class MCSectionELF; class MCSectionCOFF; class CodeViewContext; /// Context object for machine code objects. This class owns all of the /// sections that it creates. /// class MCContext { MCContext(const MCContext &) = delete; MCContext &operator=(const MCContext &) = delete; public: typedef StringMap SymbolTable; private: /// The SourceMgr for this object, if any. const SourceMgr *SrcMgr; + /// The SourceMgr for inline assembly, if any. + SourceMgr *InlineSrcMgr; + /// The MCAsmInfo for this target. const MCAsmInfo *MAI; /// The MCRegisterInfo for this target. const MCRegisterInfo *MRI; /// The MCObjectFileInfo for this target. const MCObjectFileInfo *MOFI; std::unique_ptr CVContext; /// Allocator object used for creating machine code objects. /// /// We use a bump pointer allocator to avoid the need to track all allocated /// objects. BumpPtrAllocator Allocator; SpecificBumpPtrAllocator COFFAllocator; SpecificBumpPtrAllocator ELFAllocator; SpecificBumpPtrAllocator MachOAllocator; /// Bindings of names to symbols. SymbolTable Symbols; /// Sections can have a corresponding symbol. This maps one to the /// other. DenseMap SectionSymbols; /// A mapping from a local label number and an instance count to a symbol. /// For example, in the assembly /// 1: /// 2: /// 1: /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1) DenseMap, MCSymbol *> LocalSymbols; /// Keeps tracks of names that were used both for used declared and /// artificial symbols. The value is "true" if the name has been used for a /// non-section symbol (there can be at most one of those, plus an unlimited /// number of section symbols with the same name). StringMap UsedNames; /// The next ID to dole out to an unnamed assembler temporary symbol with /// a given prefix. StringMap NextID; /// Instances of directional local labels. DenseMap Instances; /// NextInstance() creates the next instance of the directional local label /// for the LocalLabelVal and adds it to the map if needed. unsigned NextInstance(unsigned LocalLabelVal); /// GetInstance() gets the current instance of the directional local label /// for the LocalLabelVal and adds it to the map if needed. unsigned GetInstance(unsigned LocalLabelVal); /// The file name of the log file from the environment variable /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique /// directive is used or it is an error. char *SecureLogFile; /// The stream that gets written to for the .secure_log_unique directive. std::unique_ptr SecureLog; /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to /// catch errors if .secure_log_unique appears twice without /// .secure_log_reset appearing between them. bool SecureLogUsed; /// The compilation directory to use for DW_AT_comp_dir. SmallString<128> CompilationDir; /// The main file name if passed in explicitly. std::string MainFileName; /// The dwarf file and directory tables from the dwarf .file directive. /// We now emit a line table for each compile unit. To reduce the prologue /// size of each line table, the files and directories used by each compile /// unit are separated. std::map MCDwarfLineTablesCUMap; /// The current dwarf line information from the last dwarf .loc directive. MCDwarfLoc CurrentDwarfLoc; bool DwarfLocSeen; /// Generate dwarf debugging info for assembly source files. bool GenDwarfForAssembly; /// The current dwarf file number when generate dwarf debugging info for /// assembly source files. unsigned GenDwarfFileNumber; /// Sections for generating the .debug_ranges and .debug_aranges sections. SetVector SectionsForRanges; /// The information gathered from labels that will have dwarf label /// entries when generating dwarf assembly source files. std::vector MCGenDwarfLabelEntries; /// The string to embed in the debug information for the compile unit, if /// non-empty. StringRef DwarfDebugFlags; /// The string to embed in as the dwarf AT_producer for the compile unit, if /// non-empty. StringRef DwarfDebugProducer; /// The maximum version of dwarf that we should emit. uint16_t DwarfVersion; /// Honor temporary labels, this is useful for debugging semantic /// differences between temporary and non-temporary labels (primarily on /// Darwin). bool AllowTemporaryLabels; bool UseNamesOnTempLabels = true; /// The Compile Unit ID that we are currently processing. unsigned DwarfCompileUnitID; struct ELFSectionKey { std::string SectionName; StringRef GroupName; unsigned UniqueID; ELFSectionKey(StringRef SectionName, StringRef GroupName, unsigned UniqueID) : SectionName(SectionName), GroupName(GroupName), UniqueID(UniqueID) { } bool operator<(const ELFSectionKey &Other) const { if (SectionName != Other.SectionName) return SectionName < Other.SectionName; if (GroupName != Other.GroupName) return GroupName < Other.GroupName; return UniqueID < Other.UniqueID; } }; struct COFFSectionKey { std::string SectionName; StringRef GroupName; int SelectionKey; unsigned UniqueID; COFFSectionKey(StringRef SectionName, StringRef GroupName, int SelectionKey, unsigned UniqueID) : SectionName(SectionName), GroupName(GroupName), SelectionKey(SelectionKey), UniqueID(UniqueID) {} bool operator<(const COFFSectionKey &Other) const { if (SectionName != Other.SectionName) return SectionName < Other.SectionName; if (GroupName != Other.GroupName) return GroupName < Other.GroupName; if (SelectionKey != Other.SelectionKey) return SelectionKey < Other.SelectionKey; return UniqueID < Other.UniqueID; } }; StringMap MachOUniquingMap; std::map ELFUniquingMap; std::map COFFUniquingMap; StringMap ELFRelSecNames; SpecificBumpPtrAllocator MCSubtargetAllocator; /// Do automatic reset in destructor bool AutoReset; bool HadError; MCSymbol *createSymbolImpl(const StringMapEntry *Name, bool CanBeUnnamed); MCSymbol *createSymbol(StringRef Name, bool AlwaysAddSuffix, bool IsTemporary); MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal, unsigned Instance); public: explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI, const MCObjectFileInfo *MOFI, const SourceMgr *Mgr = nullptr, bool DoAutoReset = true); ~MCContext(); const SourceMgr *getSourceManager() const { return SrcMgr; } + + void setInlineSourceManager(SourceMgr *SM) { InlineSrcMgr = SM; } const MCAsmInfo *getAsmInfo() const { return MAI; } const MCRegisterInfo *getRegisterInfo() const { return MRI; } const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; } CodeViewContext &getCVContext(); void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; } void setUseNamesOnTempLabels(bool Value) { UseNamesOnTempLabels = Value; } /// \name Module Lifetime Management /// @{ /// reset - return object to right after construction state to prepare /// to process a new module void reset(); /// @} /// \name Symbol Management /// @{ /// Create and return a new linker temporary symbol with a unique but /// unspecified name. MCSymbol *createLinkerPrivateTempSymbol(); /// Create and return a new assembler temporary symbol with a unique but /// unspecified name. MCSymbol *createTempSymbol(bool CanBeUnnamed = true); MCSymbol *createTempSymbol(const Twine &Name, bool AlwaysAddSuffix, bool CanBeUnnamed = true); /// Create the definition of a directional local symbol for numbered label /// (used for "1:" definitions). MCSymbol *createDirectionalLocalSymbol(unsigned LocalLabelVal); /// Create and return a directional local symbol for numbered label (used /// for "1b" or 1f" references). MCSymbol *getDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before); /// Lookup the symbol inside with the specified \p Name. If it exists, /// return it. If not, create a forward reference and return it. /// /// \param Name - The symbol name, which must be unique across all symbols. MCSymbol *getOrCreateSymbol(const Twine &Name); MCSymbolELF *getOrCreateSectionSymbol(const MCSectionELF &Section); /// Gets a symbol that will be defined to the final stack offset of a local /// variable after codegen. /// /// \param Idx - The index of a local variable passed to @llvm.localescape. MCSymbol *getOrCreateFrameAllocSymbol(StringRef FuncName, unsigned Idx); MCSymbol *getOrCreateParentFrameOffsetSymbol(StringRef FuncName); MCSymbol *getOrCreateLSDASymbol(StringRef FuncName); /// Get the symbol for \p Name, or null. MCSymbol *lookupSymbol(const Twine &Name) const; /// Set value for a symbol. void setSymbolValue(MCStreamer &Streamer, StringRef Sym, uint64_t Val); /// getSymbols - Get a reference for the symbol table for clients that /// want to, for example, iterate over all symbols. 'const' because we /// still want any modifications to the table itself to use the MCContext /// APIs. const SymbolTable &getSymbols() const { return Symbols; } /// @} /// \name Section Management /// @{ enum : unsigned { /// Pass this value as the UniqueID during section creation to get the /// generic section with the given name and characteristics. The usual /// sections such as .text use this ID. GenericSectionID = ~0U }; /// 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(const Twine &Section, unsigned Type, unsigned Flags) { return getELFSection(Section, Type, Flags, nullptr); } MCSectionELF *getELFSection(const Twine &Section, unsigned Type, unsigned Flags, const char *BeginSymName) { return getELFSection(Section, Type, Flags, 0, "", BeginSymName); } MCSectionELF *getELFSection(const Twine &Section, unsigned Type, unsigned Flags, unsigned EntrySize, const Twine &Group) { return getELFSection(Section, Type, Flags, EntrySize, Group, nullptr); } MCSectionELF *getELFSection(const Twine &Section, unsigned Type, unsigned Flags, unsigned EntrySize, const Twine &Group, const char *BeginSymName) { return getELFSection(Section, Type, Flags, EntrySize, Group, ~0, BeginSymName); } MCSectionELF *getELFSection(const Twine &Section, unsigned Type, unsigned Flags, unsigned EntrySize, const Twine &Group, unsigned UniqueID) { return getELFSection(Section, Type, Flags, EntrySize, Group, UniqueID, nullptr); } MCSectionELF *getELFSection(const Twine &Section, unsigned Type, unsigned Flags, unsigned EntrySize, const Twine &Group, unsigned UniqueID, const char *BeginSymName); MCSectionELF *getELFSection(const Twine &Section, unsigned Type, unsigned Flags, unsigned EntrySize, const MCSymbolELF *Group, unsigned UniqueID, const char *BeginSymName, const MCSectionELF *Associated); /// Get a section with the provided group identifier. This section is /// named by concatenating \p Prefix with '.' then \p Suffix. The \p Type /// describes the type of the section and \p Flags are used to further /// configure this named section. MCSectionELF *getELFNamedSection(const Twine &Prefix, const Twine &Suffix, unsigned Type, unsigned Flags, unsigned EntrySize = 0); MCSectionELF *createELFRelSection(const Twine &Name, unsigned Type, unsigned Flags, unsigned EntrySize, const MCSymbolELF *Group, const MCSectionELF *Associated); void renameELFSection(MCSectionELF *Section, StringRef Name); MCSectionELF *createELFGroupSection(const MCSymbolELF *Group); MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics, SectionKind Kind, StringRef COMDATSymName, int Selection, unsigned UniqueID = GenericSectionID, 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, unsigned UniqueID = GenericSectionID); // Create and save a copy of STI and return a reference to the copy. MCSubtargetInfo &getSubtargetCopy(const MCSubtargetInfo &STI); /// @} /// \name Dwarf Management /// @{ /// \brief Get the compilation directory for DW_AT_comp_dir /// The compilation directory should be set with \c setCompilationDir before /// calling this function. If it is unset, an empty string will be returned. StringRef getCompilationDir() const { return CompilationDir; } /// \brief Set the compilation directory for DW_AT_comp_dir void setCompilationDir(StringRef S) { CompilationDir = S.str(); } /// \brief Get the main file name for use in error messages and debug /// info. This can be set to ensure we've got the correct file name /// after preprocessing or for -save-temps. const std::string &getMainFileName() const { return MainFileName; } /// \brief Set the main file name and override the default. void setMainFileName(StringRef S) { MainFileName = S; } /// Creates an entry in the dwarf file and directory tables. unsigned getDwarfFile(StringRef Directory, StringRef FileName, unsigned FileNumber, unsigned CUID); bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0); const std::map &getMCDwarfLineTables() const { return MCDwarfLineTablesCUMap; } MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) { return MCDwarfLineTablesCUMap[CUID]; } const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const { auto I = MCDwarfLineTablesCUMap.find(CUID); assert(I != MCDwarfLineTablesCUMap.end()); return I->second; } const SmallVectorImpl &getMCDwarfFiles(unsigned CUID = 0) { return getMCDwarfLineTable(CUID).getMCDwarfFiles(); } const SmallVectorImpl &getMCDwarfDirs(unsigned CUID = 0) { return getMCDwarfLineTable(CUID).getMCDwarfDirs(); } bool hasMCLineSections() const { for (const auto &Table : MCDwarfLineTablesCUMap) if (!Table.second.getMCDwarfFiles().empty() || Table.second.getLabel()) return true; return false; } unsigned getDwarfCompileUnitID() { return DwarfCompileUnitID; } void setDwarfCompileUnitID(unsigned CUIndex) { DwarfCompileUnitID = CUIndex; } void setMCLineTableCompilationDir(unsigned CUID, StringRef CompilationDir) { getMCDwarfLineTable(CUID).setCompilationDir(CompilationDir); } /// Saves the information from the currently parsed dwarf .loc directive /// and sets DwarfLocSeen. When the next instruction is assembled an entry /// in the line number table with this information and the address of the /// instruction will be created. void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column, unsigned Flags, unsigned Isa, unsigned Discriminator) { CurrentDwarfLoc.setFileNum(FileNum); CurrentDwarfLoc.setLine(Line); CurrentDwarfLoc.setColumn(Column); CurrentDwarfLoc.setFlags(Flags); CurrentDwarfLoc.setIsa(Isa); CurrentDwarfLoc.setDiscriminator(Discriminator); DwarfLocSeen = true; } void clearDwarfLocSeen() { DwarfLocSeen = false; } bool getDwarfLocSeen() { return DwarfLocSeen; } const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; } bool getGenDwarfForAssembly() { return GenDwarfForAssembly; } void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; } unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; } void setGenDwarfFileNumber(unsigned FileNumber) { GenDwarfFileNumber = FileNumber; } const SetVector &getGenDwarfSectionSyms() { return SectionsForRanges; } bool addGenDwarfSection(MCSection *Sec) { return SectionsForRanges.insert(Sec); } void finalizeDwarfSections(MCStreamer &MCOS); const std::vector &getMCGenDwarfLabelEntries() const { return MCGenDwarfLabelEntries; } void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) { MCGenDwarfLabelEntries.push_back(E); } void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; } StringRef getDwarfDebugFlags() { return DwarfDebugFlags; } void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; } StringRef getDwarfDebugProducer() { return DwarfDebugProducer; } dwarf::DwarfFormat getDwarfFormat() const { // TODO: Support DWARF64 return dwarf::DWARF32; } void setDwarfVersion(uint16_t v) { DwarfVersion = v; } uint16_t getDwarfVersion() const { return DwarfVersion; } /// @} char *getSecureLogFile() { return SecureLogFile; } raw_fd_ostream *getSecureLog() { return SecureLog.get(); } bool getSecureLogUsed() { return SecureLogUsed; } void setSecureLog(std::unique_ptr Value) { SecureLog = std::move(Value); } void setSecureLogUsed(bool Value) { SecureLogUsed = Value; } void *allocate(unsigned Size, unsigned Align = 8) { return Allocator.Allocate(Size, Align); } void deallocate(void *Ptr) {} bool hadError() { return HadError; } void reportError(SMLoc L, const Twine &Msg); // Unrecoverable error has occurred. Display the best diagnostic we can // and bail via exit(1). For now, most MC backend errors are unrecoverable. // FIXME: We should really do something about that. LLVM_ATTRIBUTE_NORETURN void reportFatalError(SMLoc L, const Twine &Msg); }; } // end namespace llvm // operator new and delete aren't allowed inside namespaces. // The throw specifications are mandated by the standard. /// \brief Placement new for using the MCContext's allocator. /// /// This placement form of operator new uses the MCContext's allocator for /// obtaining memory. It is a non-throwing new, which means that it returns /// null on error. (If that is what the allocator does. The current does, so if /// this ever changes, this operator will have to be changed, too.) /// Usage looks like this (assuming there's an MCContext 'Context' in scope): /// \code /// // Default alignment (8) /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments); /// // Specific alignment /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments); /// \endcode /// Please note that you cannot use delete on the pointer; it must be /// deallocated using an explicit destructor call followed by /// \c Context.Deallocate(Ptr). /// /// \param Bytes The number of bytes to allocate. Calculated by the compiler. /// \param C The MCContext that provides the allocator. /// \param Alignment The alignment of the allocated memory (if the underlying /// allocator supports it). /// \return The allocated memory. Could be NULL. inline void *operator new(size_t Bytes, llvm::MCContext &C, size_t Alignment = 8) noexcept { return C.allocate(Bytes, Alignment); } /// \brief Placement delete companion to the new above. /// /// This operator is just a companion to the new above. There is no way of /// invoking it directly; see the new operator for more details. This operator /// is called implicitly by the compiler if a placement new expression using /// the MCContext throws in the object constructor. inline void operator delete(void *Ptr, llvm::MCContext &C, size_t) noexcept { C.deallocate(Ptr); } /// This placement form of operator new[] uses the MCContext's allocator for /// obtaining memory. It is a non-throwing new[], which means that it returns /// null on error. /// Usage looks like this (assuming there's an MCContext 'Context' in scope): /// \code /// // Default alignment (8) /// char *data = new (Context) char[10]; /// // Specific alignment /// char *data = new (Context, 4) char[10]; /// \endcode /// Please note that you cannot use delete on the pointer; it must be /// deallocated using an explicit destructor call followed by /// \c Context.Deallocate(Ptr). /// /// \param Bytes The number of bytes to allocate. Calculated by the compiler. /// \param C The MCContext that provides the allocator. /// \param Alignment The alignment of the allocated memory (if the underlying /// allocator supports it). /// \return The allocated memory. Could be NULL. inline void *operator new[](size_t Bytes, llvm::MCContext &C, size_t Alignment = 8) noexcept { return C.allocate(Bytes, Alignment); } /// \brief Placement delete[] companion to the new[] above. /// /// This operator is just a companion to the new[] above. There is no way of /// invoking it directly; see the new[] operator for more details. This operator /// is called implicitly by the compiler if a placement new[] expression using /// the MCContext throws in the object constructor. inline void operator delete[](void *Ptr, llvm::MCContext &C) noexcept { C.deallocate(Ptr); } #endif Index: head/contrib/llvm/include/llvm/MC/MCParser/MCAsmParser.h =================================================================== --- head/contrib/llvm/include/llvm/MC/MCParser/MCAsmParser.h (revision 317457) +++ head/contrib/llvm/include/llvm/MC/MCParser/MCAsmParser.h (revision 317458) @@ -1,265 +1,265 @@ //===-- llvm/MC/MCAsmParser.h - Abstract Asm Parser Interface ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_MC_MCPARSER_MCASMPARSER_H #define LLVM_MC_MCPARSER_MCASMPARSER_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/MC/MCParser/AsmLexer.h" #include "llvm/Support/DataTypes.h" namespace llvm { class MCAsmInfo; class MCAsmLexer; class MCAsmParserExtension; class MCContext; class MCExpr; class MCInstPrinter; class MCInstrInfo; class MCStreamer; class MCTargetAsmParser; class SMLoc; class SMRange; class SourceMgr; class Twine; class InlineAsmIdentifierInfo { public: void *OpDecl; bool IsVarDecl; unsigned Length, Size, Type; void clear() { OpDecl = nullptr; IsVarDecl = false; Length = 1; Size = 0; Type = 0; } }; /// \brief Generic Sema callback for assembly parser. class MCAsmParserSemaCallback { public: virtual ~MCAsmParserSemaCallback(); virtual void *LookupInlineAsmIdentifier(StringRef &LineBuf, InlineAsmIdentifierInfo &Info, bool IsUnevaluatedContext) = 0; virtual StringRef LookupInlineAsmLabel(StringRef Identifier, SourceMgr &SM, SMLoc Location, bool Create) = 0; virtual bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset) = 0; }; /// \brief Generic assembler parser interface, for use by target specific /// assembly parsers. class MCAsmParser { public: typedef bool (*DirectiveHandler)(MCAsmParserExtension*, StringRef, SMLoc); typedef std::pair ExtensionDirectiveHandler; struct MCPendingError { SMLoc Loc; SmallString<64> Msg; SMRange Range; }; private: MCAsmParser(const MCAsmParser &) = delete; void operator=(const MCAsmParser &) = delete; MCTargetAsmParser *TargetParser; unsigned ShowParsedOperands : 1; protected: // Can only create subclasses. MCAsmParser(); bool HadError; SmallVector PendingErrors; /// Flag tracking whether any errors have been encountered. public: virtual ~MCAsmParser(); virtual void addDirectiveHandler(StringRef Directive, ExtensionDirectiveHandler Handler) = 0; virtual void addAliasForDirective(StringRef Directive, StringRef Alias) = 0; virtual SourceMgr &getSourceManager() = 0; virtual MCAsmLexer &getLexer() = 0; const MCAsmLexer &getLexer() const { return const_cast(this)->getLexer(); } virtual MCContext &getContext() = 0; /// \brief Return the output streamer for the assembler. virtual MCStreamer &getStreamer() = 0; MCTargetAsmParser &getTargetParser() const { return *TargetParser; } void setTargetParser(MCTargetAsmParser &P); virtual unsigned getAssemblerDialect() { return 0;} virtual void setAssemblerDialect(unsigned i) { } bool getShowParsedOperands() const { return ShowParsedOperands; } void setShowParsedOperands(bool Value) { ShowParsedOperands = Value; } /// \brief Run the parser on the input source buffer. virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false) = 0; virtual void setParsingInlineAsm(bool V) = 0; virtual bool isParsingInlineAsm() = 0; /// \brief Parse MS-style inline assembly. virtual bool parseMSInlineAsm( void *AsmLoc, std::string &AsmString, unsigned &NumOutputs, unsigned &NumInputs, SmallVectorImpl> &OpDecls, SmallVectorImpl &Constraints, SmallVectorImpl &Clobbers, const MCInstrInfo *MII, const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) = 0; /// \brief Emit a note at the location \p L, with the message \p Msg. virtual void Note(SMLoc L, const Twine &Msg, SMRange Range = None) = 0; /// \brief Emit a warning at the location \p L, with the message \p Msg. /// /// \return The return value is true, if warnings are fatal. virtual bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) = 0; /// \brief Return an error at the location \p L, with the message \p Msg. This /// may be modified before being emitted. /// /// \return The return value is always true, as an idiomatic convenience to /// clients. bool Error(SMLoc L, const Twine &Msg, SMRange Range = None); /// \brief Emit an error at the location \p L, with the message \p Msg. /// /// \return The return value is always true, as an idiomatic convenience to /// clients. virtual bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) = 0; bool hasPendingError() { return !PendingErrors.empty(); } bool printPendingErrors() { bool rv = !PendingErrors.empty(); for (auto Err : PendingErrors) { printError(Err.Loc, Twine(Err.Msg), Err.Range); } PendingErrors.clear(); return rv; } bool addErrorSuffix(const Twine &Suffix); /// \brief Get the next AsmToken in the stream, possibly handling file /// inclusion first. virtual const AsmToken &Lex() = 0; /// \brief Get the current AsmToken from the stream. const AsmToken &getTok() const; /// \brief Report an error at the current lexer location. bool TokError(const Twine &Msg, SMRange Range = None); bool parseTokenLoc(SMLoc &Loc); bool parseToken(AsmToken::TokenKind T, const Twine &Msg = "unexpected token"); /// \brief Attempt to parse and consume token, returning true on /// success. bool parseOptionalToken(AsmToken::TokenKind T); bool parseEOL(const Twine &ErrMsg); bool parseMany(std::function parseOne, bool hasComma = true); bool parseIntToken(int64_t &V, const Twine &ErrMsg); bool check(bool P, const llvm::Twine &Msg); bool check(bool P, SMLoc Loc, const llvm::Twine &Msg); /// \brief Parse an identifier or string (as a quoted identifier) and set \p /// Res to the identifier contents. virtual bool parseIdentifier(StringRef &Res) = 0; /// \brief Parse up to the end of statement and return the contents from the /// current token until the end of the statement; the current token on exit /// will be either the EndOfStatement or EOF. virtual StringRef parseStringToEndOfStatement() = 0; /// \brief Parse the current token as a string which may include escaped /// characters and return the string contents. virtual bool parseEscapedString(std::string &Data) = 0; /// \brief Skip to the end of the current statement, for error recovery. virtual void eatToEndOfStatement() = 0; /// \brief Parse an arbitrary expression. /// /// \param Res - The value of the expression. The result is undefined /// on error. /// \return - False on success. virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) = 0; bool parseExpression(const MCExpr *&Res); /// \brief Parse a primary expression. /// /// \param Res - The value of the expression. The result is undefined /// on error. /// \return - False on success. virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) = 0; /// \brief Parse an arbitrary expression, assuming that an initial '(' has /// already been consumed. /// /// \param Res - The value of the expression. The result is undefined /// on error. /// \return - False on success. virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) = 0; /// \brief Parse an expression which must evaluate to an absolute value. /// /// \param Res - The value of the absolute expression. The result is undefined /// on error. /// \return - False on success. virtual bool parseAbsoluteExpression(int64_t &Res) = 0; /// \brief Ensure that we have a valid section set in the streamer. Otherwise, /// report an error and switch to .text. /// \return - False on success. virtual bool checkForValidSection() = 0; /// \brief Parse an arbitrary expression of a specified parenthesis depth, /// assuming that the initial '(' characters have already been consumed. /// /// \param ParenDepth - Specifies how many trailing expressions outside the /// current parentheses we have to parse. /// \param Res - The value of the expression. The result is undefined /// on error. /// \return - False on success. virtual bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res, SMLoc &EndLoc) = 0; }; /// \brief Create an MCAsmParser instance. MCAsmParser *createMCAsmParser(SourceMgr &, MCContext &, MCStreamer &, - const MCAsmInfo &); + const MCAsmInfo &, unsigned CB = 0); } // End llvm namespace #endif Index: head/contrib/llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp =================================================================== --- head/contrib/llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp (revision 317457) +++ head/contrib/llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp (revision 317458) @@ -1,597 +1,595 @@ //===-- AsmPrinterInlineAsm.cpp - AsmPrinter Inline Asm Handling ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the inline assembler pieces of the AsmPrinter class. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Twine.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/InlineAsm.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCParser/MCTargetAsmParser.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Target/TargetSubtargetInfo.h" using namespace llvm; #define DEBUG_TYPE "asm-printer" -namespace { - struct SrcMgrDiagInfo { - const MDNode *LocInfo; - LLVMContext::InlineAsmDiagHandlerTy DiagHandler; - void *DiagContext; - }; -} - /// srcMgrDiagHandler - This callback is invoked when the SourceMgr for an /// inline asm has an error in it. diagInfo is a pointer to the SrcMgrDiagInfo /// struct above. static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) { - SrcMgrDiagInfo *DiagInfo = static_cast(diagInfo); + AsmPrinter::SrcMgrDiagInfo *DiagInfo = + static_cast(diagInfo); assert(DiagInfo && "Diagnostic context not passed down?"); // If the inline asm had metadata associated with it, pull out a location // cookie corresponding to which line the error occurred on. unsigned LocCookie = 0; if (const MDNode *LocInfo = DiagInfo->LocInfo) { unsigned ErrorLine = Diag.getLineNo()-1; if (ErrorLine >= LocInfo->getNumOperands()) ErrorLine = 0; if (LocInfo->getNumOperands() != 0) if (const ConstantInt *CI = mdconst::dyn_extract(LocInfo->getOperand(ErrorLine))) LocCookie = CI->getZExtValue(); } DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie); } /// EmitInlineAsm - Emit a blob of inline asm to the output streamer. void AsmPrinter::EmitInlineAsm(StringRef Str, const MCSubtargetInfo &STI, const MCTargetOptions &MCOptions, const MDNode *LocMDNode, InlineAsm::AsmDialect Dialect) const { assert(!Str.empty() && "Can't emit empty inline asm block"); // Remember if the buffer is nul terminated or not so we can avoid a copy. bool isNullTerminated = Str.back() == 0; if (isNullTerminated) Str = Str.substr(0, Str.size()-1); // If the output streamer does not have mature MC support or the integrated // assembler has been disabled, just emit the blob textually. // Otherwise parse the asm and emit it via MC support. // This is useful in case the asm parser doesn't handle something but the // system assembler does. const MCAsmInfo *MCAI = TM.getMCAsmInfo(); assert(MCAI && "No MCAsmInfo"); if (!MCAI->useIntegratedAssembler() && !OutStreamer->isIntegratedAssemblerRequired()) { emitInlineAsmStart(); OutStreamer->EmitRawText(Str); emitInlineAsmEnd(STI, nullptr); return; } - SourceMgr SrcMgr; - SrcMgr.setIncludeDirs(MCOptions.IASSearchPaths); + if (!DiagInfo) { + DiagInfo = make_unique(); - SrcMgrDiagInfo DiagInfo; + MCContext &Context = MMI->getContext(); + Context.setInlineSourceManager(&DiagInfo->SrcMgr); - // If the current LLVMContext has an inline asm handler, set it in SourceMgr. - LLVMContext &LLVMCtx = MMI->getModule()->getContext(); - bool HasDiagHandler = false; - if (LLVMCtx.getInlineAsmDiagnosticHandler() != nullptr) { - // If the source manager has an issue, we arrange for srcMgrDiagHandler - // to be invoked, getting DiagInfo passed into it. - DiagInfo.LocInfo = LocMDNode; - DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler(); - DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext(); - SrcMgr.setDiagHandler(srcMgrDiagHandler, &DiagInfo); - HasDiagHandler = true; + LLVMContext &LLVMCtx = MMI->getModule()->getContext(); + if (LLVMCtx.getInlineAsmDiagnosticHandler()) { + DiagInfo->DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler(); + DiagInfo->DiagContext = LLVMCtx.getInlineAsmDiagnosticContext(); + DiagInfo->SrcMgr.setDiagHandler(srcMgrDiagHandler, DiagInfo.get()); + } } + SourceMgr &SrcMgr = DiagInfo->SrcMgr; + SrcMgr.setIncludeDirs(MCOptions.IASSearchPaths); + DiagInfo->LocInfo = LocMDNode; + std::unique_ptr Buffer; - if (isNullTerminated) - Buffer = MemoryBuffer::getMemBuffer(Str, ""); - else - Buffer = MemoryBuffer::getMemBufferCopy(Str, ""); + // The inline asm source manager will outlive Str, so make a copy of the + // string for SourceMgr to own. + Buffer = MemoryBuffer::getMemBufferCopy(Str, ""); // Tell SrcMgr about this buffer, it takes ownership of the buffer. - SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc()); + unsigned BufNum = SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc()); std::unique_ptr Parser( - createMCAsmParser(SrcMgr, OutContext, *OutStreamer, *MAI)); + createMCAsmParser(SrcMgr, OutContext, *OutStreamer, *MAI, BufNum)); // We create a new MCInstrInfo here since we might be at the module level // and not have a MachineFunction to initialize the TargetInstrInfo from and // we only need MCInstrInfo for asm parsing. We create one unconditionally // because it's not subtarget dependent. std::unique_ptr MII(TM.getTarget().createMCInstrInfo()); std::unique_ptr TAP(TM.getTarget().createMCAsmParser( STI, *Parser, *MII, MCOptions)); if (!TAP) report_fatal_error("Inline asm not supported by this streamer because" " we don't have an asm parser for this target\n"); Parser->setAssemblerDialect(Dialect); Parser->setTargetParser(*TAP.get()); if (MF) { const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); TAP->SetFrameRegister(TRI->getFrameRegister(*MF)); } emitInlineAsmStart(); // Don't implicitly switch to the text section before the asm. int Res = Parser->Run(/*NoInitialTextSection*/ true, /*NoFinalize*/ true); emitInlineAsmEnd(STI, &TAP->getSTI()); - if (Res && !HasDiagHandler) + + // LocInfo cannot be used for error generation from the backend. + // FIXME: associate LocInfo with the SourceBuffer to improve backend + // messages. + DiagInfo->LocInfo = nullptr; + + if (Res && !DiagInfo->DiagHandler) report_fatal_error("Error parsing inline asm\n"); } static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI, MachineModuleInfo *MMI, int InlineAsmVariant, AsmPrinter *AP, unsigned LocCookie, raw_ostream &OS) { // Switch to the inline assembly variant. OS << "\t.intel_syntax\n\t"; const char *LastEmitted = AsmStr; // One past the last character emitted. unsigned NumOperands = MI->getNumOperands(); while (*LastEmitted) { switch (*LastEmitted) { default: { // Not a special case, emit the string section literally. const char *LiteralEnd = LastEmitted+1; while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' && *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n') ++LiteralEnd; OS.write(LastEmitted, LiteralEnd-LastEmitted); LastEmitted = LiteralEnd; break; } case '\n': ++LastEmitted; // Consume newline character. OS << '\n'; // Indent code with newline. break; case '$': { ++LastEmitted; // Consume '$' character. bool Done = true; // Handle escapes. switch (*LastEmitted) { default: Done = false; break; case '$': ++LastEmitted; // Consume second '$' character. break; } if (Done) break; // If we have ${:foo}, then this is not a real operand reference, it is a // "magic" string reference, just like in .td files. Arrange to call // PrintSpecial. if (LastEmitted[0] == '{' && LastEmitted[1] == ':') { LastEmitted += 2; const char *StrStart = LastEmitted; const char *StrEnd = strchr(StrStart, '}'); if (!StrEnd) report_fatal_error("Unterminated ${:foo} operand in inline asm" " string: '" + Twine(AsmStr) + "'"); std::string Val(StrStart, StrEnd); AP->PrintSpecial(MI, OS, Val.c_str()); LastEmitted = StrEnd+1; break; } const char *IDStart = LastEmitted; const char *IDEnd = IDStart; while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd; unsigned Val; if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val)) report_fatal_error("Bad $ operand number in inline asm string: '" + Twine(AsmStr) + "'"); LastEmitted = IDEnd; if (Val >= NumOperands-1) report_fatal_error("Invalid $ operand number in inline asm string: '" + Twine(AsmStr) + "'"); // Okay, we finally have a value number. Ask the target to print this // operand! unsigned OpNo = InlineAsm::MIOp_FirstOperand; bool Error = false; // Scan to find the machine operand number for the operand. for (; Val; --Val) { if (OpNo >= MI->getNumOperands()) break; unsigned OpFlags = MI->getOperand(OpNo).getImm(); OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1; } // We may have a location metadata attached to the end of the // instruction, and at no point should see metadata at any // other point while processing. It's an error if so. if (OpNo >= MI->getNumOperands() || MI->getOperand(OpNo).isMetadata()) { Error = true; } else { unsigned OpFlags = MI->getOperand(OpNo).getImm(); ++OpNo; // Skip over the ID number. if (InlineAsm::isMemKind(OpFlags)) { Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant, /*Modifier*/ nullptr, OS); } else { Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant, /*Modifier*/ nullptr, OS); } } if (Error) { std::string msg; raw_string_ostream Msg(msg); Msg << "invalid operand in inline asm: '" << AsmStr << "'"; MMI->getModule()->getContext().emitError(LocCookie, Msg.str()); } break; } } } OS << "\n\t.att_syntax\n" << (char)0; // null terminate string. } static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI, MachineModuleInfo *MMI, int InlineAsmVariant, int AsmPrinterVariant, AsmPrinter *AP, unsigned LocCookie, raw_ostream &OS) { int CurVariant = -1; // The number of the {.|.|.} region we are in. const char *LastEmitted = AsmStr; // One past the last character emitted. unsigned NumOperands = MI->getNumOperands(); OS << '\t'; while (*LastEmitted) { switch (*LastEmitted) { default: { // Not a special case, emit the string section literally. const char *LiteralEnd = LastEmitted+1; while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' && *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n') ++LiteralEnd; if (CurVariant == -1 || CurVariant == AsmPrinterVariant) OS.write(LastEmitted, LiteralEnd-LastEmitted); LastEmitted = LiteralEnd; break; } case '\n': ++LastEmitted; // Consume newline character. OS << '\n'; // Indent code with newline. break; case '$': { ++LastEmitted; // Consume '$' character. bool Done = true; // Handle escapes. switch (*LastEmitted) { default: Done = false; break; case '$': // $$ -> $ if (CurVariant == -1 || CurVariant == AsmPrinterVariant) OS << '$'; ++LastEmitted; // Consume second '$' character. break; case '(': // $( -> same as GCC's { character. ++LastEmitted; // Consume '(' character. if (CurVariant != -1) report_fatal_error("Nested variants found in inline asm string: '" + Twine(AsmStr) + "'"); CurVariant = 0; // We're in the first variant now. break; case '|': ++LastEmitted; // consume '|' character. if (CurVariant == -1) OS << '|'; // this is gcc's behavior for | outside a variant else ++CurVariant; // We're in the next variant. break; case ')': // $) -> same as GCC's } char. ++LastEmitted; // consume ')' character. if (CurVariant == -1) OS << '}'; // this is gcc's behavior for } outside a variant else CurVariant = -1; break; } if (Done) break; bool HasCurlyBraces = false; if (*LastEmitted == '{') { // ${variable} ++LastEmitted; // Consume '{' character. HasCurlyBraces = true; } // If we have ${:foo}, then this is not a real operand reference, it is a // "magic" string reference, just like in .td files. Arrange to call // PrintSpecial. if (HasCurlyBraces && *LastEmitted == ':') { ++LastEmitted; const char *StrStart = LastEmitted; const char *StrEnd = strchr(StrStart, '}'); if (!StrEnd) report_fatal_error("Unterminated ${:foo} operand in inline asm" " string: '" + Twine(AsmStr) + "'"); std::string Val(StrStart, StrEnd); AP->PrintSpecial(MI, OS, Val.c_str()); LastEmitted = StrEnd+1; break; } const char *IDStart = LastEmitted; const char *IDEnd = IDStart; while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd; unsigned Val; if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val)) report_fatal_error("Bad $ operand number in inline asm string: '" + Twine(AsmStr) + "'"); LastEmitted = IDEnd; char Modifier[2] = { 0, 0 }; if (HasCurlyBraces) { // If we have curly braces, check for a modifier character. This // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm. if (*LastEmitted == ':') { ++LastEmitted; // Consume ':' character. if (*LastEmitted == 0) report_fatal_error("Bad ${:} expression in inline asm string: '" + Twine(AsmStr) + "'"); Modifier[0] = *LastEmitted; ++LastEmitted; // Consume modifier character. } if (*LastEmitted != '}') report_fatal_error("Bad ${} expression in inline asm string: '" + Twine(AsmStr) + "'"); ++LastEmitted; // Consume '}' character. } if (Val >= NumOperands-1) report_fatal_error("Invalid $ operand number in inline asm string: '" + Twine(AsmStr) + "'"); // Okay, we finally have a value number. Ask the target to print this // operand! if (CurVariant == -1 || CurVariant == AsmPrinterVariant) { unsigned OpNo = InlineAsm::MIOp_FirstOperand; bool Error = false; // Scan to find the machine operand number for the operand. for (; Val; --Val) { if (OpNo >= MI->getNumOperands()) break; unsigned OpFlags = MI->getOperand(OpNo).getImm(); OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1; } // We may have a location metadata attached to the end of the // instruction, and at no point should see metadata at any // other point while processing. It's an error if so. if (OpNo >= MI->getNumOperands() || MI->getOperand(OpNo).isMetadata()) { Error = true; } else { unsigned OpFlags = MI->getOperand(OpNo).getImm(); ++OpNo; // Skip over the ID number. if (Modifier[0] == 'l') { // Labels are target independent. // FIXME: What if the operand isn't an MBB, report error? const MCSymbol *Sym = MI->getOperand(OpNo).getMBB()->getSymbol(); Sym->print(OS, AP->MAI); } else { if (InlineAsm::isMemKind(OpFlags)) { Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant, Modifier[0] ? Modifier : nullptr, OS); } else { Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant, Modifier[0] ? Modifier : nullptr, OS); } } } if (Error) { std::string msg; raw_string_ostream Msg(msg); Msg << "invalid operand in inline asm: '" << AsmStr << "'"; MMI->getModule()->getContext().emitError(LocCookie, Msg.str()); } } break; } } } OS << '\n' << (char)0; // null terminate string. } /// EmitInlineAsm - This method formats and emits the specified machine /// instruction that is an inline asm. void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const { assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms"); // Count the number of register definitions to find the asm string. unsigned NumDefs = 0; for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef(); ++NumDefs) assert(NumDefs != MI->getNumOperands()-2 && "No asm string?"); assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?"); // Disassemble the AsmStr, printing out the literal pieces, the operands, etc. const char *AsmStr = MI->getOperand(NumDefs).getSymbolName(); // If this asmstr is empty, just print the #APP/#NOAPP markers. // These are useful to see where empty asm's wound up. if (AsmStr[0] == 0) { OutStreamer->emitRawComment(MAI->getInlineAsmStart()); OutStreamer->emitRawComment(MAI->getInlineAsmEnd()); return; } // Emit the #APP start marker. This has to happen even if verbose-asm isn't // enabled, so we use emitRawComment. OutStreamer->emitRawComment(MAI->getInlineAsmStart()); // Get the !srcloc metadata node if we have it, and decode the loc cookie from // it. unsigned LocCookie = 0; const MDNode *LocMD = nullptr; for (unsigned i = MI->getNumOperands(); i != 0; --i) { if (MI->getOperand(i-1).isMetadata() && (LocMD = MI->getOperand(i-1).getMetadata()) && LocMD->getNumOperands() != 0) { if (const ConstantInt *CI = mdconst::dyn_extract(LocMD->getOperand(0))) { LocCookie = CI->getZExtValue(); break; } } } // Emit the inline asm to a temporary string so we can emit it through // EmitInlineAsm. SmallString<256> StringData; raw_svector_ostream OS(StringData); // The variant of the current asmprinter. int AsmPrinterVariant = MAI->getAssemblerDialect(); InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect(); AsmPrinter *AP = const_cast(this); if (InlineAsmVariant == InlineAsm::AD_ATT) EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant, AP, LocCookie, OS); else EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS); // Reset SanitizeAddress based on the function's attribute. MCTargetOptions MCOptions = TM.Options.MCOptions; MCOptions.SanitizeAddress = MF->getFunction()->hasFnAttribute(Attribute::SanitizeAddress); EmitInlineAsm(OS.str(), getSubtargetInfo(), MCOptions, LocMD, MI->getInlineAsmDialect()); // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't // enabled, so we use emitRawComment. OutStreamer->emitRawComment(MAI->getInlineAsmEnd()); } /// PrintSpecial - Print information related to the specified machine instr /// that is independent of the operand, and may be independent of the instr /// itself. This can be useful for portably encoding the comment character /// or other bits of target-specific knowledge into the asmstrings. The /// syntax used is ${:comment}. Targets can override this to add support /// for their own strange codes. void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS, const char *Code) const { if (!strcmp(Code, "private")) { const DataLayout &DL = MF->getDataLayout(); OS << DL.getPrivateGlobalPrefix(); } else if (!strcmp(Code, "comment")) { OS << MAI->getCommentString(); } else if (!strcmp(Code, "uid")) { // Comparing the address of MI isn't sufficient, because machineinstrs may // be allocated to the same address across functions. // If this is a new LastFn instruction, bump the counter. if (LastMI != MI || LastFn != getFunctionNumber()) { ++Counter; LastMI = MI; LastFn = getFunctionNumber(); } OS << Counter; } else { std::string msg; raw_string_ostream Msg(msg); Msg << "Unknown special formatter '" << Code << "' for machine instr: " << *MI; report_fatal_error(Msg.str()); } } /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM /// instruction, using the specified assembler variant. Targets should /// override this to format as appropriate. bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &O) { // Does this asm operand have a single letter operand modifier? if (ExtraCode && ExtraCode[0]) { if (ExtraCode[1] != 0) return true; // Unknown modifier. const MachineOperand &MO = MI->getOperand(OpNo); switch (ExtraCode[0]) { default: return true; // Unknown modifier. case 'c': // Substitute immediate value without immediate syntax if (MO.getType() != MachineOperand::MO_Immediate) return true; O << MO.getImm(); return false; case 'n': // Negate the immediate constant. if (MO.getType() != MachineOperand::MO_Immediate) return true; O << -MO.getImm(); return false; case 's': // The GCC deprecated s modifier if (MO.getType() != MachineOperand::MO_Immediate) return true; O << ((32 - MO.getImm()) & 31); return false; } } return true; } bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &O) { // Target doesn't support this yet! return true; } void AsmPrinter::emitInlineAsmStart() const {} void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo, const MCSubtargetInfo *EndInfo) const {} Index: head/contrib/llvm/lib/MC/MCContext.cpp =================================================================== --- head/contrib/llvm/lib/MC/MCContext.cpp (revision 317457) +++ head/contrib/llvm/lib/MC/MCContext.cpp (revision 317458) @@ -1,530 +1,532 @@ //===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/MC/MCContext.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Twine.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCAssembler.h" #include "llvm/MC/MCCodeView.h" #include "llvm/MC/MCDwarf.h" #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/CommandLine.h" #include "llvm/Support/ELF.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" using namespace llvm; static cl::opt AsSecureLogFileName("as-secure-log-file-name", cl::desc("As secure log file name (initialized from " "AS_SECURE_LOG_FILE env variable)"), cl::init(getenv("AS_SECURE_LOG_FILE")), cl::Hidden); MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri, const MCObjectFileInfo *mofi, const SourceMgr *mgr, bool DoAutoReset) : SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi), Allocator(), Symbols(Allocator), UsedNames(Allocator), CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), DwarfLocSeen(false), GenDwarfForAssembly(false), GenDwarfFileNumber(0), DwarfVersion(4), AllowTemporaryLabels(true), DwarfCompileUnitID(0), AutoReset(DoAutoReset), HadError(false) { SecureLogFile = AsSecureLogFileName; SecureLog = nullptr; SecureLogUsed = false; if (SrcMgr && SrcMgr->getNumBuffers()) MainFileName = SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier(); } MCContext::~MCContext() { if (AutoReset) reset(); // NOTE: The symbols are all allocated out of a bump pointer allocator, // we don't need to free them here. } //===----------------------------------------------------------------------===// // Module Lifetime Management //===----------------------------------------------------------------------===// void MCContext::reset() { // Call the destructors so the fragments are freed COFFAllocator.DestroyAll(); ELFAllocator.DestroyAll(); MachOAllocator.DestroyAll(); MCSubtargetAllocator.DestroyAll(); UsedNames.clear(); Symbols.clear(); SectionSymbols.clear(); Allocator.Reset(); Instances.clear(); CompilationDir.clear(); MainFileName.clear(); MCDwarfLineTablesCUMap.clear(); SectionsForRanges.clear(); MCGenDwarfLabelEntries.clear(); DwarfDebugFlags = StringRef(); DwarfCompileUnitID = 0; CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0); CVContext.reset(); MachOUniquingMap.clear(); ELFUniquingMap.clear(); COFFUniquingMap.clear(); NextID.clear(); AllowTemporaryLabels = true; DwarfLocSeen = false; GenDwarfForAssembly = false; GenDwarfFileNumber = 0; HadError = false; } //===----------------------------------------------------------------------===// // Symbol Manipulation //===----------------------------------------------------------------------===// MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) { SmallString<128> NameSV; StringRef NameRef = Name.toStringRef(NameSV); assert(!NameRef.empty() && "Normal symbols cannot be unnamed!"); MCSymbol *&Sym = Symbols[NameRef]; if (!Sym) Sym = createSymbol(NameRef, false, false); return Sym; } MCSymbolELF *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) { MCSymbol *&Sym = SectionSymbols[&Section]; if (Sym) return cast(Sym); StringRef Name = Section.getSectionName(); auto NameIter = UsedNames.insert(std::make_pair(Name, false)).first; Sym = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false); return cast(Sym); } MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName, unsigned Idx) { return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName + "$frame_escape_" + Twine(Idx)); } MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) { return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName + "$parent_frame_offset"); } MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) { return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" + FuncName); } 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, IsTemporary); } MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix, bool CanBeUnnamed) { if (CanBeUnnamed && !UseNamesOnTempLabels) return createSymbolImpl(nullptr, true); // Determine whether this is a user written assembler temporary or normal // label, if used. bool IsTemporary = CanBeUnnamed; if (AllowTemporaryLabels && !IsTemporary) IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix()); SmallString<128> NewName = Name; bool AddSuffix = AlwaysAddSuffix; unsigned &NextUniqueID = NextID[Name]; for (;;) { if (AddSuffix) { NewName.resize(Name.size()); raw_svector_ostream(NewName) << NextUniqueID++; } auto NameEntry = UsedNames.insert(std::make_pair(NewName, true)); if (NameEntry.second || !NameEntry.first->second) { // Ok, we found a name. // Mark it as used for a non-section symbol. NameEntry.first->second = true; // Have the MCSymbol object itself refer to the copy of the string that is // embedded in the UsedNames entry. return createSymbolImpl(&*NameEntry.first, IsTemporary); } assert(IsTemporary && "Cannot rename non-temporary symbols"); AddSuffix = true; } llvm_unreachable("Infinite loop"); } MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix, bool CanBeUnnamed) { SmallString<128> NameSV; raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name; return createSymbol(NameSV, AlwaysAddSuffix, CanBeUnnamed); } MCSymbol *MCContext::createLinkerPrivateTempSymbol() { SmallString<128> NameSV; raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp"; return createSymbol(NameSV, true, false); } MCSymbol *MCContext::createTempSymbol(bool CanBeUnnamed) { return createTempSymbol("tmp", true, CanBeUnnamed); } unsigned MCContext::NextInstance(unsigned LocalLabelVal) { MCLabel *&Label = Instances[LocalLabelVal]; if (!Label) Label = new (*this) MCLabel(0); return Label->incInstance(); } unsigned MCContext::GetInstance(unsigned LocalLabelVal) { MCLabel *&Label = Instances[LocalLabelVal]; if (!Label) Label = new (*this) MCLabel(0); return Label->getInstance(); } MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal, unsigned Instance) { MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)]; if (!Sym) Sym = createTempSymbol(false); return Sym; } MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) { unsigned Instance = NextInstance(LocalLabelVal); return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance); } MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before) { unsigned Instance = GetInstance(LocalLabelVal); if (!Before) ++Instance; return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance); } MCSymbol *MCContext::lookupSymbol(const Twine &Name) const { SmallString<128> NameSV; StringRef NameRef = Name.toStringRef(NameSV); return Symbols.lookup(NameRef); } void MCContext::setSymbolValue(MCStreamer &Streamer, StringRef Sym, uint64_t Val) { auto Symbol = getOrCreateSymbol(Sym); Streamer.EmitAssignment(Symbol, MCConstantExpr::create(Val, *this)); } //===----------------------------------------------------------------------===// // 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()) GroupName = Group->getName(); unsigned UniqueID = Section->getUniqueID(); ELFUniquingMap.erase( ELFSectionKey{Section->getSectionName(), GroupName, UniqueID}); auto I = ELFUniquingMap.insert(std::make_pair( ELFSectionKey{Name, GroupName, UniqueID}, Section)) .first; StringRef CachedName = I->first.SectionName; const_cast(Section)->setSectionName(CachedName); } MCSectionELF *MCContext::createELFRelSection(const Twine &Name, unsigned Type, unsigned Flags, unsigned EntrySize, const MCSymbolELF *Group, const MCSectionELF *Associated) { StringMap::iterator I; bool Inserted; std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name.str(), true)); return new (ELFAllocator.Allocate()) MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group, true, nullptr, Associated); } MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix, const Twine &Suffix, unsigned Type, unsigned Flags, unsigned EntrySize) { return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix); } MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type, unsigned Flags, unsigned EntrySize, const Twine &Group, unsigned UniqueID, const char *BeginSymName) { MCSymbolELF *GroupSym = nullptr; if (!Group.isTriviallyEmpty() && !Group.str().empty()) GroupSym = cast(getOrCreateSymbol(Group)); return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID, BeginSymName, nullptr); } MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type, unsigned Flags, unsigned EntrySize, const MCSymbolELF *GroupSym, unsigned UniqueID, const char *BeginSymName, const MCSectionELF *Associated) { StringRef Group = ""; if (GroupSym) Group = GroupSym->getName(); // Do the lookup, if we have a hit, return it. auto IterBool = ELFUniquingMap.insert( std::make_pair(ELFSectionKey{Section.str(), Group, UniqueID}, nullptr)); auto &Entry = *IterBool.first; if (!IterBool.second) return Entry.second; StringRef CachedName = Entry.first.SectionName; SectionKind Kind; if (Flags & ELF::SHF_ARM_PURECODE) Kind = SectionKind::getExecuteOnly(); else if (Flags & ELF::SHF_EXECINSTR) Kind = SectionKind::getText(); else Kind = SectionKind::getReadOnly(); MCSymbol *Begin = nullptr; if (BeginSymName) Begin = createTempSymbol(BeginSymName, false); MCSectionELF *Result = new (ELFAllocator.Allocate()) MCSectionELF(CachedName, Type, Flags, Kind, EntrySize, GroupSym, UniqueID, Begin, Associated); Entry.second = Result; return Result; } MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) { MCSectionELF *Result = new (ELFAllocator.Allocate()) MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4, Group, ~0, nullptr, nullptr); return Result; } MCSectionCOFF *MCContext::getCOFFSection(StringRef Section, unsigned Characteristics, SectionKind Kind, StringRef COMDATSymName, int Selection, unsigned UniqueID, 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, UniqueID}; 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, GenericSectionID, BeginSymName); } MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) { COFFSectionKey T{Section, "", 0, GenericSectionID}; auto Iter = COFFUniquingMap.find(T); if (Iter == COFFUniquingMap.end()) return nullptr; return Iter->second; } MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec, const MCSymbol *KeySym, unsigned UniqueID) { // Return the normal section if we don't have to be associative or unique. if (!KeySym && UniqueID == GenericSectionID) return Sec; // If we have a key symbol, make an associative section with the same name and // kind as the normal section. unsigned Characteristics = Sec->getCharacteristics(); if (KeySym) { Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(), KeySym->getName(), COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID); } return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(), "", 0, UniqueID); } MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) { return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI); } //===----------------------------------------------------------------------===// // Dwarf Management //===----------------------------------------------------------------------===// /// getDwarfFile - takes a file name an number to place in the dwarf file and /// directory tables. If the file number has already been allocated it is an /// error and zero is returned and the client reports the error, else the /// allocated file number is returned. The file numbers may be in any order. unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName, unsigned FileNumber, unsigned CUID) { MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID]; return Table.getFile(Directory, FileName, FileNumber); } /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it /// currently is assigned and false otherwise. bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) { const SmallVectorImpl &MCDwarfFiles = getMCDwarfFiles(CUID); if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size()) return false; return !MCDwarfFiles[FileNumber].Name.empty(); } /// Remove empty sections from SectionStartEndSyms, to avoid generating /// useless debug info for them. void MCContext::finalizeDwarfSections(MCStreamer &MCOS) { SectionsForRanges.remove_if( [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); }); } CodeViewContext &MCContext::getCVContext() { if (!CVContext.get()) CVContext.reset(new CodeViewContext); return *CVContext.get(); } //===----------------------------------------------------------------------===// // Error Reporting //===----------------------------------------------------------------------===// void MCContext::reportError(SMLoc Loc, const Twine &Msg) { HadError = true; - // If we have a source manager use it. Otherwise just use the generic - // report_fatal_error(). - if (!SrcMgr) + // If we have a source manager use it. Otherwise, try using the inline source + // manager. + // If that fails, use the generic report_fatal_error(). + if (SrcMgr) + SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg); + else if (InlineSrcMgr) + InlineSrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg); + else report_fatal_error(Msg, false); - - // Use the source manager to print the message. - SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg); } void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) { reportError(Loc, Msg); // If we reached here, we are failing ungracefully. Run the interrupt handlers // to make sure any special cleanups get done, in particular that we remove // files registered with RemoveFileOnSignal. sys::RunInterruptHandlers(); exit(1); } Index: head/contrib/llvm/lib/MC/MCParser/AsmParser.cpp =================================================================== --- head/contrib/llvm/lib/MC/MCParser/AsmParser.cpp (revision 317457) +++ head/contrib/llvm/lib/MC/MCParser/AsmParser.cpp (revision 317458) @@ -1,5523 +1,5528 @@ //===- AsmParser.cpp - Parser for Assembly Files --------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This class implements the parser for assembly files. // //===----------------------------------------------------------------------===// #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/None.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCCodeView.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCDirectives.h" #include "llvm/MC/MCDwarf.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCInstPrinter.h" #include "llvm/MC/MCInstrDesc.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCParser/AsmCond.h" #include "llvm/MC/MCParser/AsmLexer.h" #include "llvm/MC/MCParser/MCAsmLexer.h" #include "llvm/MC/MCParser/MCAsmParser.h" #include "llvm/MC/MCParser/MCAsmParserUtils.h" #include "llvm/MC/MCParser/MCParsedAsmOperand.h" #include "llvm/MC/MCParser/MCTargetAsmParser.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSection.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/MC/MCValue.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Dwarf.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SMLoc.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/raw_ostream.h" #include #include #include #include #include #include #include #include #include #include #include #include using namespace llvm; MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {} static cl::opt AsmMacroMaxNestingDepth( "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden, cl::desc("The maximum nesting depth allowed for assembly macros.")); namespace { /// \brief Helper types for tracking macro definitions. typedef std::vector MCAsmMacroArgument; typedef std::vector MCAsmMacroArguments; struct MCAsmMacroParameter { StringRef Name; MCAsmMacroArgument Value; bool Required; bool Vararg; MCAsmMacroParameter() : Required(false), Vararg(false) {} }; typedef std::vector MCAsmMacroParameters; struct MCAsmMacro { StringRef Name; StringRef Body; MCAsmMacroParameters Parameters; public: MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P) : Name(N), Body(B), Parameters(std::move(P)) {} }; /// \brief Helper class for storing information about an active macro /// instantiation. struct MacroInstantiation { /// The location of the instantiation. SMLoc InstantiationLoc; /// The buffer where parsing should resume upon instantiation completion. int ExitBuffer; /// The location where parsing should resume upon instantiation completion. SMLoc ExitLoc; /// The depth of TheCondStack at the start of the instantiation. size_t CondStackDepth; public: MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth); }; struct ParseStatementInfo { /// \brief The parsed operands from the last parsed statement. SmallVector, 8> ParsedOperands; /// \brief The opcode from the last parsed instruction. unsigned Opcode; /// \brief Was there an error parsing the inline assembly? bool ParseError; SmallVectorImpl *AsmRewrites; ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {} ParseStatementInfo(SmallVectorImpl *rewrites) : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {} }; /// \brief The concrete assembly parser instance. class AsmParser : public MCAsmParser { AsmParser(const AsmParser &) = delete; void operator=(const AsmParser &) = delete; private: AsmLexer Lexer; MCContext &Ctx; MCStreamer &Out; const MCAsmInfo &MAI; SourceMgr &SrcMgr; SourceMgr::DiagHandlerTy SavedDiagHandler; void *SavedDiagContext; std::unique_ptr PlatformParser; /// This is the current buffer index we're lexing from as managed by the /// SourceMgr object. unsigned CurBuffer; AsmCond TheCondState; std::vector TheCondStack; /// \brief maps directive names to handler methods in parser /// extensions. Extensions register themselves in this map by calling /// addDirectiveHandler. StringMap ExtensionDirectiveMap; /// \brief Map of currently defined macros. StringMap MacroMap; /// \brief Stack of active macro instantiations. std::vector ActiveMacros; /// \brief List of bodies of anonymous macros. std::deque MacroLikeBodies; /// Boolean tracking whether macro substitution is enabled. unsigned MacrosEnabledFlag : 1; /// \brief Keeps track of how many .macro's have been instantiated. unsigned NumOfMacroInstantiations; /// The values from the last parsed cpp hash file line comment if any. struct CppHashInfoTy { StringRef Filename; int64_t LineNumber = 0; SMLoc Loc; unsigned Buf = 0; }; CppHashInfoTy CppHashInfo; /// \brief List of forward directional labels for diagnosis at the end. SmallVector, 4> DirLabels; /// When generating dwarf for assembly source files we need to calculate the /// logical line number based on the last parsed cpp hash file line comment /// and current line. Since this is slow and messes up the SourceMgr's /// cache we save the last info we queried with SrcMgr.FindLineNumber(). SMLoc LastQueryIDLoc; unsigned LastQueryBuffer; unsigned LastQueryLine; /// 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; public: AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out, - const MCAsmInfo &MAI); + const MCAsmInfo &MAI, unsigned CB); ~AsmParser() override; bool Run(bool NoInitialTextSection, bool NoFinalize = false) override; void addDirectiveHandler(StringRef Directive, ExtensionDirectiveHandler Handler) override { ExtensionDirectiveMap[Directive] = Handler; } void addAliasForDirective(StringRef Directive, StringRef Alias) override { DirectiveKindMap[Directive] = DirectiveKindMap[Alias]; } public: /// @name MCAsmParser Interface /// { SourceMgr &getSourceManager() override { return SrcMgr; } MCAsmLexer &getLexer() override { return Lexer; } MCContext &getContext() override { return Ctx; } MCStreamer &getStreamer() override { return Out; } CodeViewContext &getCVContext() { return Ctx.getCVContext(); } unsigned getAssemblerDialect() override { if (AssemblerDialect == ~0U) return MAI.getAssemblerDialect(); else return AssemblerDialect; } void setAssemblerDialect(unsigned i) override { AssemblerDialect = i; } void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override; bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override; bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override; const AsmToken &Lex() override; void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; Lexer.setParsingMSInlineAsm(V); } bool isParsingInlineAsm() override { return ParsingInlineAsm; } bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString, unsigned &NumOutputs, unsigned &NumInputs, SmallVectorImpl > &OpDecls, SmallVectorImpl &Constraints, SmallVectorImpl &Clobbers, const MCInstrInfo *MII, const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) override; bool parseExpression(const MCExpr *&Res); bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override; bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override; bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override; bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res, SMLoc &EndLoc) override; bool parseAbsoluteExpression(int64_t &Res) override; /// \brief Parse a floating point expression using the float \p Semantics /// and set \p Res to the value. bool parseRealValue(const fltSemantics &Semantics, APInt &Res); /// \brief Parse an identifier or string (as a quoted identifier) /// and set \p Res to the identifier contents. bool parseIdentifier(StringRef &Res) override; void eatToEndOfStatement() override; bool checkForValidSection() override; /// } private: bool parseStatement(ParseStatementInfo &Info, MCAsmParserSemaCallback *SI); bool parseCurlyBlockScope(SmallVectorImpl& AsmStrRewrites); bool parseCppHashLineFilenameComment(SMLoc L); void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body, ArrayRef Parameters); bool expandMacro(raw_svector_ostream &OS, StringRef Body, ArrayRef Parameters, ArrayRef A, bool EnableAtPseudoVariable, SMLoc L); /// \brief Are macros enabled in the parser? bool areMacrosEnabled() {return MacrosEnabledFlag;} /// \brief Control a flag in the parser that enables or disables macros. void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;} /// \brief Lookup a previously defined macro. /// \param Name Macro name. /// \returns Pointer to macro. NULL if no such macro was defined. const MCAsmMacro* lookupMacro(StringRef Name); /// \brief Define a new macro with the given name and information. void defineMacro(StringRef Name, MCAsmMacro Macro); /// \brief Undefine a macro. If no such macro was defined, it's a no-op. void undefineMacro(StringRef Name); /// \brief Are we inside a macro instantiation? bool isInsideMacroInstantiation() {return !ActiveMacros.empty();} /// \brief Handle entry to macro instantiation. /// /// \param M The macro. /// \param NameLoc Instantiation location. bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc); /// \brief Handle exit from macro instantiation. void handleMacroExit(); /// \brief Extract AsmTokens for a macro argument. bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg); /// \brief Parse all macro arguments for a given macro. bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A); void printMacroInstantiations(); void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg, SMRange Range = None) const { ArrayRef Ranges(Range); SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges); } static void DiagHandler(const SMDiagnostic &Diag, void *Context); /// \brief Enter the specified file. This returns true on failure. bool enterIncludeFile(const std::string &Filename); /// \brief Process the specified file for the .incbin directive. /// This returns true on failure. bool processIncbinFile(const std::string &Filename, int64_t Skip = 0, const MCExpr *Count = nullptr, SMLoc Loc = SMLoc()); /// \brief Reset the current lexer position to that given by \p Loc. The /// current token is not set; clients should ensure Lex() is called /// subsequently. /// /// \param InBuffer If not 0, should be the known buffer id that contains the /// location. void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0); /// \brief Parse up to the end of statement and a return the contents from the /// current token until the end of the statement; the current token on exit /// will be either the EndOfStatement or EOF. StringRef parseStringToEndOfStatement() override; /// \brief Parse until the end of a statement or a comma is encountered, /// return the contents from the current token up to the end or comma. StringRef parseStringToComma(); bool parseAssignment(StringRef Name, bool allow_redef, bool NoDeadStrip = false); unsigned getBinOpPrecedence(AsmToken::TokenKind K, MCBinaryExpr::Opcode &Kind); bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc); bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc); bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc); bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc); bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName); bool parseCVFileId(int64_t &FileId, StringRef DirectiveName); // Generic (target and platform independent) directive parsing. enum DirectiveKind { DK_NO_DIRECTIVE, // Placeholder DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT, DK_RELOC, DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA, DK_DC, DK_DC_A, DK_DC_B, DK_DC_D, DK_DC_L, DK_DC_S, DK_DC_W, DK_DC_X, DK_DCB, DK_DCB_B, DK_DCB_D, DK_DCB_L, DK_DCB_S, DK_DCB_W, DK_DCB_X, DK_DS, DK_DS_B, DK_DS_D, DK_DS_L, DK_DS_P, DK_DS_S, DK_DS_W, DK_DS_X, DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW, DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR, DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK, DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE, DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT, DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC, DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB, DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF, DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS, DK_CV_FILE, DK_CV_FUNC_ID, DK_CV_INLINE_SITE_ID, DK_CV_LOC, DK_CV_LINETABLE, DK_CV_INLINE_LINETABLE, DK_CV_DEF_RANGE, DK_CV_STRINGTABLE, DK_CV_FILECHECKSUMS, DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA, DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER, DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA, DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE, DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED, DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE, DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM, DK_SLEB128, DK_ULEB128, DK_ERR, DK_ERROR, DK_WARNING, DK_END }; /// \brief Maps directive name --> DirectiveKind enum, for /// directives parsed by this class. StringMap DirectiveKindMap; // ".ascii", ".asciz", ".string" bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated); bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc" bool parseDirectiveValue(StringRef IDVal, unsigned Size); // ".byte", ".long", ... bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ... bool parseDirectiveRealValue(StringRef IDVal, const fltSemantics &); // ".single", ... bool parseDirectiveFill(); // ".fill" bool parseDirectiveZero(); // ".zero" // ".set", ".equ", ".equiv" bool parseDirectiveSet(StringRef IDVal, bool allow_redef); bool parseDirectiveOrg(); // ".org" // ".align{,32}", ".p2align{,w,l}" bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize); // ".file", ".line", ".loc", ".stabs" bool parseDirectiveFile(SMLoc DirectiveLoc); bool parseDirectiveLine(); bool parseDirectiveLoc(); bool parseDirectiveStabs(); // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable", // ".cv_inline_linetable", ".cv_def_range" bool parseDirectiveCVFile(); bool parseDirectiveCVFuncId(); bool parseDirectiveCVInlineSiteId(); bool parseDirectiveCVLoc(); bool parseDirectiveCVLinetable(); bool parseDirectiveCVInlineLinetable(); bool parseDirectiveCVDefRange(); bool parseDirectiveCVStringTable(); bool parseDirectiveCVFileChecksums(); // .cfi directives bool parseDirectiveCFIRegister(SMLoc DirectiveLoc); bool parseDirectiveCFIWindowSave(); bool parseDirectiveCFISections(); bool parseDirectiveCFIStartProc(); bool parseDirectiveCFIEndProc(); bool parseDirectiveCFIDefCfaOffset(); bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc); bool parseDirectiveCFIAdjustCfaOffset(); bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc); bool parseDirectiveCFIOffset(SMLoc DirectiveLoc); bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc); bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality); bool parseDirectiveCFIRememberState(); bool parseDirectiveCFIRestoreState(); bool parseDirectiveCFISameValue(SMLoc DirectiveLoc); bool parseDirectiveCFIRestore(SMLoc DirectiveLoc); bool parseDirectiveCFIEscape(); bool parseDirectiveCFISignalFrame(); bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc); // macro directives bool parseDirectivePurgeMacro(SMLoc DirectiveLoc); bool parseDirectiveExitMacro(StringRef Directive); bool parseDirectiveEndMacro(StringRef Directive); bool parseDirectiveMacro(SMLoc DirectiveLoc); bool parseDirectiveMacrosOnOff(StringRef Directive); // ".bundle_align_mode" bool parseDirectiveBundleAlignMode(); // ".bundle_lock" bool parseDirectiveBundleLock(); // ".bundle_unlock" bool parseDirectiveBundleUnlock(); // ".space", ".skip" bool parseDirectiveSpace(StringRef IDVal); // ".dcb" bool parseDirectiveDCB(StringRef IDVal, unsigned Size); bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &); // ".ds" bool parseDirectiveDS(StringRef IDVal, unsigned Size); // .sleb128 (Signed=true) and .uleb128 (Signed=false) bool parseDirectiveLEB128(bool Signed); /// \brief Parse a directive like ".globl" which /// accepts a single symbol (which should be a label or an external). bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr); bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm" bool parseDirectiveAbort(); // ".abort" bool parseDirectiveInclude(); // ".include" bool parseDirectiveIncbin(); // ".incbin" // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne" bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind); // ".ifb" or ".ifnb", depending on ExpectBlank. bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank); // ".ifc" or ".ifnc", depending on ExpectEqual. bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual); // ".ifeqs" or ".ifnes", depending on ExpectEqual. bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual); // ".ifdef" or ".ifndef", depending on expect_defined bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined); bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif" bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else" bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif bool parseEscapedString(std::string &Data) override; const MCExpr *applyModifierToExpr(const MCExpr *E, MCSymbolRefExpr::VariantKind Variant); // Macro-like directives MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc); void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc, raw_svector_ostream &OS); bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive); bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp" bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc" bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr" // "_emit" or "__emit" bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info, size_t Len); // "align" bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info); // "end" bool parseDirectiveEnd(SMLoc DirectiveLoc); // ".err" or ".error" bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage); // ".warning" bool parseDirectiveWarning(SMLoc DirectiveLoc); void initializeDirectiveKindMap(); }; } // end anonymous namespace namespace llvm { extern MCAsmParserExtension *createDarwinAsmParser(); extern MCAsmParserExtension *createELFAsmParser(); extern MCAsmParserExtension *createCOFFAsmParser(); } // end namespace llvm enum { DEFAULT_ADDRSPACE = 0 }; AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out, - const MCAsmInfo &MAI) + const MCAsmInfo &MAI, unsigned CB = 0) : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM), - PlatformParser(nullptr), CurBuffer(SM.getMainFileID()), + PlatformParser(nullptr), CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true), CppHashInfo(), AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) { HadError = false; // Save the old handler. SavedDiagHandler = SrcMgr.getDiagHandler(); SavedDiagContext = SrcMgr.getDiagContext(); // Set our own handler which calls the saved handler. SrcMgr.setDiagHandler(DiagHandler, this); Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); // Initialize the platform / file format parser. 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; } PlatformParser->Initialize(*this); initializeDirectiveKindMap(); NumOfMacroInstantiations = 0; } AsmParser::~AsmParser() { assert((HadError || ActiveMacros.empty()) && "Unexpected active macro instantiation!"); + + // Restore the saved diagnostics handler and context for use during + // finalization. + SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext); } void AsmParser::printMacroInstantiations() { // Print the active macro instantiation stack. for (std::vector::const_reverse_iterator it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it) printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note, "while in macro instantiation"); } void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) { printPendingErrors(); printMessage(L, SourceMgr::DK_Note, Msg, Range); printMacroInstantiations(); } bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) { if(getTargetParser().getTargetOptions().MCNoWarn) return false; if (getTargetParser().getTargetOptions().MCFatalWarnings) return Error(L, Msg, Range); printMessage(L, SourceMgr::DK_Warning, Msg, Range); printMacroInstantiations(); return false; } bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) { HadError = true; printMessage(L, SourceMgr::DK_Error, Msg, Range); printMacroInstantiations(); return true; } bool AsmParser::enterIncludeFile(const std::string &Filename) { std::string IncludedFile; unsigned NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile); if (!NewBuf) return true; CurBuffer = NewBuf; Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); return false; } /// Process the specified .incbin file by searching for it in the include paths /// then just emitting the byte contents of the file to the streamer. This /// returns true on failure. bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip, const MCExpr *Count, SMLoc Loc) { std::string IncludedFile; unsigned NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile); if (!NewBuf) return true; // Pick up the bytes from the file and emit them. StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(); Bytes = Bytes.drop_front(Skip); if (Count) { int64_t Res; if (!Count->evaluateAsAbsolute(Res)) return Error(Loc, "expected absolute expression"); if (Res < 0) return Warning(Loc, "negative count has no effect"); Bytes = Bytes.take_front(Res); } getStreamer().EmitBytes(Bytes); return false; } void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) { CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc); Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(), Loc.getPointer()); } const AsmToken &AsmParser::Lex() { if (Lexer.getTok().is(AsmToken::Error)) Error(Lexer.getErrLoc(), Lexer.getErr()); // if it's a end of statement with a comment in it if (getTok().is(AsmToken::EndOfStatement)) { // if this is a line comment output it. if (getTok().getString().front() != '\n' && getTok().getString().front() != '\r' && MAI.preserveAsmComments()) Out.addExplicitComment(Twine(getTok().getString())); } const AsmToken *tok = &Lexer.Lex(); // Parse comments here to be deferred until end of next statement. while (tok->is(AsmToken::Comment)) { if (MAI.preserveAsmComments()) Out.addExplicitComment(Twine(tok->getString())); tok = &Lexer.Lex(); } if (tok->is(AsmToken::Eof)) { // If this is the end of an included file, pop the parent file off the // include stack. SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer); if (ParentIncludeLoc != SMLoc()) { jumpToLoc(ParentIncludeLoc); return Lex(); } } return *tok; } bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) { // Create the initial section, if requested. if (!NoInitialTextSection) Out.InitSections(false); // Prime the lexer. Lex(); HadError = false; AsmCond StartingCondState = TheCondState; // If we are generating dwarf for assembly source files save the initial text // section and generate a .file directive. if (getContext().getGenDwarfForAssembly()) { MCSection *Sec = getStreamer().getCurrentSectionOnly(); if (!Sec->getBeginSymbol()) { MCSymbol *SectionStartSym = getContext().createTempSymbol(); getStreamer().EmitLabel(SectionStartSym); Sec->setBeginSymbol(SectionStartSym); } bool InsertResult = getContext().addGenDwarfSection(Sec); assert(InsertResult && ".text section should not have debug info yet"); (void)InsertResult; getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective( 0, StringRef(), getContext().getMainFileName())); } // While we have input, parse each statement. while (Lexer.isNot(AsmToken::Eof)) { ParseStatementInfo Info; if (!parseStatement(Info, nullptr)) continue; // If we have a Lexer Error we are on an Error Token. Load in Lexer Error // for printing ErrMsg via Lex() only if no (presumably better) parser error // exists. if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) { Lex(); } // parseStatement returned true so may need to emit an error. printPendingErrors(); // Skipping to the next line if needed. if (!getLexer().isAtStartOfStatement()) eatToEndOfStatement(); } // All errors should have been emitted. assert(!hasPendingError() && "unexpected error from parseStatement"); getTargetParser().flushPendingInstructions(getStreamer()); if (TheCondState.TheCond != StartingCondState.TheCond || TheCondState.Ignore != StartingCondState.Ignore) printError(getTok().getLoc(), "unmatched .ifs or .elses"); // Check to see there are no empty DwarfFile slots. const auto &LineTables = getContext().getMCDwarfLineTables(); if (!LineTables.empty()) { unsigned Index = 0; for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) { if (File.Name.empty() && Index != 0) printError(getTok().getLoc(), "unassigned file number: " + Twine(Index) + " for .file directives"); ++Index; } } // 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) { if (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. printError(getTok().getLoc(), "assembler local symbol '" + Sym->getName() + "' not defined"); } } // Temporary symbols like the ones for directional jumps don't go in the // symbol table. They also need to be diagnosed in all (final) cases. for (std::tuple &LocSym : DirLabels) { if (std::get<2>(LocSym)->isUndefined()) { // Reset the state of any "# line file" directives we've seen to the // context as it was at the diagnostic site. CppHashInfo = std::get<1>(LocSym); printError(std::get<0>(LocSym), "directional label undefined"); } } } // Finalize the output stream if there are no errors and if the client wants // us to. if (!HadError && !NoFinalize) Out.Finish(); return HadError || getContext().hadError(); } bool AsmParser::checkForValidSection() { if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) { Out.InitSections(false); return Error(getTok().getLoc(), "expected section directive before assembly directive"); } return false; } /// \brief Throw away the rest of the line for testing purposes. void AsmParser::eatToEndOfStatement() { while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof)) Lexer.Lex(); // Eat EOL. if (Lexer.is(AsmToken::EndOfStatement)) Lexer.Lex(); } StringRef AsmParser::parseStringToEndOfStatement() { const char *Start = getTok().getLoc().getPointer(); while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof)) Lexer.Lex(); const char *End = getTok().getLoc().getPointer(); return StringRef(Start, End - Start); } StringRef AsmParser::parseStringToComma() { const char *Start = getTok().getLoc().getPointer(); while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof)) Lexer.Lex(); const char *End = getTok().getLoc().getPointer(); return StringRef(Start, End - Start); } /// \brief Parse a paren expression and return it. /// NOTE: This assumes the leading '(' has already been consumed. /// /// parenexpr ::= expr) /// bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) { if (parseExpression(Res)) return true; if (Lexer.isNot(AsmToken::RParen)) return TokError("expected ')' in parentheses expression"); EndLoc = Lexer.getTok().getEndLoc(); Lex(); return false; } /// \brief Parse a bracket expression and return it. /// NOTE: This assumes the leading '[' has already been consumed. /// /// bracketexpr ::= expr] /// bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) { if (parseExpression(Res)) return true; EndLoc = getTok().getEndLoc(); if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression")) return true; return false; } /// \brief Parse a primary expression and return it. /// primaryexpr ::= (parenexpr /// primaryexpr ::= symbol /// primaryexpr ::= number /// primaryexpr ::= '.' /// primaryexpr ::= ~,+,- primaryexpr bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) { SMLoc FirstTokenLoc = getLexer().getLoc(); AsmToken::TokenKind FirstTokenKind = Lexer.getKind(); switch (FirstTokenKind) { default: return TokError("unknown token in expression"); // If we have an error assume that we've already handled it. case AsmToken::Error: return true; case AsmToken::Exclaim: Lex(); // Eat the operator. if (parsePrimaryExpr(Res, EndLoc)) return true; Res = MCUnaryExpr::createLNot(Res, getContext()); return false; case AsmToken::Dollar: case AsmToken::At: case AsmToken::String: case AsmToken::Identifier: { StringRef Identifier; if (parseIdentifier(Identifier)) { // We may have failed but $ may be a valid token. if (getTok().is(AsmToken::Dollar)) { if (Lexer.getMAI().getDollarIsPC()) { Lex(); // This is a '$' reference, which references the current PC. Emit a // temporary label to the streamer and refer to it. MCSymbol *Sym = Ctx.createTempSymbol(); Out.EmitLabel(Sym); Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext()); EndLoc = FirstTokenLoc; return false; } return Error(FirstTokenLoc, "invalid token in expression"); } } // Parse symbol variant std::pair Split; if (!MAI.useParensForSymbolVariant()) { if (FirstTokenKind == AsmToken::String) { if (Lexer.is(AsmToken::At)) { Lex(); // eat @ SMLoc AtLoc = getLexer().getLoc(); StringRef VName; if (parseIdentifier(VName)) return Error(AtLoc, "expected symbol variant after '@'"); Split = std::make_pair(Identifier, VName); } } else { Split = Identifier.split('@'); } } else if (Lexer.is(AsmToken::LParen)) { Lex(); // eat '('. StringRef VName; parseIdentifier(VName); // eat ')'. if (parseToken(AsmToken::RParen, "unexpected token in variant, expected ')'")) return true; Split = std::make_pair(Identifier, VName); } EndLoc = SMLoc::getFromPointer(Identifier.end()); // This is a symbol reference. StringRef SymbolName = Identifier; if (SymbolName.empty()) return true; MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; // Lookup the symbol variant if used. if (Split.second.size()) { Variant = MCSymbolRefExpr::getVariantKindForName(Split.second); if (Variant != MCSymbolRefExpr::VK_Invalid) { SymbolName = Split.first; } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) { Variant = MCSymbolRefExpr::VK_None; } else { return Error(SMLoc::getFromPointer(Split.second.begin()), "invalid variant '" + Split.second + "'"); } } MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName); // If this is an absolute variable reference, substitute it now to preserve // semantics in the face of reassignment. if (Sym->isVariable() && isa(Sym->getVariableValue(/*SetUsed*/ false))) { if (Variant) return Error(EndLoc, "unexpected modifier on variable reference"); Res = Sym->getVariableValue(/*SetUsed*/ false); return false; } // Otherwise create a symbol ref. Res = MCSymbolRefExpr::create(Sym, Variant, getContext()); return false; } case AsmToken::BigNum: return TokError("literal value out of range for directive"); case AsmToken::Integer: { SMLoc Loc = getTok().getLoc(); int64_t IntVal = getTok().getIntVal(); Res = MCConstantExpr::create(IntVal, getContext()); EndLoc = Lexer.getTok().getEndLoc(); Lex(); // Eat token. // Look for 'b' or 'f' following an Integer as a directional label if (Lexer.getKind() == AsmToken::Identifier) { StringRef IDVal = getTok().getString(); // Lookup the symbol variant if used. std::pair Split = IDVal.split('@'); MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; if (Split.first.size() != IDVal.size()) { Variant = MCSymbolRefExpr::getVariantKindForName(Split.second); if (Variant == MCSymbolRefExpr::VK_Invalid) return TokError("invalid variant '" + Split.second + "'"); IDVal = Split.first; } if (IDVal == "f" || IDVal == "b") { MCSymbol *Sym = Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b"); Res = MCSymbolRefExpr::create(Sym, Variant, getContext()); if (IDVal == "b" && Sym->isUndefined()) return Error(Loc, "directional label undefined"); DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym)); EndLoc = Lexer.getTok().getEndLoc(); Lex(); // Eat identifier. } } return false; } case AsmToken::Real: { APFloat RealVal(APFloat::IEEEdouble(), getTok().getString()); uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue(); Res = MCConstantExpr::create(IntVal, getContext()); EndLoc = Lexer.getTok().getEndLoc(); Lex(); // Eat token. return false; } case AsmToken::Dot: { // This is a '.' reference, which references the current PC. Emit a // temporary label to the streamer and refer to it. MCSymbol *Sym = Ctx.createTempSymbol(); Out.EmitLabel(Sym); Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext()); EndLoc = Lexer.getTok().getEndLoc(); Lex(); // Eat identifier. return false; } case AsmToken::LParen: Lex(); // Eat the '('. return parseParenExpr(Res, EndLoc); case AsmToken::LBrac: if (!PlatformParser->HasBracketExpressions()) return TokError("brackets expression not supported on this target"); Lex(); // Eat the '['. return parseBracketExpr(Res, EndLoc); case AsmToken::Minus: Lex(); // Eat the operator. if (parsePrimaryExpr(Res, EndLoc)) return true; Res = MCUnaryExpr::createMinus(Res, getContext()); return false; case AsmToken::Plus: Lex(); // Eat the operator. if (parsePrimaryExpr(Res, EndLoc)) return true; Res = MCUnaryExpr::createPlus(Res, getContext()); return false; case AsmToken::Tilde: Lex(); // Eat the operator. if (parsePrimaryExpr(Res, EndLoc)) return true; Res = MCUnaryExpr::createNot(Res, getContext()); return false; // MIPS unary expression operators. The lexer won't generate these tokens if // MCAsmInfo::HasMipsExpressions is false for the target. case AsmToken::PercentCall16: case AsmToken::PercentCall_Hi: case AsmToken::PercentCall_Lo: case AsmToken::PercentDtprel_Hi: case AsmToken::PercentDtprel_Lo: case AsmToken::PercentGot: case AsmToken::PercentGot_Disp: case AsmToken::PercentGot_Hi: case AsmToken::PercentGot_Lo: case AsmToken::PercentGot_Ofst: case AsmToken::PercentGot_Page: case AsmToken::PercentGottprel: case AsmToken::PercentGp_Rel: case AsmToken::PercentHi: case AsmToken::PercentHigher: case AsmToken::PercentHighest: case AsmToken::PercentLo: case AsmToken::PercentNeg: case AsmToken::PercentPcrel_Hi: case AsmToken::PercentPcrel_Lo: case AsmToken::PercentTlsgd: case AsmToken::PercentTlsldm: case AsmToken::PercentTprel_Hi: case AsmToken::PercentTprel_Lo: Lex(); // Eat the operator. if (Lexer.isNot(AsmToken::LParen)) return TokError("expected '(' after operator"); Lex(); // Eat the operator. if (parseExpression(Res, EndLoc)) return true; if (Lexer.isNot(AsmToken::RParen)) return TokError("expected ')'"); Lex(); // Eat the operator. Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx); return !Res; } } bool AsmParser::parseExpression(const MCExpr *&Res) { SMLoc EndLoc; return parseExpression(Res, EndLoc); } const MCExpr * AsmParser::applyModifierToExpr(const MCExpr *E, MCSymbolRefExpr::VariantKind Variant) { // Ask the target implementation about this expression first. const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx); if (NewE) return NewE; // Recurse over the given expression, rebuilding it to apply the given variant // if there is exactly one symbol. switch (E->getKind()) { case MCExpr::Target: case MCExpr::Constant: return nullptr; case MCExpr::SymbolRef: { const MCSymbolRefExpr *SRE = cast(E); if (SRE->getKind() != MCSymbolRefExpr::VK_None) { TokError("invalid variant on expression '" + getTok().getIdentifier() + "' (already modified)"); return E; } return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext()); } case MCExpr::Unary: { const MCUnaryExpr *UE = cast(E); const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant); if (!Sub) return nullptr; return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext()); } case MCExpr::Binary: { const MCBinaryExpr *BE = cast(E); const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant); const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant); if (!LHS && !RHS) return nullptr; if (!LHS) LHS = BE->getLHS(); if (!RHS) RHS = BE->getRHS(); return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext()); } } llvm_unreachable("Invalid expression kind!"); } /// \brief Parse an expression and return it. /// /// expr ::= expr &&,|| expr -> lowest. /// expr ::= expr |,^,&,! expr /// expr ::= expr ==,!=,<>,<,<=,>,>= expr /// expr ::= expr <<,>> expr /// expr ::= expr +,- expr /// expr ::= expr *,/,% expr -> highest. /// expr ::= primaryexpr /// bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) { // Parse the expression. Res = nullptr; if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc)) return true; // As a special case, we support 'a op b @ modifier' by rewriting the // expression to include the modifier. This is inefficient, but in general we // expect users to use 'a@modifier op b'. if (Lexer.getKind() == AsmToken::At) { Lex(); if (Lexer.isNot(AsmToken::Identifier)) return TokError("unexpected symbol modifier following '@'"); MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier()); if (Variant == MCSymbolRefExpr::VK_Invalid) return TokError("invalid variant '" + getTok().getIdentifier() + "'"); const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant); if (!ModifiedRes) { return TokError("invalid modifier '" + getTok().getIdentifier() + "' (no symbols present)"); } Res = ModifiedRes; Lex(); } // Try to constant fold it up front, if possible. int64_t Value; if (Res->evaluateAsAbsolute(Value)) Res = MCConstantExpr::create(Value, getContext()); return false; } bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) { Res = nullptr; return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc); } bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res, SMLoc &EndLoc) { if (parseParenExpr(Res, EndLoc)) return true; for (; ParenDepth > 0; --ParenDepth) { if (parseBinOpRHS(1, Res, EndLoc)) return true; // We don't Lex() the last RParen. // This is the same behavior as parseParenExpression(). if (ParenDepth - 1 > 0) { EndLoc = getTok().getEndLoc(); if (parseToken(AsmToken::RParen, "expected ')' in parentheses expression")) return true; } } return false; } bool AsmParser::parseAbsoluteExpression(int64_t &Res) { const MCExpr *Expr; SMLoc StartLoc = Lexer.getLoc(); if (parseExpression(Expr)) return true; if (!Expr->evaluateAsAbsolute(Res)) return Error(StartLoc, "expected absolute expression"); 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) { switch (K) { default: return 0; // not a binop. // Lowest Precedence: &&, || case AsmToken::AmpAmp: Kind = MCBinaryExpr::LAnd; return 2; case AsmToken::PipePipe: Kind = MCBinaryExpr::LOr; return 1; // Low 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; // Low Intermediate Precedence: +, - case AsmToken::Plus: Kind = MCBinaryExpr::Add; return 4; case AsmToken::Minus: Kind = MCBinaryExpr::Sub; return 4; // High Intermediate Precedence: |, &, ^ // // FIXME: gas seems to support '!' as an infix operator? case AsmToken::Pipe: Kind = MCBinaryExpr::Or; return 5; case AsmToken::Caret: Kind = MCBinaryExpr::Xor; return 5; case AsmToken::Amp: Kind = MCBinaryExpr::And; 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; case AsmToken::LessLess: Kind = MCBinaryExpr::Shl; return 6; case AsmToken::GreaterGreater: Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr; return 6; } } unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K, MCBinaryExpr::Opcode &Kind) { bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr(); return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr) : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr); } /// \brief Parse all binary operators with precedence >= 'Precedence'. /// Res contains the LHS of the expression on input. bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc) { while (true) { MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add; unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind); // If the next token is lower precedence than we are allowed to eat, return // successfully with what we ate already. if (TokPrec < Precedence) return false; Lex(); // Eat the next primary expression. const MCExpr *RHS; if (parsePrimaryExpr(RHS, EndLoc)) return true; // If BinOp binds less tightly with RHS than the operator after RHS, let // the pending operator take RHS as its LHS. MCBinaryExpr::Opcode Dummy; unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy); if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc)) return true; // Merge LHS and RHS according to operator. Res = MCBinaryExpr::create(Kind, Res, RHS, getContext()); } } /// ParseStatement: /// ::= EndOfStatement /// ::= Label* Directive ...Operands... EndOfStatement /// ::= Label* Identifier OperandList* EndOfStatement bool AsmParser::parseStatement(ParseStatementInfo &Info, MCAsmParserSemaCallback *SI) { assert(!hasPendingError() && "parseStatement started with pending error"); // Eat initial spaces and comments while (Lexer.is(AsmToken::Space)) Lex(); if (Lexer.is(AsmToken::EndOfStatement)) { // if this is a line comment we can drop it safely if (getTok().getString().front() == '\r' || getTok().getString().front() == '\n') Out.AddBlankLine(); Lex(); return false; } if (Lexer.is(AsmToken::Hash)) { // Seeing a hash here means that it was an end-of-line comment in // an asm syntax where hash's are not comment and the previous // statement parser did not check the end of statement. Relex as // EndOfStatement. StringRef CommentStr = parseStringToEndOfStatement(); Lexer.Lex(); Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr)); return false; } // Statements always start with an identifier. AsmToken ID = getTok(); SMLoc IDLoc = ID.getLoc(); StringRef IDVal; int64_t LocalLabelVal = -1; if (Lexer.is(AsmToken::HashDirective)) return parseCppHashLineFilenameComment(IDLoc); // Allow an integer followed by a ':' as a directional local label. if (Lexer.is(AsmToken::Integer)) { LocalLabelVal = getTok().getIntVal(); if (LocalLabelVal < 0) { if (!TheCondState.Ignore) { Lex(); // always eat a token return Error(IDLoc, "unexpected token at start of statement"); } IDVal = ""; } else { IDVal = getTok().getString(); Lex(); // Consume the integer token to be used as an identifier token. if (Lexer.getKind() != AsmToken::Colon) { if (!TheCondState.Ignore) { Lex(); // always eat a token return Error(IDLoc, "unexpected token at start of statement"); } } } } else if (Lexer.is(AsmToken::Dot)) { // Treat '.' as a valid identifier in this context. Lex(); IDVal = "."; } else if (Lexer.is(AsmToken::LCurly)) { // Treat '{' as a valid identifier in this context. Lex(); IDVal = "{"; } else if (Lexer.is(AsmToken::RCurly)) { // Treat '}' as a valid identifier in this context. Lex(); IDVal = "}"; } else if (parseIdentifier(IDVal)) { if (!TheCondState.Ignore) { Lex(); // always eat a token return Error(IDLoc, "unexpected token at start of statement"); } IDVal = ""; } // Handle conditional assembly here before checking for skipping. We // have to do this so that .endif isn't skipped in a ".if 0" block for // example. StringMap::const_iterator DirKindIt = DirectiveKindMap.find(IDVal); DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE : DirKindIt->getValue(); switch (DirKind) { default: break; case DK_IF: case DK_IFEQ: case DK_IFGE: case DK_IFGT: case DK_IFLE: case DK_IFLT: case DK_IFNE: return parseDirectiveIf(IDLoc, DirKind); case DK_IFB: return parseDirectiveIfb(IDLoc, true); case DK_IFNB: return parseDirectiveIfb(IDLoc, false); case DK_IFC: return parseDirectiveIfc(IDLoc, true); case DK_IFEQS: return parseDirectiveIfeqs(IDLoc, true); case DK_IFNC: return parseDirectiveIfc(IDLoc, false); case DK_IFNES: return parseDirectiveIfeqs(IDLoc, false); case DK_IFDEF: return parseDirectiveIfdef(IDLoc, true); case DK_IFNDEF: case DK_IFNOTDEF: return parseDirectiveIfdef(IDLoc, false); case DK_ELSEIF: return parseDirectiveElseIf(IDLoc); case DK_ELSE: return parseDirectiveElse(IDLoc); case DK_ENDIF: return parseDirectiveEndIf(IDLoc); } // Ignore the statement if in the middle of inactive conditional // (e.g. ".if 0"). if (TheCondState.Ignore) { eatToEndOfStatement(); return false; } // FIXME: Recurse on local labels? // See what kind of statement we have. switch (Lexer.getKind()) { case AsmToken::Colon: { if (!getTargetParser().isLabel(ID)) break; if (checkForValidSection()) return true; // identifier ':' -> Label. Lex(); // Diagnose attempt to use '.' as a label. if (IDVal == ".") return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label"); // Diagnose attempt to use a variable as a label. // // FIXME: Diagnostics. Note the location of the definition as a label. // FIXME: This doesn't diagnose assignment to a symbol which has been // implicitly marked as external. MCSymbol *Sym; if (LocalLabelVal == -1) { if (ParsingInlineAsm && SI) { StringRef RewrittenLabel = SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true); assert(RewrittenLabel.size() && "We should have an internal name here."); Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(), RewrittenLabel); IDVal = RewrittenLabel; } Sym = getContext().getOrCreateSymbol(IDVal); } else Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal); Sym->redefineIfPossible(); if (!Sym->isUndefined() || Sym->isVariable()) return Error(IDLoc, "invalid symbol redefinition"); // End of Labels should be treated as end of line for lexing // purposes but that information is not available to the Lexer who // does not understand Labels. This may cause us to see a Hash // here instead of a preprocessor line comment. if (getTok().is(AsmToken::Hash)) { StringRef CommentStr = parseStringToEndOfStatement(); Lexer.Lex(); Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr)); } // Consume any end of statement token, if present, to avoid spurious // AddBlankLine calls(). if (getTok().is(AsmToken::EndOfStatement)) { Lex(); } // Emit the label. if (!ParsingInlineAsm) Out.EmitLabel(Sym); // If we are generating dwarf for assembly source files then gather the // info to make a dwarf label entry for this label if needed. if (getContext().getGenDwarfForAssembly()) MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(), IDLoc); getTargetParser().onLabelParsed(Sym); return false; } case AsmToken::Equal: if (!getTargetParser().equalIsAsmAssignment()) break; // identifier '=' ... -> assignment statement Lex(); return parseAssignment(IDVal, true); default: // Normal instruction or directive. break; } // If macros are enabled, check to see if this is a macro instantiation. if (areMacrosEnabled()) if (const MCAsmMacro *M = lookupMacro(IDVal)) { return handleMacroEntry(M, IDLoc); } // Otherwise, we have a normal instruction or directive. // Directives start with "." if (IDVal[0] == '.' && IDVal != ".") { // There are several entities interested in parsing directives: // // 1. The target-specific assembly parser. Some directives are target // specific or may potentially behave differently on certain targets. // 2. Asm parser extensions. For example, platform-specific parsers // (like the ELF parser) register themselves as extensions. // 3. The generic directive parser implemented by this class. These are // all the directives that behave in a target and platform independent // manner, or at least have a default behavior that's shared between // all targets and platforms. getTargetParser().flushPendingInstructions(getStreamer()); SMLoc StartTokLoc = getTok().getLoc(); bool TPDirectiveReturn = getTargetParser().ParseDirective(ID); if (hasPendingError()) return true; // Currently the return value should be true if we are // uninterested but as this is at odds with the standard parsing // convention (return true = error) we have instances of a parsed // directive that fails returning true as an error. Catch these // cases as best as possible errors here. if (TPDirectiveReturn && StartTokLoc != getTok().getLoc()) return true; // Return if we did some parsing or believe we succeeded. if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc()) return false; // Next, check the extension directive map to see if any extension has // registered itself to parse this directive. std::pair Handler = ExtensionDirectiveMap.lookup(IDVal); if (Handler.first) return (*Handler.second)(Handler.first, IDVal, IDLoc); // Finally, if no one else is interested in this directive, it must be // generic and familiar to this class. switch (DirKind) { default: break; case DK_SET: case DK_EQU: return parseDirectiveSet(IDVal, true); case DK_EQUIV: return parseDirectiveSet(IDVal, false); case DK_ASCII: return parseDirectiveAscii(IDVal, false); case DK_ASCIZ: case DK_STRING: return parseDirectiveAscii(IDVal, true); case DK_BYTE: case DK_DC_B: return parseDirectiveValue(IDVal, 1); case DK_DC: case DK_DC_W: case DK_SHORT: case DK_VALUE: case DK_2BYTE: return parseDirectiveValue(IDVal, 2); case DK_LONG: case DK_INT: case DK_4BYTE: case DK_DC_L: return parseDirectiveValue(IDVal, 4); case DK_QUAD: case DK_8BYTE: return parseDirectiveValue(IDVal, 8); case DK_DC_A: return parseDirectiveValue(IDVal, getContext().getAsmInfo()->getPointerSize()); case DK_OCTA: return parseDirectiveOctaValue(IDVal); case DK_SINGLE: case DK_FLOAT: case DK_DC_S: return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle()); case DK_DOUBLE: case DK_DC_D: return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble()); case DK_ALIGN: { bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes(); return parseDirectiveAlign(IsPow2, /*ExprSize=*/1); } case DK_ALIGN32: { bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes(); return parseDirectiveAlign(IsPow2, /*ExprSize=*/4); } case DK_BALIGN: return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1); case DK_BALIGNW: return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2); case DK_BALIGNL: return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4); case DK_P2ALIGN: return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1); case DK_P2ALIGNW: return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2); case DK_P2ALIGNL: return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4); case DK_ORG: return parseDirectiveOrg(); case DK_FILL: return parseDirectiveFill(); case DK_ZERO: return parseDirectiveZero(); case DK_EXTERN: eatToEndOfStatement(); // .extern is the default, ignore it. return false; case DK_GLOBL: case DK_GLOBAL: return parseDirectiveSymbolAttribute(MCSA_Global); case DK_LAZY_REFERENCE: return parseDirectiveSymbolAttribute(MCSA_LazyReference); case DK_NO_DEAD_STRIP: return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip); case DK_SYMBOL_RESOLVER: return parseDirectiveSymbolAttribute(MCSA_SymbolResolver); case DK_PRIVATE_EXTERN: return parseDirectiveSymbolAttribute(MCSA_PrivateExtern); case DK_REFERENCE: return parseDirectiveSymbolAttribute(MCSA_Reference); case DK_WEAK_DEFINITION: return parseDirectiveSymbolAttribute(MCSA_WeakDefinition); case DK_WEAK_REFERENCE: return parseDirectiveSymbolAttribute(MCSA_WeakReference); case DK_WEAK_DEF_CAN_BE_HIDDEN: return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate); case DK_COMM: case DK_COMMON: return parseDirectiveComm(/*IsLocal=*/false); case DK_LCOMM: return parseDirectiveComm(/*IsLocal=*/true); case DK_ABORT: return parseDirectiveAbort(); case DK_INCLUDE: return parseDirectiveInclude(); case DK_INCBIN: return parseDirectiveIncbin(); case DK_CODE16: case DK_CODE16GCC: return TokError(Twine(IDVal) + " not currently supported for this target"); case DK_REPT: return parseDirectiveRept(IDLoc, IDVal); case DK_IRP: return parseDirectiveIrp(IDLoc); case DK_IRPC: return parseDirectiveIrpc(IDLoc); case DK_ENDR: return parseDirectiveEndr(IDLoc); case DK_BUNDLE_ALIGN_MODE: return parseDirectiveBundleAlignMode(); case DK_BUNDLE_LOCK: return parseDirectiveBundleLock(); case DK_BUNDLE_UNLOCK: return parseDirectiveBundleUnlock(); case DK_SLEB128: return parseDirectiveLEB128(true); case DK_ULEB128: return parseDirectiveLEB128(false); case DK_SPACE: case DK_SKIP: return parseDirectiveSpace(IDVal); case DK_FILE: return parseDirectiveFile(IDLoc); case DK_LINE: return parseDirectiveLine(); case DK_LOC: return parseDirectiveLoc(); case DK_STABS: return parseDirectiveStabs(); case DK_CV_FILE: return parseDirectiveCVFile(); case DK_CV_FUNC_ID: return parseDirectiveCVFuncId(); case DK_CV_INLINE_SITE_ID: return parseDirectiveCVInlineSiteId(); case DK_CV_LOC: return parseDirectiveCVLoc(); case DK_CV_LINETABLE: return parseDirectiveCVLinetable(); case DK_CV_INLINE_LINETABLE: return parseDirectiveCVInlineLinetable(); case DK_CV_DEF_RANGE: return parseDirectiveCVDefRange(); case DK_CV_STRINGTABLE: return parseDirectiveCVStringTable(); case DK_CV_FILECHECKSUMS: return parseDirectiveCVFileChecksums(); case DK_CFI_SECTIONS: return parseDirectiveCFISections(); case DK_CFI_STARTPROC: return parseDirectiveCFIStartProc(); case DK_CFI_ENDPROC: return parseDirectiveCFIEndProc(); case DK_CFI_DEF_CFA: return parseDirectiveCFIDefCfa(IDLoc); case DK_CFI_DEF_CFA_OFFSET: return parseDirectiveCFIDefCfaOffset(); case DK_CFI_ADJUST_CFA_OFFSET: return parseDirectiveCFIAdjustCfaOffset(); case DK_CFI_DEF_CFA_REGISTER: return parseDirectiveCFIDefCfaRegister(IDLoc); case DK_CFI_OFFSET: return parseDirectiveCFIOffset(IDLoc); case DK_CFI_REL_OFFSET: return parseDirectiveCFIRelOffset(IDLoc); case DK_CFI_PERSONALITY: return parseDirectiveCFIPersonalityOrLsda(true); case DK_CFI_LSDA: return parseDirectiveCFIPersonalityOrLsda(false); case DK_CFI_REMEMBER_STATE: return parseDirectiveCFIRememberState(); case DK_CFI_RESTORE_STATE: return parseDirectiveCFIRestoreState(); case DK_CFI_SAME_VALUE: return parseDirectiveCFISameValue(IDLoc); case DK_CFI_RESTORE: return parseDirectiveCFIRestore(IDLoc); case DK_CFI_ESCAPE: return parseDirectiveCFIEscape(); case DK_CFI_SIGNAL_FRAME: return parseDirectiveCFISignalFrame(); case DK_CFI_UNDEFINED: return parseDirectiveCFIUndefined(IDLoc); case DK_CFI_REGISTER: return parseDirectiveCFIRegister(IDLoc); case DK_CFI_WINDOW_SAVE: return parseDirectiveCFIWindowSave(); case DK_MACROS_ON: case DK_MACROS_OFF: return parseDirectiveMacrosOnOff(IDVal); case DK_MACRO: return parseDirectiveMacro(IDLoc); case DK_EXITM: return parseDirectiveExitMacro(IDVal); case DK_ENDM: case DK_ENDMACRO: return parseDirectiveEndMacro(IDVal); case DK_PURGEM: return parseDirectivePurgeMacro(IDLoc); case DK_END: return parseDirectiveEnd(IDLoc); case DK_ERR: return parseDirectiveError(IDLoc, false); case DK_ERROR: return parseDirectiveError(IDLoc, true); case DK_WARNING: return parseDirectiveWarning(IDLoc); case DK_RELOC: return parseDirectiveReloc(IDLoc); case DK_DCB: case DK_DCB_W: return parseDirectiveDCB(IDVal, 2); case DK_DCB_B: return parseDirectiveDCB(IDVal, 1); case DK_DCB_D: return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble()); case DK_DCB_L: return parseDirectiveDCB(IDVal, 4); case DK_DCB_S: return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle()); case DK_DC_X: case DK_DCB_X: return TokError(Twine(IDVal) + " not currently supported for this target"); case DK_DS: case DK_DS_W: return parseDirectiveDS(IDVal, 2); case DK_DS_B: return parseDirectiveDS(IDVal, 1); case DK_DS_D: return parseDirectiveDS(IDVal, 8); case DK_DS_L: case DK_DS_S: return parseDirectiveDS(IDVal, 4); case DK_DS_P: case DK_DS_X: return parseDirectiveDS(IDVal, 12); } return Error(IDLoc, "unknown directive"); } // __asm _emit or __asm __emit if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" || IDVal == "_EMIT" || IDVal == "__EMIT")) return parseDirectiveMSEmit(IDLoc, Info, IDVal.size()); // __asm align if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN")) return parseDirectiveMSAlign(IDLoc, Info); if (ParsingInlineAsm && (IDVal == "even")) Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4); if (checkForValidSection()) return true; // Canonicalize the opcode to lower case. std::string OpcodeStr = IDVal.lower(); ParseInstructionInfo IInfo(Info.AsmRewrites); bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID, Info.ParsedOperands); Info.ParseError = ParseHadError; // Dump the parsed representation, if requested. if (getShowParsedOperands()) { SmallString<256> Str; raw_svector_ostream OS(Str); OS << "parsed instruction: ["; for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) { if (i != 0) OS << ", "; Info.ParsedOperands[i]->print(OS); } OS << "]"; printMessage(IDLoc, SourceMgr::DK_Note, OS.str()); } // Fail even if ParseInstruction erroneously returns false. if (hasPendingError() || ParseHadError) return true; // If we are generating dwarf for the current section then generate a .loc // directive for the instruction. if (!ParseHadError && getContext().getGenDwarfForAssembly() && getContext().getGenDwarfSectionSyms().count( getStreamer().getCurrentSectionOnly())) { unsigned Line; if (ActiveMacros.empty()) Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer); else Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc, ActiveMacros.front()->ExitBuffer); // If we previously parsed a cpp hash file line comment then make sure the // current Dwarf File is for the CppHashFilename if not then emit the // Dwarf File table for it and adjust the line number for the .loc. if (CppHashInfo.Filename.size()) { unsigned FileNumber = getStreamer().EmitDwarfFileDirective( 0, StringRef(), CppHashInfo.Filename); getContext().setGenDwarfFileNumber(FileNumber); // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's // cache with the different Loc from the call above we save the last // info we queried here with SrcMgr.FindLineNumber(). unsigned CppHashLocLineNo; if (LastQueryIDLoc == CppHashInfo.Loc && LastQueryBuffer == CppHashInfo.Buf) CppHashLocLineNo = LastQueryLine; else { CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf); LastQueryLine = CppHashLocLineNo; LastQueryIDLoc = CppHashInfo.Loc; LastQueryBuffer = CppHashInfo.Buf; } Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo); } getStreamer().EmitDwarfLocDirective( getContext().getGenDwarfFileNumber(), Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0, StringRef()); } // If parsing succeeded, match the instruction. if (!ParseHadError) { uint64_t ErrorInfo; if (getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo, ParsingInlineAsm)) return true; } return false; } // Parse and erase curly braces marking block start/end bool AsmParser::parseCurlyBlockScope(SmallVectorImpl &AsmStrRewrites) { // Identify curly brace marking block start/end if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly)) return false; SMLoc StartLoc = Lexer.getLoc(); Lex(); // Eat the brace if (Lexer.is(AsmToken::EndOfStatement)) Lex(); // Eat EndOfStatement following the brace // Erase the block start/end brace from the output asm string AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() - StartLoc.getPointer()); return true; } /// parseCppHashLineFilenameComment as this: /// ::= # number "filename" bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) { Lex(); // Eat the hash token. // Lexer only ever emits HashDirective if it fully formed if it's // done the checking already so this is an internal error. assert(getTok().is(AsmToken::Integer) && "Lexing Cpp line comment: Expected Integer"); int64_t LineNumber = getTok().getIntVal(); Lex(); assert(getTok().is(AsmToken::String) && "Lexing Cpp line comment: Expected String"); StringRef Filename = getTok().getString(); Lex(); // Get rid of the enclosing quotes. Filename = Filename.substr(1, Filename.size() - 2); // Save the SMLoc, Filename and LineNumber for later use by diagnostics. CppHashInfo.Loc = L; CppHashInfo.Filename = Filename; CppHashInfo.LineNumber = LineNumber; CppHashInfo.Buf = CurBuffer; return false; } /// \brief will use the last parsed cpp hash line filename comment /// for the Filename and LineNo if any in the diagnostic. void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) { const AsmParser *Parser = static_cast(Context); raw_ostream &OS = errs(); const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr(); SMLoc DiagLoc = Diag.getLoc(); unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc); unsigned CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc); // Like SourceMgr::printMessage() we need to print the include stack if any // before printing the message. unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc); if (!Parser->SavedDiagHandler && DiagCurBuffer && DiagCurBuffer != DiagSrcMgr.getMainFileID()) { SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer); DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS); } // If we have not parsed a cpp hash line filename comment or the source // manager changed or buffer changed (like in a nested include) then just // print the normal diagnostic using its Filename and LineNo. if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr || DiagBuf != CppHashBuf) { if (Parser->SavedDiagHandler) Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext); else Diag.print(nullptr, OS); return; } // Use the CppHashFilename and calculate a line number based on the // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc // for the diagnostic. const std::string &Filename = Parser->CppHashInfo.Filename; int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf); int CppHashLocLineNo = Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf); int LineNo = Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo); SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo, Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(), Diag.getLineContents(), Diag.getRanges()); if (Parser->SavedDiagHandler) Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext); else NewDiag.print(nullptr, OS); } // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The // difference being that that function accepts '@' as part of identifiers and // we can't do that. AsmLexer.cpp should probably be changed to handle // '@' as a special case when needed. static bool isIdentifierChar(char c) { return isalnum(static_cast(c)) || c == '_' || c == '$' || c == '.'; } bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body, ArrayRef Parameters, ArrayRef A, bool EnableAtPseudoVariable, SMLoc L) { unsigned NParameters = Parameters.size(); bool HasVararg = NParameters ? Parameters.back().Vararg : false; if ((!IsDarwin || NParameters != 0) && NParameters != A.size()) return Error(L, "Wrong number of arguments"); // A macro without parameters is handled differently on Darwin: // gas accepts no arguments and does no substitutions while (!Body.empty()) { // Scan for the next substitution. 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; } } // Add the prefix. OS << Body.slice(0, Pos); // Check if we reached the end. if (Pos == End) break; if (IsDarwin && !NParameters) { switch (Body[Pos + 1]) { // $$ => $ case '$': OS << '$'; break; // $n => number of arguments case 'n': OS << A.size(); break; // $[0-9] => argument default: { // Missing arguments are ignored. unsigned Index = Body[Pos + 1] - '0'; if (Index >= A.size()) break; // Otherwise substitute with the token values, with spaces eliminated. for (const AsmToken &Token : A[Index]) OS << Token.getString(); break; } } 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; if (Argument == "@") { OS << NumOfMacroInstantiations; Pos += 2; } else { for (; Index < NParameters; ++Index) if (Parameters[Index].Name == Argument) break; if (Index == NParameters) { if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')') Pos += 3; 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 OS << Token.getStringContents(); Pos += 1 + Argument.size(); } } } // Update the scan point. Body = Body.substr(Pos); } return false; } MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth) : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL), CondStackDepth(CondStackDepth) {} static bool isOperator(AsmToken::TokenKind kind) { switch (kind) { default: return false; case AsmToken::Plus: case AsmToken::Minus: case AsmToken::Tilde: case AsmToken::Slash: case AsmToken::Star: case AsmToken::Dot: case AsmToken::Equal: case AsmToken::EqualEqual: case AsmToken::Pipe: case AsmToken::PipePipe: case AsmToken::Caret: case AsmToken::Amp: case AsmToken::AmpAmp: case AsmToken::Exclaim: case AsmToken::ExclaimEqual: case AsmToken::Less: case AsmToken::LessEqual: case AsmToken::LessLess: case AsmToken::LessGreater: case AsmToken::Greater: case AsmToken::GreaterEqual: case AsmToken::GreaterGreater: return true; } } namespace { class AsmLexerSkipSpaceRAII { public: AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) { Lexer.setSkipSpace(SkipSpace); } ~AsmLexerSkipSpaceRAII() { Lexer.setSkipSpace(true); } private: AsmLexer &Lexer; }; } // end anonymous namespace bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) { if (Vararg) { if (Lexer.isNot(AsmToken::EndOfStatement)) { StringRef Str = parseStringToEndOfStatement(); MA.emplace_back(AsmToken::String, Str); } return false; } unsigned ParenLevel = 0; // Darwin doesn't use spaces to delmit arguments. AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin); bool SpaceEaten; while (true) { SpaceEaten = false; if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) return TokError("unexpected token in macro instantiation"); if (ParenLevel == 0) { if (Lexer.is(AsmToken::Comma)) break; if (Lexer.is(AsmToken::Space)) { SpaceEaten = true; Lexer.Lex(); // Eat spaces } // 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())) { MA.push_back(getTok()); Lexer.Lex(); // Whitespace after an operator can be ignored. if (Lexer.is(AsmToken::Space)) Lexer.Lex(); continue; } } if (SpaceEaten) break; } // handleMacroEntry relies on not advancing the lexer here // to be able to fill in the remaining default parameter values if (Lexer.is(AsmToken::EndOfStatement)) break; // Adjust the current parentheses level. if (Lexer.is(AsmToken::LParen)) ++ParenLevel; else if (Lexer.is(AsmToken::RParen) && ParenLevel) --ParenLevel; // Append the token to the current argument list. MA.push_back(getTok()); Lexer.Lex(); } if (ParenLevel != 0) return TokError("unbalanced parentheses in macro argument"); return false; } // Parse the macro instantiation arguments. bool AsmParser::parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) { const unsigned NParameters = M ? M->Parameters.size() : 0; bool NamedParametersFound = false; SmallVector FALocs; A.resize(NParameters); FALocs.resize(NParameters); // Parse two kinds of macro invocations: // - macros defined without any parameters accept an arbitrary number of them // - macros defined with parameters accept at most that many of them bool HasVararg = NParameters ? M->Parameters.back().Vararg : false; for (unsigned Parameter = 0; !NParameters || Parameter < NParameters; ++Parameter) { SMLoc IDLoc = Lexer.getLoc(); MCAsmMacroParameter FA; if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) { if (parseIdentifier(FA.Name)) return Error(IDLoc, "invalid argument identifier for formal argument"); if (Lexer.isNot(AsmToken::Equal)) return TokError("expected '=' after formal parameter identifier"); Lex(); NamedParametersFound = true; } if (NamedParametersFound && FA.Name.empty()) return Error(IDLoc, "cannot mix positional and keyword arguments"); bool Vararg = HasVararg && Parameter == (NParameters - 1); if (parseMacroArgument(FA.Value, Vararg)) return true; unsigned PI = Parameter; if (!FA.Name.empty()) { unsigned FAI = 0; for (FAI = 0; FAI < NParameters; ++FAI) if (M->Parameters[FAI].Name == FA.Name) break; if (FAI >= NParameters) { assert(M && "expected macro to be defined"); return Error(IDLoc, "parameter named '" + FA.Name + "' does not exist for macro '" + M->Name + "'"); } PI = FAI; } if (!FA.Value.empty()) { if (A.size() <= PI) A.resize(PI + 1); A[PI] = FA.Value; if (FALocs.size() <= PI) FALocs.resize(PI + 1); FALocs[PI] = Lexer.getLoc(); } // At the end of the statement, fill in remaining arguments that have // default values. If there aren't any, then the next argument is // required but missing if (Lexer.is(AsmToken::EndOfStatement)) { bool Failure = false; for (unsigned FAI = 0; FAI < NParameters; ++FAI) { if (A[FAI].empty()) { if (M->Parameters[FAI].Required) { Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(), "missing value for required parameter " "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'"); Failure = true; } if (!M->Parameters[FAI].Value.empty()) A[FAI] = M->Parameters[FAI].Value; } } return Failure; } if (Lexer.is(AsmToken::Comma)) Lex(); } return TokError("too many positional arguments"); } const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) { StringMap::iterator I = MacroMap.find(Name); return (I == MacroMap.end()) ? nullptr : &I->getValue(); } void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) { MacroMap.insert(std::make_pair(Name, std::move(Macro))); } void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); } bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) { // Arbitrarily limit macro nesting depth (default matches 'as'). We can // eliminate this, although we should protect against infinite loops. unsigned MaxNestingDepth = AsmMacroMaxNestingDepth; if (ActiveMacros.size() == MaxNestingDepth) { std::ostringstream MaxNestingDepthError; MaxNestingDepthError << "macros cannot be nested more than " << MaxNestingDepth << " levels deep." << " Use -asm-macro-max-nesting-depth to increase " "this limit."; return TokError(MaxNestingDepthError.str()); } MCAsmMacroArguments A; if (parseMacroArguments(M, A)) return true; // Macro instantiation is lexical, unfortunately. We construct a new buffer // to hold the macro body with substitutions. SmallString<256> Buf; StringRef Body = M->Body; raw_svector_ostream OS(Buf); if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc())) return true; // We include the .endmacro in the buffer as our cue to exit the macro // instantiation. OS << ".endmacro\n"; std::unique_ptr Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), ""); // Create the macro instantiation object and add to the current macro // instantiation stack. MacroInstantiation *MI = new MacroInstantiation( NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()); ActiveMacros.push_back(MI); ++NumOfMacroInstantiations; // Jump to the macro instantiation and prime the lexer. CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc()); Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); Lex(); return false; } void AsmParser::handleMacroExit() { // Jump to the EndOfStatement we should return to, and consume it. jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer); Lex(); // Pop the instantiation entry. delete ActiveMacros.back(); ActiveMacros.pop_back(); } bool AsmParser::parseAssignment(StringRef Name, bool allow_redef, bool NoDeadStrip) { MCSymbol *Sym; const MCExpr *Value; if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym, Value)) return true; if (!Sym) { // In the case where we parse an expression starting with a '.', we will // not generate an error, nor will we create a symbol. In this case we // should just return out. return false; } // Do the assignment. Out.EmitAssignment(Sym, Value); if (NoDeadStrip) Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip); return false; } /// parseIdentifier: /// ::= identifier /// ::= string bool AsmParser::parseIdentifier(StringRef &Res) { // The assembler has relaxed rules for accepting identifiers, in particular we // allow things like '.globl $foo' and '.def @feat.00', which would normally be // separate tokens. At this level, we have already lexed so we cannot (currently) // handle this as a context dependent token, instead we detect adjacent tokens // and return the combined identifier. if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) { SMLoc PrefixLoc = getLexer().getLoc(); // Consume the prefix character, and check for a following identifier. AsmToken Buf[1]; Lexer.peekTokens(Buf, false); if (Buf[0].isNot(AsmToken::Identifier)) return true; // We have a '$' or '@' followed by an identifier, make sure they are adjacent. if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer()) return true; // eat $ or @ Lexer.Lex(); // Lexer's Lex guarantees consecutive token. // Construct the joined identifier and consume the token. Res = StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1); Lex(); // Parser Lex to maintain invariants. return false; } if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String)) return true; Res = getTok().getIdentifier(); Lex(); // Consume the identifier token. return false; } /// parseDirectiveSet: /// ::= .equ identifier ',' expression /// ::= .equiv identifier ',' expression /// ::= .set identifier ',' expression bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) { StringRef Name; if (check(parseIdentifier(Name), "expected identifier") || parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true)) return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); return false; } bool AsmParser::parseEscapedString(std::string &Data) { if (check(getTok().isNot(AsmToken::String), "expected string")) return true; Data = ""; StringRef Str = getTok().getStringContents(); for (unsigned i = 0, e = Str.size(); i != e; ++i) { if (Str[i] != '\\') { Data += Str[i]; continue; } // Recognize escaped characters. Note that this escape semantics currently // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes. ++i; if (i == e) return TokError("unexpected backslash at end of string"); // Recognize octal sequences. if ((unsigned)(Str[i] - '0') <= 7) { // Consume up to three octal characters. unsigned Value = Str[i] - '0'; if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) { ++i; Value = Value * 8 + (Str[i] - '0'); if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) { ++i; Value = Value * 8 + (Str[i] - '0'); } } if (Value > 255) return TokError("invalid octal escape sequence (out of range)"); Data += (unsigned char)Value; continue; } // Otherwise recognize individual escapes. switch (Str[i]) { default: // Just reject invalid escape sequences for now. return TokError("invalid escape sequence (unrecognized character)"); case 'b': Data += '\b'; break; case 'f': Data += '\f'; break; case 'n': Data += '\n'; break; case 'r': Data += '\r'; break; case 't': Data += '\t'; break; case '"': Data += '"'; break; case '\\': Data += '\\'; break; } } Lex(); return false; } /// parseDirectiveAscii: /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ] bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) { auto parseOp = [&]() -> bool { std::string Data; if (checkForValidSection() || parseEscapedString(Data)) return true; getStreamer().EmitBytes(Data); if (ZeroTerminated) getStreamer().EmitBytes(StringRef("\0", 1)); return false; }; if (parseMany(parseOp)) return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); return false; } /// parseDirectiveReloc /// ::= .reloc expression , identifier [ , expression ] bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) { const MCExpr *Offset; const MCExpr *Expr = nullptr; SMLoc OffsetLoc = Lexer.getTok().getLoc(); int64_t OffsetValue; // We can only deal with constant expressions at the moment. if (parseExpression(Offset)) return true; if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc, "expression is not a constant value") || check(OffsetValue < 0, OffsetLoc, "expression is negative") || parseToken(AsmToken::Comma, "expected comma") || check(getTok().isNot(AsmToken::Identifier), "expected relocation name")) return true; SMLoc NameLoc = Lexer.getTok().getLoc(); StringRef Name = Lexer.getTok().getIdentifier(); Lex(); if (Lexer.is(AsmToken::Comma)) { Lex(); SMLoc ExprLoc = Lexer.getLoc(); if (parseExpression(Expr)) return true; MCValue Value; if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr)) return Error(ExprLoc, "expression must be relocatable"); } if (parseToken(AsmToken::EndOfStatement, "unexpected token in .reloc directive")) return true; if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc)) return Error(NameLoc, "unknown relocation name"); return false; } /// parseDirectiveValue /// ::= (.byte | .short | ... ) [ expression (, expression)* ] bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) { auto parseOp = [&]() -> bool { const MCExpr *Value; SMLoc ExprLoc = getLexer().getLoc(); if (checkForValidSection() || parseExpression(Value)) return true; // Special case constant expressions to match code generator. if (const MCConstantExpr *MCE = dyn_cast(Value)) { assert(Size <= 8 && "Invalid size"); uint64_t IntValue = MCE->getValue(); if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue)) return Error(ExprLoc, "out of range literal value"); getStreamer().EmitIntValue(IntValue, Size); } else getStreamer().EmitValue(Value, Size, ExprLoc); return false; }; if (parseMany(parseOp)) return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); return false; } /// ParseDirectiveOctaValue /// ::= .octa [ hexconstant (, hexconstant)* ] bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) { auto parseOp = [&]() -> bool { if (checkForValidSection()) return true; if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum)) return TokError("unknown token in expression"); SMLoc ExprLoc = getTok().getLoc(); APInt IntValue = getTok().getAPIntVal(); uint64_t hi, lo; Lex(); if (!IntValue.isIntN(128)) return Error(ExprLoc, "out of range literal value"); if (!IntValue.isIntN(64)) { hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue(); lo = IntValue.getLoBits(64).getZExtValue(); } else { hi = 0; lo = IntValue.getZExtValue(); } if (MAI.isLittleEndian()) { getStreamer().EmitIntValue(lo, 8); getStreamer().EmitIntValue(hi, 8); } else { getStreamer().EmitIntValue(hi, 8); getStreamer().EmitIntValue(lo, 8); } return false; }; if (parseMany(parseOp)) return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); return false; } bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) { // We don't truly support arithmetic on floating point expressions, so we // have to manually parse unary prefixes. bool IsNeg = false; if (getLexer().is(AsmToken::Minus)) { Lexer.Lex(); IsNeg = true; } else if (getLexer().is(AsmToken::Plus)) Lexer.Lex(); if (Lexer.is(AsmToken::Error)) return TokError(Lexer.getErr()); if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) && Lexer.isNot(AsmToken::Identifier)) return TokError("unexpected token in directive"); // Convert to an APFloat. APFloat Value(Semantics); StringRef IDVal = getTok().getString(); if (getLexer().is(AsmToken::Identifier)) { if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf")) Value = APFloat::getInf(Semantics); else if (!IDVal.compare_lower("nan")) Value = APFloat::getNaN(Semantics, false, ~0); else return TokError("invalid floating point literal"); } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) == APFloat::opInvalidOp) return TokError("invalid floating point literal"); if (IsNeg) Value.changeSign(); // Consume the numeric token. Lex(); Res = Value.bitcastToAPInt(); return false; } /// parseDirectiveRealValue /// ::= (.single | .double) [ expression (, expression)* ] bool AsmParser::parseDirectiveRealValue(StringRef IDVal, const fltSemantics &Semantics) { auto parseOp = [&]() -> bool { APInt AsInt; if (checkForValidSection() || parseRealValue(Semantics, AsInt)) return true; getStreamer().EmitIntValue(AsInt.getLimitedValue(), AsInt.getBitWidth() / 8); return false; }; if (parseMany(parseOp)) return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); return false; } /// parseDirectiveZero /// ::= .zero expression bool AsmParser::parseDirectiveZero() { SMLoc NumBytesLoc = Lexer.getLoc(); const MCExpr *NumBytes; if (checkForValidSection() || parseExpression(NumBytes)) return true; int64_t Val = 0; if (getLexer().is(AsmToken::Comma)) { Lex(); if (parseAbsoluteExpression(Val)) return true; } if (parseToken(AsmToken::EndOfStatement, "unexpected token in '.zero' directive")) return true; getStreamer().emitFill(*NumBytes, Val, NumBytesLoc); return false; } /// parseDirectiveFill /// ::= .fill expression [ , expression [ , expression ] ] bool AsmParser::parseDirectiveFill() { SMLoc NumValuesLoc = Lexer.getLoc(); const MCExpr *NumValues; if (checkForValidSection() || parseExpression(NumValues)) return true; int64_t FillSize = 1; int64_t FillExpr = 0; SMLoc SizeLoc, ExprLoc; if (parseOptionalToken(AsmToken::Comma)) { SizeLoc = getTok().getLoc(); if (parseAbsoluteExpression(FillSize)) return true; if (parseOptionalToken(AsmToken::Comma)) { ExprLoc = getTok().getLoc(); if (parseAbsoluteExpression(FillExpr)) return true; } } if (parseToken(AsmToken::EndOfStatement, "unexpected token in '.fill' directive")) return true; if (FillSize < 0) { Warning(SizeLoc, "'.fill' directive with negative size has no effect"); return false; } if (FillSize > 8) { Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8"); FillSize = 8; } if (!isUInt<32>(FillExpr) && FillSize > 4) Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits"); getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc); return false; } /// parseDirectiveOrg /// ::= .org expression [ , expression ] bool AsmParser::parseDirectiveOrg() { const MCExpr *Offset; SMLoc OffsetLoc = Lexer.getLoc(); if (checkForValidSection() || parseExpression(Offset)) return true; // Parse optional fill expression. int64_t FillExpr = 0; if (parseOptionalToken(AsmToken::Comma)) if (parseAbsoluteExpression(FillExpr)) return addErrorSuffix(" in '.org' directive"); if (parseToken(AsmToken::EndOfStatement)) return addErrorSuffix(" in '.org' directive"); getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc); return false; } /// parseDirectiveAlign /// ::= {.align, ...} expression [ , expression [ , expression ]] bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) { SMLoc AlignmentLoc = getLexer().getLoc(); int64_t Alignment; SMLoc MaxBytesLoc; bool HasFillExpr = false; int64_t FillExpr = 0; int64_t MaxBytesToFill = 0; auto parseAlign = [&]() -> bool { if (checkForValidSection() || parseAbsoluteExpression(Alignment)) return true; if (parseOptionalToken(AsmToken::Comma)) { // The fill expression can be omitted while specifying a maximum number of // alignment bytes, e.g: // .align 3,,4 if (getTok().isNot(AsmToken::Comma)) { HasFillExpr = true; if (parseAbsoluteExpression(FillExpr)) return true; } if (parseOptionalToken(AsmToken::Comma)) if (parseTokenLoc(MaxBytesLoc) || parseAbsoluteExpression(MaxBytesToFill)) return true; } return parseToken(AsmToken::EndOfStatement); }; if (parseAlign()) return addErrorSuffix(" in directive"); // Always emit an alignment here even if we thrown an error. bool ReturnVal = false; // Compute alignment in bytes. if (IsPow2) { // FIXME: Diagnose overflow. if (Alignment >= 32) { ReturnVal |= Error(AlignmentLoc, "invalid alignment value"); Alignment = 31; } Alignment = 1ULL << Alignment; } else { // Reject alignments that aren't either a power of two or zero, // for gas compatibility. Alignment of zero is silently rounded // up to one. if (Alignment == 0) Alignment = 1; if (!isPowerOf2_64(Alignment)) ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2"); } // Diagnose non-sensical max bytes to align. if (MaxBytesLoc.isValid()) { if (MaxBytesToFill < 1) { ReturnVal |= Error(MaxBytesLoc, "alignment directive can never be satisfied in this " "many bytes, ignoring maximum bytes expression"); MaxBytesToFill = 0; } if (MaxBytesToFill >= Alignment) { Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and " "has no effect"); MaxBytesToFill = 0; } } // Check whether we should use optimal code alignment for this .align // directive. const MCSection *Section = getStreamer().getCurrentSectionOnly(); assert(Section && "must have section to emit alignment"); bool UseCodeAlign = Section->UseCodeAlign(); if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) && ValueSize == 1 && UseCodeAlign) { getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill); } else { // FIXME: Target specific behavior about how the "extra" bytes are filled. getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill); } return ReturnVal; } /// parseDirectiveFile /// ::= .file [number] filename /// ::= .file number directory filename bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) { // FIXME: I'm not sure what this is. int64_t FileNumber = -1; SMLoc FileNumberLoc = getLexer().getLoc(); if (getLexer().is(AsmToken::Integer)) { FileNumber = getTok().getIntVal(); Lex(); if (FileNumber < 1) return TokError("file number less than one"); } std::string Path = getTok().getString(); // Usually the directory and filename together, otherwise just the directory. // Allow the strings to have escaped octal character sequence. if (check(getTok().isNot(AsmToken::String), "unexpected token in '.file' directive") || parseEscapedString(Path)) return true; StringRef Directory; StringRef Filename; std::string FilenameData; if (getLexer().is(AsmToken::String)) { if (check(FileNumber == -1, "explicit path specified, but no file number") || parseEscapedString(FilenameData)) return true; Filename = FilenameData; Directory = Path; } else { Filename = Path; } if (parseToken(AsmToken::EndOfStatement, "unexpected token in '.file' directive")) return true; if (FileNumber == -1) getStreamer().EmitFileDirective(Filename); else { // If there is -g option as well as debug info from directive file, // we turn off -g option, directly use the existing debug info instead. if (getContext().getGenDwarfForAssembly()) getContext().setGenDwarfForAssembly(false); else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) == 0) return Error(FileNumberLoc, "file number already allocated"); } return false; } /// parseDirectiveLine /// ::= .line [number] bool AsmParser::parseDirectiveLine() { int64_t LineNumber; if (getLexer().is(AsmToken::Integer)) { if (parseIntToken(LineNumber, "unexpected token in '.line' directive")) return true; (void)LineNumber; // FIXME: Do something with the .line. } if (parseToken(AsmToken::EndOfStatement, "unexpected token in '.line' directive")) return true; return false; } /// parseDirectiveLoc /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end] /// [epilogue_begin] [is_stmt VALUE] [isa VALUE] /// The first number is a file number, must have been previously assigned with /// a .file directive, the second number is the line number and optionally the /// third number is a column position (zero if not specified). The remaining /// optional items are .loc sub-directives. bool AsmParser::parseDirectiveLoc() { int64_t FileNumber = 0, LineNumber = 0; SMLoc Loc = getTok().getLoc(); if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") || check(FileNumber < 1, Loc, "file number less than one in '.loc' directive") || check(!getContext().isValidDwarfFileNumber(FileNumber), Loc, "unassigned file number in '.loc' directive")) return true; // optional if (getLexer().is(AsmToken::Integer)) { LineNumber = getTok().getIntVal(); if (LineNumber < 0) return TokError("line number less than zero in '.loc' directive"); Lex(); } int64_t ColumnPos = 0; if (getLexer().is(AsmToken::Integer)) { ColumnPos = getTok().getIntVal(); if (ColumnPos < 0) return TokError("column position less than zero in '.loc' directive"); Lex(); } unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0; unsigned Isa = 0; int64_t Discriminator = 0; auto parseLocOp = [&]() -> bool { StringRef Name; SMLoc Loc = getTok().getLoc(); if (parseIdentifier(Name)) return TokError("unexpected token in '.loc' directive"); if (Name == "basic_block") Flags |= DWARF2_FLAG_BASIC_BLOCK; else if (Name == "prologue_end") Flags |= DWARF2_FLAG_PROLOGUE_END; else if (Name == "epilogue_begin") Flags |= DWARF2_FLAG_EPILOGUE_BEGIN; else if (Name == "is_stmt") { Loc = getTok().getLoc(); const MCExpr *Value; if (parseExpression(Value)) return true; // The expression must be the constant 0 or 1. if (const MCConstantExpr *MCE = dyn_cast(Value)) { int Value = MCE->getValue(); if (Value == 0) Flags &= ~DWARF2_FLAG_IS_STMT; else if (Value == 1) Flags |= DWARF2_FLAG_IS_STMT; else return Error(Loc, "is_stmt value not 0 or 1"); } else { return Error(Loc, "is_stmt value not the constant value of 0 or 1"); } } else if (Name == "isa") { Loc = getTok().getLoc(); const MCExpr *Value; if (parseExpression(Value)) return true; // The expression must be a constant greater or equal to 0. if (const MCConstantExpr *MCE = dyn_cast(Value)) { int Value = MCE->getValue(); if (Value < 0) return Error(Loc, "isa number less than zero"); Isa = Value; } else { return Error(Loc, "isa number not a constant value"); } } else if (Name == "discriminator") { if (parseAbsoluteExpression(Discriminator)) return true; } else { return Error(Loc, "unknown sub-directive in '.loc' directive"); } return false; }; if (parseMany(parseLocOp, false /*hasComma*/)) return true; getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags, Isa, Discriminator, StringRef()); return false; } /// parseDirectiveStabs /// ::= .stabs string, number, number, number bool AsmParser::parseDirectiveStabs() { return TokError("unsupported directive '.stabs'"); } /// parseDirectiveCVFile /// ::= .cv_file number filename bool AsmParser::parseDirectiveCVFile() { SMLoc FileNumberLoc = getTok().getLoc(); int64_t FileNumber; std::string Filename; if (parseIntToken(FileNumber, "expected file number in '.cv_file' directive") || check(FileNumber < 1, FileNumberLoc, "file number less than one") || check(getTok().isNot(AsmToken::String), "unexpected token in '.cv_file' directive") || // Usually directory and filename are together, otherwise just // directory. Allow the strings to have escaped octal character sequence. parseEscapedString(Filename) || parseToken(AsmToken::EndOfStatement, "unexpected token in '.cv_file' directive")) return true; if (!getStreamer().EmitCVFileDirective(FileNumber, Filename)) return Error(FileNumberLoc, "file number already allocated"); return false; } bool AsmParser::parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName) { SMLoc Loc; return parseTokenLoc(Loc) || parseIntToken(FunctionId, "expected function id in '" + DirectiveName + "' directive") || check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc, "expected function id within range [0, UINT_MAX)"); } bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) { SMLoc Loc; return parseTokenLoc(Loc) || parseIntToken(FileNumber, "expected integer in '" + DirectiveName + "' directive") || check(FileNumber < 1, Loc, "file number less than one in '" + DirectiveName + "' directive") || check(!getCVContext().isValidFileNumber(FileNumber), Loc, "unassigned file number in '" + DirectiveName + "' directive"); } /// parseDirectiveCVFuncId /// ::= .cv_func_id FunctionId /// /// Introduces a function ID that can be used with .cv_loc. bool AsmParser::parseDirectiveCVFuncId() { SMLoc FunctionIdLoc = getTok().getLoc(); int64_t FunctionId; if (parseCVFunctionId(FunctionId, ".cv_func_id") || parseToken(AsmToken::EndOfStatement, "unexpected token in '.cv_func_id' directive")) return true; if (!getStreamer().EmitCVFuncIdDirective(FunctionId)) return Error(FunctionIdLoc, "function id already allocated"); return false; } /// parseDirectiveCVInlineSiteId /// ::= .cv_inline_site_id FunctionId /// "within" IAFunc /// "inlined_at" IAFile IALine [IACol] /// /// Introduces a function ID that can be used with .cv_loc. Includes "inlined /// at" source location information for use in the line table of the caller, /// whether the caller is a real function or another inlined call site. bool AsmParser::parseDirectiveCVInlineSiteId() { SMLoc FunctionIdLoc = getTok().getLoc(); int64_t FunctionId; int64_t IAFunc; int64_t IAFile; int64_t IALine; int64_t IACol = 0; // FunctionId if (parseCVFunctionId(FunctionId, ".cv_inline_site_id")) return true; // "within" if (check((getLexer().isNot(AsmToken::Identifier) || getTok().getIdentifier() != "within"), "expected 'within' identifier in '.cv_inline_site_id' directive")) return true; Lex(); // IAFunc if (parseCVFunctionId(IAFunc, ".cv_inline_site_id")) return true; // "inlined_at" if (check((getLexer().isNot(AsmToken::Identifier) || getTok().getIdentifier() != "inlined_at"), "expected 'inlined_at' identifier in '.cv_inline_site_id' " "directive") ) return true; Lex(); // IAFile IALine if (parseCVFileId(IAFile, ".cv_inline_site_id") || parseIntToken(IALine, "expected line number after 'inlined_at'")) return true; // [IACol] if (getLexer().is(AsmToken::Integer)) { IACol = getTok().getIntVal(); Lex(); } if (parseToken(AsmToken::EndOfStatement, "unexpected token in '.cv_inline_site_id' directive")) return true; if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile, IALine, IACol, FunctionIdLoc)) return Error(FunctionIdLoc, "function id already allocated"); return false; } /// parseDirectiveCVLoc /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end] /// [is_stmt VALUE] /// The first number is a file number, must have been previously assigned with /// a .file directive, the second number is the line number and optionally the /// third number is a column position (zero if not specified). The remaining /// optional items are .loc sub-directives. bool AsmParser::parseDirectiveCVLoc() { SMLoc DirectiveLoc = getTok().getLoc(); SMLoc Loc; int64_t FunctionId, FileNumber; if (parseCVFunctionId(FunctionId, ".cv_loc") || parseCVFileId(FileNumber, ".cv_loc")) return true; int64_t LineNumber = 0; if (getLexer().is(AsmToken::Integer)) { LineNumber = getTok().getIntVal(); if (LineNumber < 0) return TokError("line number less than zero in '.cv_loc' directive"); Lex(); } int64_t ColumnPos = 0; if (getLexer().is(AsmToken::Integer)) { ColumnPos = getTok().getIntVal(); if (ColumnPos < 0) return TokError("column position less than zero in '.cv_loc' directive"); Lex(); } bool PrologueEnd = false; uint64_t IsStmt = 0; auto parseOp = [&]() -> bool { StringRef Name; SMLoc Loc = getTok().getLoc(); if (parseIdentifier(Name)) return TokError("unexpected token in '.cv_loc' directive"); if (Name == "prologue_end") PrologueEnd = true; else if (Name == "is_stmt") { Loc = getTok().getLoc(); const MCExpr *Value; if (parseExpression(Value)) return true; // The expression must be the constant 0 or 1. IsStmt = ~0ULL; if (const auto *MCE = dyn_cast(Value)) IsStmt = MCE->getValue(); if (IsStmt > 1) return Error(Loc, "is_stmt value not 0 or 1"); } else { return Error(Loc, "unknown sub-directive in '.cv_loc' directive"); } return false; }; if (parseMany(parseOp, false /*hasComma*/)) return true; getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber, ColumnPos, PrologueEnd, IsStmt, StringRef(), DirectiveLoc); return false; } /// parseDirectiveCVLinetable /// ::= .cv_linetable FunctionId, FnStart, FnEnd bool AsmParser::parseDirectiveCVLinetable() { int64_t FunctionId; StringRef FnStartName, FnEndName; SMLoc Loc = getTok().getLoc(); if (parseCVFunctionId(FunctionId, ".cv_linetable") || parseToken(AsmToken::Comma, "unexpected token in '.cv_linetable' directive") || parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc, "expected identifier in directive") || parseToken(AsmToken::Comma, "unexpected token in '.cv_linetable' directive") || parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc, "expected identifier in directive")) return true; MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName); MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName); getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym); return false; } /// parseDirectiveCVInlineLinetable /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd bool AsmParser::parseDirectiveCVInlineLinetable() { int64_t PrimaryFunctionId, SourceFileId, SourceLineNum; StringRef FnStartName, FnEndName; SMLoc Loc = getTok().getLoc(); if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") || parseTokenLoc(Loc) || parseIntToken( SourceFileId, "expected SourceField in '.cv_inline_linetable' directive") || check(SourceFileId <= 0, Loc, "File id less than zero in '.cv_inline_linetable' directive") || parseTokenLoc(Loc) || parseIntToken( SourceLineNum, "expected SourceLineNum in '.cv_inline_linetable' directive") || check(SourceLineNum < 0, Loc, "Line number less than zero in '.cv_inline_linetable' directive") || parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc, "expected identifier in directive") || parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc, "expected identifier in directive")) return true; if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement")) return true; MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName); MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName); getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym); return false; } /// parseDirectiveCVDefRange /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes* bool AsmParser::parseDirectiveCVDefRange() { SMLoc Loc; std::vector> Ranges; while (getLexer().is(AsmToken::Identifier)) { Loc = getLexer().getLoc(); StringRef GapStartName; if (parseIdentifier(GapStartName)) return Error(Loc, "expected identifier in directive"); MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName); Loc = getLexer().getLoc(); StringRef GapEndName; if (parseIdentifier(GapEndName)) return Error(Loc, "expected identifier in directive"); MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName); Ranges.push_back({GapStartSym, GapEndSym}); } std::string FixedSizePortion; if (parseToken(AsmToken::Comma, "unexpected token in directive") || parseEscapedString(FixedSizePortion)) return true; getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion); return false; } /// parseDirectiveCVStringTable /// ::= .cv_stringtable bool AsmParser::parseDirectiveCVStringTable() { getStreamer().EmitCVStringTableDirective(); return false; } /// parseDirectiveCVFileChecksums /// ::= .cv_filechecksums bool AsmParser::parseDirectiveCVFileChecksums() { getStreamer().EmitCVFileChecksumsDirective(); return false; } /// parseDirectiveCFISections /// ::= .cfi_sections section [, section] bool AsmParser::parseDirectiveCFISections() { StringRef Name; bool EH = false; bool Debug = false; if (parseIdentifier(Name)) return TokError("Expected an identifier"); if (Name == ".eh_frame") EH = true; else if (Name == ".debug_frame") Debug = true; if (getLexer().is(AsmToken::Comma)) { Lex(); if (parseIdentifier(Name)) return TokError("Expected an identifier"); if (Name == ".eh_frame") EH = true; else if (Name == ".debug_frame") Debug = true; } getStreamer().EmitCFISections(EH, Debug); return false; } /// parseDirectiveCFIStartProc /// ::= .cfi_startproc [simple] bool AsmParser::parseDirectiveCFIStartProc() { StringRef Simple; if (!parseOptionalToken(AsmToken::EndOfStatement)) { if (check(parseIdentifier(Simple) || Simple != "simple", "unexpected token") || parseToken(AsmToken::EndOfStatement)) return addErrorSuffix(" in '.cfi_startproc' directive"); } getStreamer().EmitCFIStartProc(!Simple.empty()); return false; } /// parseDirectiveCFIEndProc /// ::= .cfi_endproc bool AsmParser::parseDirectiveCFIEndProc() { getStreamer().EmitCFIEndProc(); return false; } /// \brief parse register name or number. bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc) { unsigned RegNo; if (getLexer().isNot(AsmToken::Integer)) { if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc)) return true; Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true); } else return parseAbsoluteExpression(Register); return false; } /// parseDirectiveCFIDefCfa /// ::= .cfi_def_cfa register, offset bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) { int64_t Register = 0, Offset = 0; if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseToken(AsmToken::Comma, "unexpected token in directive") || parseAbsoluteExpression(Offset)) return true; getStreamer().EmitCFIDefCfa(Register, Offset); return false; } /// parseDirectiveCFIDefCfaOffset /// ::= .cfi_def_cfa_offset offset bool AsmParser::parseDirectiveCFIDefCfaOffset() { int64_t Offset = 0; if (parseAbsoluteExpression(Offset)) return true; getStreamer().EmitCFIDefCfaOffset(Offset); return false; } /// parseDirectiveCFIRegister /// ::= .cfi_register register, register bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) { int64_t Register1 = 0, Register2 = 0; if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) || parseToken(AsmToken::Comma, "unexpected token in directive") || parseRegisterOrRegisterNumber(Register2, DirectiveLoc)) return true; getStreamer().EmitCFIRegister(Register1, Register2); return false; } /// parseDirectiveCFIWindowSave /// ::= .cfi_window_save bool AsmParser::parseDirectiveCFIWindowSave() { getStreamer().EmitCFIWindowSave(); return false; } /// parseDirectiveCFIAdjustCfaOffset /// ::= .cfi_adjust_cfa_offset adjustment bool AsmParser::parseDirectiveCFIAdjustCfaOffset() { int64_t Adjustment = 0; if (parseAbsoluteExpression(Adjustment)) return true; getStreamer().EmitCFIAdjustCfaOffset(Adjustment); return false; } /// parseDirectiveCFIDefCfaRegister /// ::= .cfi_def_cfa_register register bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) { int64_t Register = 0; if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) return true; getStreamer().EmitCFIDefCfaRegister(Register); return false; } /// parseDirectiveCFIOffset /// ::= .cfi_offset register, offset bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) { int64_t Register = 0; int64_t Offset = 0; if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseToken(AsmToken::Comma, "unexpected token in directive") || parseAbsoluteExpression(Offset)) return true; getStreamer().EmitCFIOffset(Register, Offset); return false; } /// parseDirectiveCFIRelOffset /// ::= .cfi_rel_offset register, offset bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) { int64_t Register = 0, Offset = 0; if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseToken(AsmToken::Comma, "unexpected token in directive") || parseAbsoluteExpression(Offset)) return true; getStreamer().EmitCFIRelOffset(Register, Offset); return false; } static bool isValidEncoding(int64_t Encoding) { if (Encoding & ~0xff) return false; if (Encoding == dwarf::DW_EH_PE_omit) return true; const unsigned Format = Encoding & 0xf; if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 && Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 && Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 && Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed) return false; const unsigned Application = Encoding & 0x70; if (Application != dwarf::DW_EH_PE_absptr && Application != dwarf::DW_EH_PE_pcrel) return false; return true; } /// parseDirectiveCFIPersonalityOrLsda /// IsPersonality true for cfi_personality, false for cfi_lsda /// ::= .cfi_personality encoding, [symbol_name] /// ::= .cfi_lsda encoding, [symbol_name] bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) { int64_t Encoding = 0; if (parseAbsoluteExpression(Encoding)) return true; if (Encoding == dwarf::DW_EH_PE_omit) return false; StringRef Name; if (check(!isValidEncoding(Encoding), "unsupported encoding.") || parseToken(AsmToken::Comma, "unexpected token in directive") || check(parseIdentifier(Name), "expected identifier in directive")) return true; MCSymbol *Sym = getContext().getOrCreateSymbol(Name); if (IsPersonality) getStreamer().EmitCFIPersonality(Sym, Encoding); else getStreamer().EmitCFILsda(Sym, Encoding); return false; } /// parseDirectiveCFIRememberState /// ::= .cfi_remember_state bool AsmParser::parseDirectiveCFIRememberState() { getStreamer().EmitCFIRememberState(); return false; } /// parseDirectiveCFIRestoreState /// ::= .cfi_remember_state bool AsmParser::parseDirectiveCFIRestoreState() { getStreamer().EmitCFIRestoreState(); return false; } /// parseDirectiveCFISameValue /// ::= .cfi_same_value register bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) { int64_t Register = 0; if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) return true; getStreamer().EmitCFISameValue(Register); return false; } /// parseDirectiveCFIRestore /// ::= .cfi_restore register bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) { int64_t Register = 0; if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) return true; getStreamer().EmitCFIRestore(Register); return false; } /// parseDirectiveCFIEscape /// ::= .cfi_escape expression[,...] bool AsmParser::parseDirectiveCFIEscape() { std::string Values; int64_t CurrValue; if (parseAbsoluteExpression(CurrValue)) return true; Values.push_back((uint8_t)CurrValue); while (getLexer().is(AsmToken::Comma)) { Lex(); if (parseAbsoluteExpression(CurrValue)) return true; Values.push_back((uint8_t)CurrValue); } getStreamer().EmitCFIEscape(Values); return false; } /// parseDirectiveCFISignalFrame /// ::= .cfi_signal_frame bool AsmParser::parseDirectiveCFISignalFrame() { if (parseToken(AsmToken::EndOfStatement, "unexpected token in '.cfi_signal_frame'")) return true; getStreamer().EmitCFISignalFrame(); return false; } /// parseDirectiveCFIUndefined /// ::= .cfi_undefined register bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) { int64_t Register = 0; if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) return true; getStreamer().EmitCFIUndefined(Register); return false; } /// parseDirectiveMacrosOnOff /// ::= .macros_on /// ::= .macros_off bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) { if (parseToken(AsmToken::EndOfStatement, "unexpected token in '" + Directive + "' directive")) return true; setMacrosEnabled(Directive == ".macros_on"); return false; } /// parseDirectiveMacro /// ::= .macro name[,] [parameters] bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) { StringRef Name; if (parseIdentifier(Name)) return TokError("expected identifier in '.macro' directive"); if (getLexer().is(AsmToken::Comma)) Lex(); MCAsmMacroParameters Parameters; while (getLexer().isNot(AsmToken::EndOfStatement)) { if (!Parameters.empty() && Parameters.back().Vararg) return Error(Lexer.getLoc(), "Vararg parameter '" + Parameters.back().Name + "' should be last one in the list of parameters."); MCAsmMacroParameter Parameter; if (parseIdentifier(Parameter.Name)) return TokError("expected identifier in '.macro' directive"); if (Lexer.is(AsmToken::Colon)) { Lex(); // consume ':' SMLoc QualLoc; StringRef Qualifier; QualLoc = Lexer.getLoc(); if (parseIdentifier(Qualifier)) return Error(QualLoc, "missing parameter qualifier for " "'" + Parameter.Name + "' in macro '" + Name + "'"); if (Qualifier == "req") Parameter.Required = true; else if (Qualifier == "vararg") Parameter.Vararg = true; else return Error(QualLoc, Qualifier + " is not a valid parameter qualifier " "for '" + Parameter.Name + "' in macro '" + Name + "'"); } if (getLexer().is(AsmToken::Equal)) { Lex(); SMLoc ParamLoc; ParamLoc = Lexer.getLoc(); if (parseMacroArgument(Parameter.Value, /*Vararg=*/false )) return true; if (Parameter.Required) Warning(ParamLoc, "pointless default value for required parameter " "'" + Parameter.Name + "' in macro '" + Name + "'"); } Parameters.push_back(std::move(Parameter)); if (getLexer().is(AsmToken::Comma)) Lex(); } // Eat just the end of statement. Lexer.Lex(); // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors AsmToken EndToken, StartToken = getTok(); unsigned MacroDepth = 0; // Lex the macro definition. while (true) { // Ignore Lexing errors in macros. while (Lexer.is(AsmToken::Error)) { Lexer.Lex(); } // Check whether we have reached the end of the file. if (getLexer().is(AsmToken::Eof)) return Error(DirectiveLoc, "no matching '.endmacro' in definition"); // Otherwise, check whether we have reach the .endmacro. if (getLexer().is(AsmToken::Identifier)) { if (getTok().getIdentifier() == ".endm" || getTok().getIdentifier() == ".endmacro") { if (MacroDepth == 0) { // Outermost macro. EndToken = getTok(); Lexer.Lex(); if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '" + EndToken.getIdentifier() + "' directive"); break; } else { // Otherwise we just found the end of an inner macro. --MacroDepth; } } else if (getTok().getIdentifier() == ".macro") { // We allow nested macros. Those aren't instantiated until the outermost // macro is expanded so just ignore them for now. ++MacroDepth; } } // Otherwise, scan til the end of the statement. eatToEndOfStatement(); } if (lookupMacro(Name)) { return Error(DirectiveLoc, "macro '" + Name + "' is already defined"); } const char *BodyStart = StartToken.getLoc().getPointer(); const char *BodyEnd = EndToken.getLoc().getPointer(); StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart); checkForBadMacro(DirectiveLoc, Name, Body, Parameters); defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters))); return false; } /// checkForBadMacro /// /// With the support added for named parameters there may be code out there that /// is transitioning from positional parameters. In versions of gas that did /// not support named parameters they would be ignored on the macro definition. /// But to support both styles of parameters this is not possible so if a macro /// definition has named parameters but does not use them and has what appears /// to be positional parameters, strings like $1, $2, ... and $n, then issue a /// warning that the positional parameter found in body which have no effect. /// Hoping the developer will either remove the named parameters from the macro /// definition so the positional parameters get used if that was what was /// intended or change the macro to use the named parameters. It is possible /// this warning will trigger when the none of the named parameters are used /// and the strings like $1 are infact to simply to be passed trough unchanged. void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body, ArrayRef Parameters) { // If this macro is not defined with named parameters the warning we are // checking for here doesn't apply. unsigned NParameters = Parameters.size(); if (NParameters == 0) return; bool NamedParametersFound = false; bool PositionalParametersFound = false; // Look at the body of the macro for use of both the named parameters and what // are likely to be positional parameters. This is what expandMacro() is // doing when it finds the parameters in the body. while (!Body.empty()) { // Scan for the next possible parameter. std::size_t End = Body.size(), Pos = 0; for (; Pos != End; ++Pos) { // Check for a substitution or escape. // This macro is defined with parameters, look for \foo, \bar, etc. if (Body[Pos] == '\\' && Pos + 1 != End) break; // This macro should have parameters, but look for $0, $1, ..., $n too. if (Body[Pos] != '$' || Pos + 1 == End) continue; char Next = Body[Pos + 1]; if (Next == '$' || Next == 'n' || isdigit(static_cast(Next))) break; } // Check if we reached the end. if (Pos == End) break; if (Body[Pos] == '$') { switch (Body[Pos + 1]) { // $$ => $ case '$': break; // $n => number of arguments case 'n': PositionalParametersFound = true; break; // $[0-9] => argument default: { PositionalParametersFound = true; break; } } Pos += 2; } else { unsigned I = Pos + 1; 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 (Index == NParameters) { if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')') Pos += 3; else { Pos = I; } } else { NamedParametersFound = true; Pos += 1 + Argument.size(); } } // Update the scan point. Body = Body.substr(Pos); } if (!NamedParametersFound && PositionalParametersFound) Warning(DirectiveLoc, "macro defined with named parameters which are not " "used in macro body, possible positional parameter " "found in body which will have no effect"); } /// parseDirectiveExitMacro /// ::= .exitm bool AsmParser::parseDirectiveExitMacro(StringRef Directive) { if (parseToken(AsmToken::EndOfStatement, "unexpected token in '" + Directive + "' directive")) return true; if (!isInsideMacroInstantiation()) return TokError("unexpected '" + Directive + "' in file, " "no current macro definition"); // Exit all conditionals that are active in the current macro. while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) { TheCondState = TheCondStack.back(); TheCondStack.pop_back(); } handleMacroExit(); return false; } /// parseDirectiveEndMacro /// ::= .endm /// ::= .endmacro bool AsmParser::parseDirectiveEndMacro(StringRef Directive) { if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '" + Directive + "' directive"); // If we are inside a macro instantiation, terminate the current // instantiation. if (isInsideMacroInstantiation()) { handleMacroExit(); return false; } // Otherwise, this .endmacro is a stray entry in the file; well formed // .endmacro directives are handled during the macro definition parsing. return TokError("unexpected '" + Directive + "' in file, " "no current macro definition"); } /// parseDirectivePurgeMacro /// ::= .purgem bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) { StringRef Name; SMLoc Loc; if (parseTokenLoc(Loc) || check(parseIdentifier(Name), Loc, "expected identifier in '.purgem' directive") || parseToken(AsmToken::EndOfStatement, "unexpected token in '.purgem' directive")) return true; if (!lookupMacro(Name)) return Error(DirectiveLoc, "macro '" + Name + "' is not defined"); undefineMacro(Name); return false; } /// parseDirectiveBundleAlignMode /// ::= {.bundle_align_mode} expression bool AsmParser::parseDirectiveBundleAlignMode() { // Expect a single argument: an expression that evaluates to a constant // in the inclusive range 0-30. SMLoc ExprLoc = getLexer().getLoc(); int64_t AlignSizePow2; if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) || parseToken(AsmToken::EndOfStatement, "unexpected token after expression " "in '.bundle_align_mode' " "directive") || check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc, "invalid bundle alignment size (expected between 0 and 30)")) return true; // Because of AlignSizePow2's verified range we can safely truncate it to // unsigned. getStreamer().EmitBundleAlignMode(static_cast(AlignSizePow2)); return false; } /// parseDirectiveBundleLock /// ::= {.bundle_lock} [align_to_end] bool AsmParser::parseDirectiveBundleLock() { if (checkForValidSection()) return true; bool AlignToEnd = false; StringRef Option; SMLoc Loc = getTok().getLoc(); const char *kInvalidOptionError = "invalid option for '.bundle_lock' directive"; if (!parseOptionalToken(AsmToken::EndOfStatement)) { if (check(parseIdentifier(Option), Loc, kInvalidOptionError) || check(Option != "align_to_end", Loc, kInvalidOptionError) || parseToken(AsmToken::EndOfStatement, "unexpected token after '.bundle_lock' directive option")) return true; AlignToEnd = true; } getStreamer().EmitBundleLock(AlignToEnd); return false; } /// parseDirectiveBundleLock /// ::= {.bundle_lock} bool AsmParser::parseDirectiveBundleUnlock() { if (checkForValidSection() || parseToken(AsmToken::EndOfStatement, "unexpected token in '.bundle_unlock' directive")) return true; getStreamer().EmitBundleUnlock(); return false; } /// parseDirectiveSpace /// ::= (.skip | .space) expression [ , expression ] bool AsmParser::parseDirectiveSpace(StringRef IDVal) { SMLoc NumBytesLoc = Lexer.getLoc(); const MCExpr *NumBytes; if (checkForValidSection() || parseExpression(NumBytes)) return true; int64_t FillExpr = 0; if (parseOptionalToken(AsmToken::Comma)) if (parseAbsoluteExpression(FillExpr)) return addErrorSuffix("in '" + Twine(IDVal) + "' directive"); if (parseToken(AsmToken::EndOfStatement)) return addErrorSuffix("in '" + Twine(IDVal) + "' directive"); // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0. getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc); return false; } /// parseDirectiveDCB /// ::= .dcb.{b, l, w} expression, expression bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) { SMLoc NumValuesLoc = Lexer.getLoc(); int64_t NumValues; if (checkForValidSection() || parseAbsoluteExpression(NumValues)) return true; if (NumValues < 0) { Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect"); return false; } if (parseToken(AsmToken::Comma, "unexpected token in '" + Twine(IDVal) + "' directive")) return true; const MCExpr *Value; SMLoc ExprLoc = getLexer().getLoc(); if (parseExpression(Value)) return true; // Special case constant expressions to match code generator. if (const MCConstantExpr *MCE = dyn_cast(Value)) { assert(Size <= 8 && "Invalid size"); uint64_t IntValue = MCE->getValue(); if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue)) return Error(ExprLoc, "literal value out of range for directive"); for (uint64_t i = 0, e = NumValues; i != e; ++i) getStreamer().EmitIntValue(IntValue, Size); } else { for (uint64_t i = 0, e = NumValues; i != e; ++i) getStreamer().EmitValue(Value, Size, ExprLoc); } if (parseToken(AsmToken::EndOfStatement, "unexpected token in '" + Twine(IDVal) + "' directive")) return true; return false; } /// parseDirectiveRealDCB /// ::= .dcb.{d, s} expression, expression bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) { SMLoc NumValuesLoc = Lexer.getLoc(); int64_t NumValues; if (checkForValidSection() || parseAbsoluteExpression(NumValues)) return true; if (NumValues < 0) { Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect"); return false; } if (parseToken(AsmToken::Comma, "unexpected token in '" + Twine(IDVal) + "' directive")) return true; APInt AsInt; if (parseRealValue(Semantics, AsInt)) return true; if (parseToken(AsmToken::EndOfStatement, "unexpected token in '" + Twine(IDVal) + "' directive")) return true; for (uint64_t i = 0, e = NumValues; i != e; ++i) getStreamer().EmitIntValue(AsInt.getLimitedValue(), AsInt.getBitWidth() / 8); return false; } /// parseDirectiveDS /// ::= .ds.{b, d, l, p, s, w, x} expression bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) { SMLoc NumValuesLoc = Lexer.getLoc(); int64_t NumValues; if (checkForValidSection() || parseAbsoluteExpression(NumValues)) return true; if (NumValues < 0) { Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect"); return false; } if (parseToken(AsmToken::EndOfStatement, "unexpected token in '" + Twine(IDVal) + "' directive")) return true; for (uint64_t i = 0, e = NumValues; i != e; ++i) getStreamer().emitFill(Size, 0); return false; } /// parseDirectiveLEB128 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ] bool AsmParser::parseDirectiveLEB128(bool Signed) { if (checkForValidSection()) return true; auto parseOp = [&]() -> bool { const MCExpr *Value; if (parseExpression(Value)) return true; if (Signed) getStreamer().EmitSLEB128Value(Value); else getStreamer().EmitULEB128Value(Value); return false; }; if (parseMany(parseOp)) return addErrorSuffix(" in directive"); return false; } /// parseDirectiveSymbolAttribute /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ] bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) { auto parseOp = [&]() -> bool { StringRef Name; SMLoc Loc = getTok().getLoc(); if (parseIdentifier(Name)) return Error(Loc, "expected identifier"); MCSymbol *Sym = getContext().getOrCreateSymbol(Name); // Assembler local symbols don't make any sense here. Complain loudly. if (Sym->isTemporary()) return Error(Loc, "non-local symbol required"); if (!getStreamer().EmitSymbolAttribute(Sym, Attr)) return Error(Loc, "unable to emit symbol attribute"); return false; }; if (parseMany(parseOp)) return addErrorSuffix(" in directive"); return false; } /// parseDirectiveComm /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ] bool AsmParser::parseDirectiveComm(bool IsLocal) { if (checkForValidSection()) return true; SMLoc IDLoc = getLexer().getLoc(); StringRef Name; if (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 (parseAbsoluteExpression(Size)) return true; int64_t Pow2Alignment = 0; SMLoc Pow2AlignmentLoc; if (getLexer().is(AsmToken::Comma)) { Lex(); Pow2AlignmentLoc = getLexer().getLoc(); if (parseAbsoluteExpression(Pow2Alignment)) return true; LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType(); if (IsLocal && LCOMM == LCOMM::NoAlignment) return Error(Pow2AlignmentLoc, "alignment not supported on this target"); // If this target takes alignments in bytes (not log) validate and convert. if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) || (IsLocal && LCOMM == LCOMM::ByteAlignment)) { if (!isPowerOf2_64(Pow2Alignment)) return Error(Pow2AlignmentLoc, "alignment must be a power of 2"); Pow2Alignment = Log2_64(Pow2Alignment); } } if (parseToken(AsmToken::EndOfStatement, "unexpected token in '.comm' or '.lcomm' directive")) return true; // NOTE: a size of zero for a .comm should create a undefined symbol // but a size of .lcomm creates a bss symbol of size zero. if (Size < 0) return Error(SizeLoc, "invalid '.comm' or '.lcomm' 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 '.comm' or '.lcomm' directive " "alignment, can't be less than zero"); if (!Sym->isUndefined()) return Error(IDLoc, "invalid symbol redefinition"); // Create the Symbol as a common or local common with Size and Pow2Alignment if (IsLocal) { getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment); return false; } getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment); return false; } /// parseDirectiveAbort /// ::= .abort [... message ...] bool AsmParser::parseDirectiveAbort() { // FIXME: Use loc from directive. SMLoc Loc = getLexer().getLoc(); StringRef Str = parseStringToEndOfStatement(); if (parseToken(AsmToken::EndOfStatement, "unexpected token in '.abort' directive")) return true; if (Str.empty()) return Error(Loc, ".abort detected. Assembly stopping."); else return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping."); // FIXME: Actually abort assembly here. return false; } /// parseDirectiveInclude /// ::= .include "filename" bool AsmParser::parseDirectiveInclude() { // Allow the strings to have escaped octal character sequence. std::string Filename; SMLoc IncludeLoc = getTok().getLoc(); if (check(getTok().isNot(AsmToken::String), "expected string in '.include' directive") || parseEscapedString(Filename) || check(getTok().isNot(AsmToken::EndOfStatement), "unexpected token in '.include' directive") || // Attempt to switch the lexer to the included file before consuming the // end of statement to avoid losing it when we switch. check(enterIncludeFile(Filename), IncludeLoc, "Could not find include file '" + Filename + "'")) return true; return false; } /// parseDirectiveIncbin /// ::= .incbin "filename" [ , skip [ , count ] ] bool AsmParser::parseDirectiveIncbin() { // Allow the strings to have escaped octal character sequence. std::string Filename; SMLoc IncbinLoc = getTok().getLoc(); if (check(getTok().isNot(AsmToken::String), "expected string in '.incbin' directive") || parseEscapedString(Filename)) return true; int64_t Skip = 0; const MCExpr *Count = nullptr; SMLoc SkipLoc, CountLoc; if (parseOptionalToken(AsmToken::Comma)) { // The skip expression can be omitted while specifying the count, e.g: // .incbin "filename",,4 if (getTok().isNot(AsmToken::Comma)) { if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip)) return true; } if (parseOptionalToken(AsmToken::Comma)) { CountLoc = getTok().getLoc(); if (parseExpression(Count)) return true; } } if (parseToken(AsmToken::EndOfStatement, "unexpected token in '.incbin' directive")) return true; if (check(Skip < 0, SkipLoc, "skip is negative")) return true; // Attempt to process the included file. if (processIncbinFile(Filename, Skip, Count, CountLoc)) return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'"); return false; } /// parseDirectiveIf /// ::= .if{,eq,ge,gt,le,lt,ne} expression bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) { TheCondStack.push_back(TheCondState); TheCondState.TheCond = AsmCond::IfCond; if (TheCondState.Ignore) { eatToEndOfStatement(); } else { int64_t ExprValue; if (parseAbsoluteExpression(ExprValue) || parseToken(AsmToken::EndOfStatement, "unexpected token in '.if' directive")) return true; switch (DirKind) { default: llvm_unreachable("unsupported directive"); case DK_IF: case DK_IFNE: break; case DK_IFEQ: ExprValue = ExprValue == 0; break; case DK_IFGE: ExprValue = ExprValue >= 0; break; case DK_IFGT: ExprValue = ExprValue > 0; break; case DK_IFLE: ExprValue = ExprValue <= 0; break; case DK_IFLT: ExprValue = ExprValue < 0; break; } TheCondState.CondMet = ExprValue; TheCondState.Ignore = !TheCondState.CondMet; } return false; } /// parseDirectiveIfb /// ::= .ifb string bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) { TheCondStack.push_back(TheCondState); TheCondState.TheCond = AsmCond::IfCond; if (TheCondState.Ignore) { eatToEndOfStatement(); } else { StringRef Str = parseStringToEndOfStatement(); if (parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifb' directive")) return true; TheCondState.CondMet = ExpectBlank == Str.empty(); TheCondState.Ignore = !TheCondState.CondMet; } return false; } /// parseDirectiveIfc /// ::= .ifc string1, string2 /// ::= .ifnc string1, string2 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) { TheCondStack.push_back(TheCondState); TheCondState.TheCond = AsmCond::IfCond; if (TheCondState.Ignore) { eatToEndOfStatement(); } else { StringRef Str1 = parseStringToComma(); if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive")) return true; StringRef Str2 = parseStringToEndOfStatement(); if (parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifc' directive")) return true; TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim()); TheCondState.Ignore = !TheCondState.CondMet; } return false; } /// parseDirectiveIfeqs /// ::= .ifeqs string1, string2 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) { if (Lexer.isNot(AsmToken::String)) { if (ExpectEqual) return TokError("expected string parameter for '.ifeqs' directive"); return TokError("expected string parameter for '.ifnes' directive"); } StringRef String1 = getTok().getStringContents(); Lex(); if (Lexer.isNot(AsmToken::Comma)) { if (ExpectEqual) return TokError( "expected comma after first string for '.ifeqs' directive"); return TokError("expected comma after first string for '.ifnes' directive"); } Lex(); if (Lexer.isNot(AsmToken::String)) { if (ExpectEqual) return TokError("expected string parameter for '.ifeqs' directive"); return TokError("expected string parameter for '.ifnes' directive"); } StringRef String2 = getTok().getStringContents(); Lex(); TheCondStack.push_back(TheCondState); TheCondState.TheCond = AsmCond::IfCond; TheCondState.CondMet = ExpectEqual == (String1 == String2); TheCondState.Ignore = !TheCondState.CondMet; return false; } /// parseDirectiveIfdef /// ::= .ifdef symbol bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) { StringRef Name; TheCondStack.push_back(TheCondState); TheCondState.TheCond = AsmCond::IfCond; if (TheCondState.Ignore) { eatToEndOfStatement(); } else { if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") || parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'")) return true; MCSymbol *Sym = getContext().lookupSymbol(Name); if (expect_defined) TheCondState.CondMet = (Sym && !Sym->isUndefined()); else TheCondState.CondMet = (!Sym || Sym->isUndefined()); TheCondState.Ignore = !TheCondState.CondMet; } return false; } /// parseDirectiveElseIf /// ::= .elseif expression bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) { if (TheCondState.TheCond != AsmCond::IfCond && TheCondState.TheCond != AsmCond::ElseIfCond) return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an" " .if or an .elseif"); TheCondState.TheCond = AsmCond::ElseIfCond; bool LastIgnoreState = false; if (!TheCondStack.empty()) LastIgnoreState = TheCondStack.back().Ignore; if (LastIgnoreState || TheCondState.CondMet) { TheCondState.Ignore = true; eatToEndOfStatement(); } else { int64_t ExprValue; if (parseAbsoluteExpression(ExprValue)) return true; if (parseToken(AsmToken::EndOfStatement, "unexpected token in '.elseif' directive")) return true; TheCondState.CondMet = ExprValue; TheCondState.Ignore = !TheCondState.CondMet; } return false; } /// parseDirectiveElse /// ::= .else bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) { if (parseToken(AsmToken::EndOfStatement, "unexpected token in '.else' directive")) return true; if (TheCondState.TheCond != AsmCond::IfCond && TheCondState.TheCond != AsmCond::ElseIfCond) return Error(DirectiveLoc, "Encountered a .else that doesn't follow " " an .if or an .elseif"); TheCondState.TheCond = AsmCond::ElseCond; bool LastIgnoreState = false; if (!TheCondStack.empty()) LastIgnoreState = TheCondStack.back().Ignore; if (LastIgnoreState || TheCondState.CondMet) TheCondState.Ignore = true; else TheCondState.Ignore = false; return false; } /// parseDirectiveEnd /// ::= .end bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) { if (parseToken(AsmToken::EndOfStatement, "unexpected token in '.end' directive")) return true; while (Lexer.isNot(AsmToken::Eof)) Lexer.Lex(); return false; } /// parseDirectiveError /// ::= .err /// ::= .error [string] bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) { if (!TheCondStack.empty()) { if (TheCondStack.back().Ignore) { eatToEndOfStatement(); return false; } } if (!WithMessage) return Error(L, ".err encountered"); StringRef Message = ".error directive invoked in source file"; if (Lexer.isNot(AsmToken::EndOfStatement)) { if (Lexer.isNot(AsmToken::String)) return TokError(".error argument must be a string"); Message = getTok().getStringContents(); Lex(); } return Error(L, Message); } /// parseDirectiveWarning /// ::= .warning [string] bool AsmParser::parseDirectiveWarning(SMLoc L) { if (!TheCondStack.empty()) { if (TheCondStack.back().Ignore) { eatToEndOfStatement(); return false; } } StringRef Message = ".warning directive invoked in source file"; if (!parseOptionalToken(AsmToken::EndOfStatement)) { if (Lexer.isNot(AsmToken::String)) return TokError(".warning argument must be a string"); Message = getTok().getStringContents(); Lex(); if (parseToken(AsmToken::EndOfStatement, "expected end of statement in '.warning' directive")) return true; } return Warning(L, Message); } /// parseDirectiveEndIf /// ::= .endif bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) { if (parseToken(AsmToken::EndOfStatement, "unexpected token in '.endif' directive")) return true; if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty()) return Error(DirectiveLoc, "Encountered a .endif that doesn't follow " "an .if or .else"); if (!TheCondStack.empty()) { TheCondState = TheCondStack.back(); TheCondStack.pop_back(); } return false; } void AsmParser::initializeDirectiveKindMap() { DirectiveKindMap[".set"] = DK_SET; DirectiveKindMap[".equ"] = DK_EQU; DirectiveKindMap[".equiv"] = DK_EQUIV; DirectiveKindMap[".ascii"] = DK_ASCII; DirectiveKindMap[".asciz"] = DK_ASCIZ; DirectiveKindMap[".string"] = DK_STRING; DirectiveKindMap[".byte"] = DK_BYTE; DirectiveKindMap[".short"] = DK_SHORT; DirectiveKindMap[".value"] = DK_VALUE; DirectiveKindMap[".2byte"] = DK_2BYTE; DirectiveKindMap[".long"] = DK_LONG; DirectiveKindMap[".int"] = DK_INT; DirectiveKindMap[".4byte"] = DK_4BYTE; DirectiveKindMap[".quad"] = DK_QUAD; DirectiveKindMap[".8byte"] = DK_8BYTE; DirectiveKindMap[".octa"] = DK_OCTA; DirectiveKindMap[".single"] = DK_SINGLE; DirectiveKindMap[".float"] = DK_FLOAT; DirectiveKindMap[".double"] = DK_DOUBLE; DirectiveKindMap[".align"] = DK_ALIGN; DirectiveKindMap[".align32"] = DK_ALIGN32; DirectiveKindMap[".balign"] = DK_BALIGN; DirectiveKindMap[".balignw"] = DK_BALIGNW; DirectiveKindMap[".balignl"] = DK_BALIGNL; DirectiveKindMap[".p2align"] = DK_P2ALIGN; DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW; DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL; DirectiveKindMap[".org"] = DK_ORG; DirectiveKindMap[".fill"] = DK_FILL; DirectiveKindMap[".zero"] = DK_ZERO; DirectiveKindMap[".extern"] = DK_EXTERN; DirectiveKindMap[".globl"] = DK_GLOBL; DirectiveKindMap[".global"] = DK_GLOBAL; DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE; DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP; DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER; DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN; DirectiveKindMap[".reference"] = DK_REFERENCE; DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION; DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE; DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN; DirectiveKindMap[".comm"] = DK_COMM; DirectiveKindMap[".common"] = DK_COMMON; DirectiveKindMap[".lcomm"] = DK_LCOMM; DirectiveKindMap[".abort"] = DK_ABORT; DirectiveKindMap[".include"] = DK_INCLUDE; DirectiveKindMap[".incbin"] = DK_INCBIN; DirectiveKindMap[".code16"] = DK_CODE16; DirectiveKindMap[".code16gcc"] = DK_CODE16GCC; DirectiveKindMap[".rept"] = DK_REPT; DirectiveKindMap[".rep"] = DK_REPT; DirectiveKindMap[".irp"] = DK_IRP; DirectiveKindMap[".irpc"] = DK_IRPC; DirectiveKindMap[".endr"] = DK_ENDR; DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE; DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK; DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK; DirectiveKindMap[".if"] = DK_IF; DirectiveKindMap[".ifeq"] = DK_IFEQ; DirectiveKindMap[".ifge"] = DK_IFGE; DirectiveKindMap[".ifgt"] = DK_IFGT; DirectiveKindMap[".ifle"] = DK_IFLE; DirectiveKindMap[".iflt"] = DK_IFLT; DirectiveKindMap[".ifne"] = DK_IFNE; DirectiveKindMap[".ifb"] = DK_IFB; DirectiveKindMap[".ifnb"] = DK_IFNB; DirectiveKindMap[".ifc"] = DK_IFC; DirectiveKindMap[".ifeqs"] = DK_IFEQS; DirectiveKindMap[".ifnc"] = DK_IFNC; DirectiveKindMap[".ifnes"] = DK_IFNES; DirectiveKindMap[".ifdef"] = DK_IFDEF; DirectiveKindMap[".ifndef"] = DK_IFNDEF; DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF; DirectiveKindMap[".elseif"] = DK_ELSEIF; DirectiveKindMap[".else"] = DK_ELSE; DirectiveKindMap[".end"] = DK_END; DirectiveKindMap[".endif"] = DK_ENDIF; DirectiveKindMap[".skip"] = DK_SKIP; DirectiveKindMap[".space"] = DK_SPACE; DirectiveKindMap[".file"] = DK_FILE; DirectiveKindMap[".line"] = DK_LINE; DirectiveKindMap[".loc"] = DK_LOC; DirectiveKindMap[".stabs"] = DK_STABS; DirectiveKindMap[".cv_file"] = DK_CV_FILE; DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID; DirectiveKindMap[".cv_loc"] = DK_CV_LOC; DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE; DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE; DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID; DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE; DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE; DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS; DirectiveKindMap[".sleb128"] = DK_SLEB128; DirectiveKindMap[".uleb128"] = DK_ULEB128; DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS; DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC; DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC; DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA; DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET; DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET; DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER; DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET; DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET; DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY; DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA; DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE; DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE; DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE; DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE; DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE; DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME; DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED; DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER; DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE; DirectiveKindMap[".macros_on"] = DK_MACROS_ON; DirectiveKindMap[".macros_off"] = DK_MACROS_OFF; DirectiveKindMap[".macro"] = DK_MACRO; DirectiveKindMap[".exitm"] = DK_EXITM; DirectiveKindMap[".endm"] = DK_ENDM; DirectiveKindMap[".endmacro"] = DK_ENDMACRO; DirectiveKindMap[".purgem"] = DK_PURGEM; DirectiveKindMap[".err"] = DK_ERR; DirectiveKindMap[".error"] = DK_ERROR; DirectiveKindMap[".warning"] = DK_WARNING; DirectiveKindMap[".reloc"] = DK_RELOC; DirectiveKindMap[".dc"] = DK_DC; DirectiveKindMap[".dc.a"] = DK_DC_A; DirectiveKindMap[".dc.b"] = DK_DC_B; DirectiveKindMap[".dc.d"] = DK_DC_D; DirectiveKindMap[".dc.l"] = DK_DC_L; DirectiveKindMap[".dc.s"] = DK_DC_S; DirectiveKindMap[".dc.w"] = DK_DC_W; DirectiveKindMap[".dc.x"] = DK_DC_X; DirectiveKindMap[".dcb"] = DK_DCB; DirectiveKindMap[".dcb.b"] = DK_DCB_B; DirectiveKindMap[".dcb.d"] = DK_DCB_D; DirectiveKindMap[".dcb.l"] = DK_DCB_L; DirectiveKindMap[".dcb.s"] = DK_DCB_S; DirectiveKindMap[".dcb.w"] = DK_DCB_W; DirectiveKindMap[".dcb.x"] = DK_DCB_X; DirectiveKindMap[".ds"] = DK_DS; DirectiveKindMap[".ds.b"] = DK_DS_B; DirectiveKindMap[".ds.d"] = DK_DS_D; DirectiveKindMap[".ds.l"] = DK_DS_L; DirectiveKindMap[".ds.p"] = DK_DS_P; DirectiveKindMap[".ds.s"] = DK_DS_S; DirectiveKindMap[".ds.w"] = DK_DS_W; DirectiveKindMap[".ds.x"] = DK_DS_X; } MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) { AsmToken EndToken, StartToken = getTok(); unsigned NestLevel = 0; while (true) { // Check whether we have reached the end of the file. if (getLexer().is(AsmToken::Eof)) { printError(DirectiveLoc, "no matching '.endr' in definition"); return nullptr; } if (Lexer.is(AsmToken::Identifier) && (getTok().getIdentifier() == ".rept" || getTok().getIdentifier() == ".irp" || getTok().getIdentifier() == ".irpc")) { ++NestLevel; } // Otherwise, check whether we have reached the .endr. if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") { if (NestLevel == 0) { EndToken = getTok(); Lex(); if (Lexer.isNot(AsmToken::EndOfStatement)) { printError(getTok().getLoc(), "unexpected token in '.endr' directive"); return nullptr; } break; } --NestLevel; } // Otherwise, scan till the end of the statement. eatToEndOfStatement(); } const char *BodyStart = StartToken.getLoc().getPointer(); const char *BodyEnd = EndToken.getLoc().getPointer(); StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart); // We Are Anonymous. MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters()); return &MacroLikeBodies.back(); } void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc, raw_svector_ostream &OS) { OS << ".endr\n"; std::unique_ptr Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), ""); // Create the macro instantiation object and add to the current macro // instantiation stack. MacroInstantiation *MI = new MacroInstantiation( DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()); ActiveMacros.push_back(MI); // Jump to the macro instantiation and prime the lexer. CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc()); Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); Lex(); } /// parseDirectiveRept /// ::= .rep | .rept count bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) { const MCExpr *CountExpr; SMLoc CountLoc = getTok().getLoc(); if (parseExpression(CountExpr)) return true; int64_t Count; if (!CountExpr->evaluateAsAbsolute(Count)) { return Error(CountLoc, "unexpected token in '" + Dir + "' directive"); } if (check(Count < 0, CountLoc, "Count is negative") || parseToken(AsmToken::EndOfStatement, "unexpected token in '" + Dir + "' directive")) return true; // Lex the rept definition. MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); if (!M) return true; // Macro instantiation is lexical, unfortunately. We construct a new buffer // to hold the macro body with substitutions. SmallString<256> Buf; raw_svector_ostream OS(Buf); while (Count--) { // Note that the AtPseudoVariable is disabled for instantiations of .rep(t). if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc())) return true; } instantiateMacroLikeBody(M, DirectiveLoc, OS); return false; } /// parseDirectiveIrp /// ::= .irp symbol,values bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) { MCAsmMacroParameter Parameter; MCAsmMacroArguments A; if (check(parseIdentifier(Parameter.Name), "expected identifier in '.irp' directive") || parseToken(AsmToken::Comma, "expected comma in '.irp' directive") || parseMacroArguments(nullptr, A) || parseToken(AsmToken::EndOfStatement, "expected End of Statement")) return true; // Lex the irp definition. MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); if (!M) return true; // Macro instantiation is lexical, unfortunately. We construct a new buffer // to hold the macro body with substitutions. SmallString<256> Buf; raw_svector_ostream OS(Buf); for (const MCAsmMacroArgument &Arg : A) { // Note that the AtPseudoVariable is enabled for instantiations of .irp. // This is undocumented, but GAS seems to support it. if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc())) return true; } instantiateMacroLikeBody(M, DirectiveLoc, OS); return false; } /// parseDirectiveIrpc /// ::= .irpc symbol,values bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) { MCAsmMacroParameter Parameter; MCAsmMacroArguments A; if (check(parseIdentifier(Parameter.Name), "expected identifier in '.irpc' directive") || parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") || parseMacroArguments(nullptr, A)) return true; if (A.size() != 1 || A.front().size() != 1) return TokError("unexpected token in '.irpc' directive"); // Eat the end of statement. if (parseToken(AsmToken::EndOfStatement, "expected end of statement")) return true; // Lex the irpc definition. MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); if (!M) return true; // Macro instantiation is lexical, unfortunately. We construct a new buffer // to hold the macro body with substitutions. SmallString<256> Buf; raw_svector_ostream OS(Buf); StringRef Values = A.front().front().getString(); for (std::size_t I = 0, End = Values.size(); I != End; ++I) { MCAsmMacroArgument Arg; Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1)); // Note that the AtPseudoVariable is enabled for instantiations of .irpc. // This is undocumented, but GAS seems to support it. if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc())) return true; } instantiateMacroLikeBody(M, DirectiveLoc, OS); return false; } bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) { if (ActiveMacros.empty()) return TokError("unmatched '.endr' directive"); // The only .repl that should get here are the ones created by // instantiateMacroLikeBody. assert(getLexer().is(AsmToken::EndOfStatement)); handleMacroExit(); return false; } bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info, size_t Len) { const MCExpr *Value; SMLoc ExprLoc = getLexer().getLoc(); if (parseExpression(Value)) return true; const MCConstantExpr *MCE = dyn_cast(Value); if (!MCE) return Error(ExprLoc, "unexpected expression in _emit"); uint64_t IntValue = MCE->getValue(); if (!isUInt<8>(IntValue) && !isInt<8>(IntValue)) return Error(ExprLoc, "literal value out of range for directive"); Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len); return false; } bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) { const MCExpr *Value; SMLoc ExprLoc = getLexer().getLoc(); if (parseExpression(Value)) return true; const MCConstantExpr *MCE = dyn_cast(Value); if (!MCE) return Error(ExprLoc, "unexpected expression in align"); uint64_t IntValue = MCE->getValue(); if (!isPowerOf2_64(IntValue)) return Error(ExprLoc, "literal value not a power of two greater then zero"); Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue)); return false; } // We are comparing pointers, but the pointers are relative to a single string. // Thus, this should always be deterministic. static int rewritesSort(const AsmRewrite *AsmRewriteA, const AsmRewrite *AsmRewriteB) { if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer()) return -1; if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer()) return 1; // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output // rewrite to the same location. Make sure the SizeDirective rewrite is // performed first, then the Imm/ImmPrefix and finally the Input/Output. This // ensures the sort algorithm is stable. if (AsmRewritePrecedence[AsmRewriteA->Kind] > AsmRewritePrecedence[AsmRewriteB->Kind]) return -1; if (AsmRewritePrecedence[AsmRewriteA->Kind] < AsmRewritePrecedence[AsmRewriteB->Kind]) return 1; llvm_unreachable("Unstable rewrite sort."); } bool AsmParser::parseMSInlineAsm( void *AsmLoc, std::string &AsmString, unsigned &NumOutputs, unsigned &NumInputs, SmallVectorImpl > &OpDecls, SmallVectorImpl &Constraints, SmallVectorImpl &Clobbers, const MCInstrInfo *MII, const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) { SmallVector InputDecls; SmallVector OutputDecls; SmallVector InputDeclsAddressOf; SmallVector OutputDeclsAddressOf; SmallVector InputConstraints; SmallVector OutputConstraints; SmallVector ClobberRegs; SmallVector AsmStrRewrites; // Prime the lexer. Lex(); // While we have input, parse each statement. unsigned InputIdx = 0; unsigned OutputIdx = 0; while (getLexer().isNot(AsmToken::Eof)) { // Parse curly braces marking block start/end if (parseCurlyBlockScope(AsmStrRewrites)) continue; ParseStatementInfo Info(&AsmStrRewrites); bool StatementErr = parseStatement(Info, &SI); if (StatementErr || Info.ParseError) { // Emit pending errors if any exist. printPendingErrors(); return true; } // No pending error should exist here. assert(!hasPendingError() && "unexpected error from parseStatement"); if (Info.Opcode == ~0U) continue; const MCInstrDesc &Desc = MII->get(Info.Opcode); // Build the list of clobbers, outputs and inputs. for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) { MCParsedAsmOperand &Operand = *Info.ParsedOperands[i]; // Immediate. if (Operand.isImm()) continue; // Register operand. if (Operand.isReg() && !Operand.needAddressOf() && !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) { unsigned NumDefs = Desc.getNumDefs(); // Clobber. if (NumDefs && Operand.getMCOperandNum() < NumDefs) ClobberRegs.push_back(Operand.getReg()); continue; } // Expr/Input or Output. StringRef SymName = Operand.getSymName(); if (SymName.empty()) continue; void *OpDecl = Operand.getOpDecl(); if (!OpDecl) continue; bool isOutput = (i == 1) && Desc.mayStore(); SMLoc Start = SMLoc::getFromPointer(SymName.data()); if (isOutput) { ++InputIdx; OutputDecls.push_back(OpDecl); OutputDeclsAddressOf.push_back(Operand.needAddressOf()); OutputConstraints.push_back(("=" + Operand.getConstraint()).str()); AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size()); } else { InputDecls.push_back(OpDecl); InputDeclsAddressOf.push_back(Operand.needAddressOf()); InputConstraints.push_back(Operand.getConstraint().str()); AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size()); } } // Consider implicit defs to be clobbers. Think of cpuid and push. ArrayRef ImpDefs(Desc.getImplicitDefs(), Desc.getNumImplicitDefs()); ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end()); } // Set the number of Outputs and Inputs. NumOutputs = OutputDecls.size(); NumInputs = InputDecls.size(); // Set the unique clobbers. array_pod_sort(ClobberRegs.begin(), ClobberRegs.end()); ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()), ClobberRegs.end()); Clobbers.assign(ClobberRegs.size(), std::string()); for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) { raw_string_ostream OS(Clobbers[I]); IP->printRegName(OS, ClobberRegs[I]); } // Merge the various outputs and inputs. Output are expected first. if (NumOutputs || NumInputs) { unsigned NumExprs = NumOutputs + NumInputs; OpDecls.resize(NumExprs); Constraints.resize(NumExprs); for (unsigned i = 0; i < NumOutputs; ++i) { OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]); Constraints[i] = OutputConstraints[i]; } for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) { OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]); Constraints[j] = InputConstraints[i]; } } // Build the IR assembly string. std::string AsmStringIR; raw_string_ostream OS(AsmStringIR); StringRef ASMString = SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer(); const char *AsmStart = ASMString.begin(); const char *AsmEnd = ASMString.end(); array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort); for (const AsmRewrite &AR : AsmStrRewrites) { AsmRewriteKind Kind = AR.Kind; if (Kind == AOK_Delete) continue; const char *Loc = AR.Loc.getPointer(); assert(Loc >= AsmStart && "Expected Loc to be at or after Start!"); // Emit everything up to the immediate/expression. if (unsigned Len = Loc - AsmStart) OS << StringRef(AsmStart, Len); // Skip the original expression. if (Kind == AOK_Skip) { AsmStart = Loc + AR.Len; continue; } unsigned AdditionalSkip = 0; // Rewrite expressions in $N notation. switch (Kind) { default: break; case AOK_Imm: OS << "$$" << AR.Val; break; case AOK_ImmPrefix: OS << "$$"; break; case AOK_Label: OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label; break; case AOK_Input: OS << '$' << InputIdx++; break; case AOK_Output: OS << '$' << OutputIdx++; break; case AOK_SizeDirective: switch (AR.Val) { default: break; case 8: OS << "byte ptr "; break; case 16: OS << "word ptr "; break; case 32: OS << "dword ptr "; break; case 64: OS << "qword ptr "; break; case 80: OS << "xword ptr "; break; case 128: OS << "xmmword ptr "; break; case 256: OS << "ymmword ptr "; break; } break; case AOK_Emit: OS << ".byte"; break; case AOK_Align: { // MS alignment directives are measured in bytes. If the native assembler // measures alignment in bytes, we can pass it straight through. OS << ".align"; if (getContext().getAsmInfo()->getAlignmentIsInBytes()) break; // Alignment is in log2 form, so print that instead and skip the original // immediate. unsigned Val = AR.Val; OS << ' ' << Val; assert(Val < 10 && "Expected alignment less then 2^10."); AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4; break; } case AOK_EVEN: OS << ".even"; break; case AOK_DotOperator: // Insert the dot if the user omitted it. OS.flush(); if (AsmStringIR.back() != '.') OS << '.'; OS << AR.Val; break; case AOK_EndOfStatement: OS << "\n\t"; break; } // Skip the original expression. AsmStart = Loc + AR.Len + AdditionalSkip; } // Emit the remainder of the asm string. if (AsmStart != AsmEnd) OS << StringRef(AsmStart, AsmEnd - AsmStart); AsmString = OS.str(); return false; } namespace llvm { namespace MCParserUtils { /// Returns whether the given symbol is used anywhere in the given expression, /// or subexpressions. static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) { switch (Value->getKind()) { case MCExpr::Binary: { const MCBinaryExpr *BE = static_cast(Value); return isSymbolUsedInExpression(Sym, BE->getLHS()) || isSymbolUsedInExpression(Sym, BE->getRHS()); } case MCExpr::Target: case MCExpr::Constant: return false; case MCExpr::SymbolRef: { const MCSymbol &S = static_cast(Value)->getSymbol(); if (S.isVariable()) return isSymbolUsedInExpression(Sym, S.getVariableValue()); return &S == Sym; } case MCExpr::Unary: return isSymbolUsedInExpression( Sym, static_cast(Value)->getSubExpr()); } llvm_unreachable("Unknown expr kind!"); } bool parseAssignmentExpression(StringRef Name, bool allow_redef, MCAsmParser &Parser, MCSymbol *&Sym, const MCExpr *&Value) { // FIXME: Use better location, we should use proper tokens. SMLoc EqualLoc = Parser.getTok().getLoc(); if (Parser.parseExpression(Value)) { return Parser.TokError("missing expression"); } // Note: we don't count b as used in "a = b". This is to allow // a = b // b = c if (Parser.parseToken(AsmToken::EndOfStatement)) return true; // Validate that the LHS is allowed to be a variable (either it has not been // used as a symbol, or it is an absolute symbol). Sym = Parser.getContext().lookupSymbol(Name); if (Sym) { // Diagnose assignment to a label. // // FIXME: Diagnostics. Note the location of the definition as a label. // FIXME: Diagnose assignment to protected identifier (e.g., register name). if (isSymbolUsedInExpression(Sym, Value)) return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'"); else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() && !Sym->isVariable()) ; // Allow redefinitions of undefined symbols only used in directives. else if (Sym->isVariable() && !Sym->isUsed() && allow_redef) ; // Allow redefinitions of variables that haven't yet been used. else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef)) return Parser.Error(EqualLoc, "redefinition of '" + Name + "'"); else if (!Sym->isVariable()) return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'"); else if (!isa(Sym->getVariableValue())) return Parser.Error(EqualLoc, "invalid reassignment of non-absolute variable '" + Name + "'"); } else if (Name == ".") { Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc); return false; } else Sym = Parser.getContext().getOrCreateSymbol(Name); Sym->setRedefinable(allow_redef); return false; } } // end namespace MCParserUtils } // end namespace llvm /// \brief Create an MCAsmParser instance. MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C, - MCStreamer &Out, const MCAsmInfo &MAI) { - return new AsmParser(SM, C, Out, MAI); + MCStreamer &Out, const MCAsmInfo &MAI, + unsigned CB) { + return new AsmParser(SM, C, Out, MAI, CB); }