xref: /freebsd/contrib/llvm-project/llvm/include/llvm/MC/MCParser/MCAsmParser.h (revision e64bea71c21eb42e97aa615188ba91f6cce0d36d)
1 //===- llvm/MC/MCAsmParser.h - Abstract Asm Parser Interface ----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLVM_MC_MCPARSER_MCASMPARSER_H
10 #define LLVM_MC_MCPARSER_MCASMPARSER_H
11 
12 #include "llvm/ADT/STLFunctionalExtras.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/MC/MCAsmMacro.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCParser/AsmLexer.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/SMLoc.h"
22 #include <cstdint>
23 #include <string>
24 #include <utility>
25 
26 namespace llvm {
27 
28 class MCAsmInfo;
29 class MCAsmParserExtension;
30 class MCExpr;
31 class MCInstPrinter;
32 class MCInstrInfo;
33 class MCStreamer;
34 class MCTargetAsmParser;
35 class SourceMgr;
36 
37 struct InlineAsmIdentifierInfo {
38   enum IdKind {
39     IK_Invalid,  // Initial state. Unexpected after a successful parsing.
40     IK_Label,    // Function/Label reference.
41     IK_EnumVal,  // Value of enumeration type.
42     IK_Var       // Variable.
43   };
44   // Represents an Enum value
45   struct EnumIdentifier {
46     int64_t EnumVal;
47   };
48   // Represents a label/function reference
49   struct LabelIdentifier {
50     void *Decl;
51   };
52   // Represents a variable
53   struct VariableIdentifier {
54     void *Decl;
55     bool IsGlobalLV;
56     unsigned Length;
57     unsigned Size;
58     unsigned Type;
59   };
60   // An InlineAsm identifier can only be one of those
61   union {
62     EnumIdentifier Enum;
63     LabelIdentifier Label;
64     VariableIdentifier Var;
65   };
isKindInlineAsmIdentifierInfo66   bool isKind(IdKind kind) const { return Kind == kind; }
67   // Initializers
setEnumInlineAsmIdentifierInfo68   void setEnum(int64_t enumVal) {
69     assert(isKind(IK_Invalid) && "should be initialized only once");
70     Kind = IK_EnumVal;
71     Enum.EnumVal = enumVal;
72   }
setLabelInlineAsmIdentifierInfo73   void setLabel(void *decl) {
74     assert(isKind(IK_Invalid) && "should be initialized only once");
75     Kind = IK_Label;
76     Label.Decl = decl;
77   }
setVarInlineAsmIdentifierInfo78   void setVar(void *decl, bool isGlobalLV, unsigned size, unsigned type) {
79     assert(isKind(IK_Invalid) && "should be initialized only once");
80     Kind = IK_Var;
81     Var.Decl = decl;
82     Var.IsGlobalLV = isGlobalLV;
83     Var.Size = size;
84     Var.Type = type;
85     Var.Length = size / type;
86   }
87   InlineAsmIdentifierInfo() = default;
88 
89 private:
90   // Discriminate using the current kind.
91   IdKind Kind = IK_Invalid;
92 };
93 
94 // Generic type information for an assembly object.
95 // All sizes measured in bytes.
96 struct AsmTypeInfo {
97   StringRef Name;
98   unsigned Size = 0;
99   unsigned ElementSize = 0;
100   unsigned Length = 0;
101 };
102 
103 struct AsmFieldInfo {
104   AsmTypeInfo Type;
105   unsigned Offset = 0;
106 };
107 
108 /// Generic Sema callback for assembly parser.
109 class LLVM_ABI MCAsmParserSemaCallback {
110 public:
111   virtual ~MCAsmParserSemaCallback();
112 
113   virtual void LookupInlineAsmIdentifier(StringRef &LineBuf,
114                                          InlineAsmIdentifierInfo &Info,
115                                          bool IsUnevaluatedContext) = 0;
116   virtual StringRef LookupInlineAsmLabel(StringRef Identifier, SourceMgr &SM,
117                                          SMLoc Location, bool Create) = 0;
118   virtual bool LookupInlineAsmField(StringRef Base, StringRef Member,
119                                     unsigned &Offset) = 0;
120 };
121 
122 /// Generic assembler parser interface, for use by target specific
123 /// assembly parsers.
124 class LLVM_ABI MCAsmParser {
125 public:
126   using DirectiveHandler = bool (*)(MCAsmParserExtension*, StringRef, SMLoc);
127   using ExtensionDirectiveHandler =
128       std::pair<MCAsmParserExtension*, DirectiveHandler>;
129 
130   struct MCPendingError {
131     SMLoc Loc;
132     SmallString<64> Msg;
133     SMRange Range;
134   };
135 
136 private:
137   MCTargetAsmParser *TargetParser = nullptr;
138 
139 protected: // Can only create subclasses.
140   MCAsmParser(MCContext &, MCStreamer &, SourceMgr &, const MCAsmInfo &);
141 
142   MCContext &Ctx;
143   MCStreamer &Out;
144   SourceMgr &SrcMgr;
145   const MCAsmInfo &MAI;
146   AsmLexer Lexer;
147   SmallVector<MCPendingError, 0> PendingErrors;
148 
149   /// Flag tracking whether any errors have been encountered.
150   bool HadError = false;
151 
152   bool ShowParsedOperands = false;
153 
154 public:
155   MCAsmParser(const MCAsmParser &) = delete;
156   MCAsmParser &operator=(const MCAsmParser &) = delete;
157   virtual ~MCAsmParser();
158 
159   virtual void addDirectiveHandler(StringRef Directive,
160                                    ExtensionDirectiveHandler Handler) = 0;
161 
162   virtual void addAliasForDirective(StringRef Directive, StringRef Alias) = 0;
163 
getContext()164   MCContext &getContext() { return Ctx; }
getStreamer()165   MCStreamer &getStreamer() { return Out; }
getSourceManager()166   SourceMgr &getSourceManager() { return SrcMgr; }
getLexer()167   AsmLexer &getLexer() { return Lexer; }
getLexer()168   const AsmLexer &getLexer() const { return Lexer; }
169 
getTargetParser()170   MCTargetAsmParser &getTargetParser() const { return *TargetParser; }
171   void setTargetParser(MCTargetAsmParser &P);
172 
getAssemblerDialect()173   virtual unsigned getAssemblerDialect() { return 0;}
setAssemblerDialect(unsigned i)174   virtual void setAssemblerDialect(unsigned i) { }
175 
getShowParsedOperands()176   bool getShowParsedOperands() const { return ShowParsedOperands; }
setShowParsedOperands(bool Value)177   void setShowParsedOperands(bool Value) { ShowParsedOperands = Value; }
178 
179   /// Run the parser on the input source buffer.
180   virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false) = 0;
181 
182   virtual void setParsingMSInlineAsm(bool V) = 0;
183   virtual bool isParsingMSInlineAsm() = 0;
184 
discardLTOSymbol(StringRef)185   virtual bool discardLTOSymbol(StringRef) const { return false; }
186 
isParsingMasm()187   virtual bool isParsingMasm() const { return false; }
188 
defineMacro(StringRef Name,StringRef Value)189   virtual bool defineMacro(StringRef Name, StringRef Value) { return true; }
190 
lookUpField(StringRef Name,AsmFieldInfo & Info)191   virtual bool lookUpField(StringRef Name, AsmFieldInfo &Info) const {
192     return true;
193   }
lookUpField(StringRef Base,StringRef Member,AsmFieldInfo & Info)194   virtual bool lookUpField(StringRef Base, StringRef Member,
195                            AsmFieldInfo &Info) const {
196     return true;
197   }
198 
lookUpType(StringRef Name,AsmTypeInfo & Info)199   virtual bool lookUpType(StringRef Name, AsmTypeInfo &Info) const {
200     return true;
201   }
202 
203   /// Parse MS-style inline assembly.
204   virtual bool parseMSInlineAsm(
205       std::string &AsmString, unsigned &NumOutputs, unsigned &NumInputs,
206       SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
207       SmallVectorImpl<std::string> &Constraints,
208       SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
209       MCInstPrinter *IP, MCAsmParserSemaCallback &SI) = 0;
210 
211   /// Emit a note at the location \p L, with the message \p Msg.
212   virtual void Note(SMLoc L, const Twine &Msg,
213                     SMRange Range = std::nullopt) = 0;
214 
215   /// Emit a warning at the location \p L, with the message \p Msg.
216   ///
217   /// \return The return value is true, if warnings are fatal.
218   virtual bool Warning(SMLoc L, const Twine &Msg,
219                        SMRange Range = std::nullopt) = 0;
220 
221   /// Return an error at the location \p L, with the message \p Msg. This
222   /// may be modified before being emitted.
223   ///
224   /// \return The return value is always true, as an idiomatic convenience to
225   /// clients.
226   bool Error(SMLoc L, const Twine &Msg, SMRange Range = std::nullopt);
227 
228   /// Emit an error at the location \p L, with the message \p Msg.
229   ///
230   /// \return The return value is always true, as an idiomatic convenience to
231   /// clients.
232   virtual bool printError(SMLoc L, const Twine &Msg,
233                           SMRange Range = std::nullopt) = 0;
234 
hasPendingError()235   bool hasPendingError() { return !PendingErrors.empty(); }
236 
printPendingErrors()237   bool printPendingErrors() {
238     bool rv = !PendingErrors.empty();
239     for (auto &Err : PendingErrors) {
240       printError(Err.Loc, Twine(Err.Msg), Err.Range);
241     }
242     PendingErrors.clear();
243     return rv;
244   }
245 
clearPendingErrors()246   void clearPendingErrors() { PendingErrors.clear(); }
247 
248   bool addErrorSuffix(const Twine &Suffix);
249 
250   /// Get the next AsmToken in the stream, possibly handling file
251   /// inclusion first.
252   virtual const AsmToken &Lex() = 0;
253 
254   /// Get the current AsmToken from the stream.
255   const AsmToken &getTok() const;
256 
257   /// Report an error at the current lexer location.
258   bool TokError(const Twine &Msg, SMRange Range = std::nullopt);
259 
260   bool parseTokenLoc(SMLoc &Loc);
261   bool parseToken(AsmToken::TokenKind T, const Twine &Msg = "unexpected token");
262   /// Attempt to parse and consume token, returning true on
263   /// success.
264   bool parseOptionalToken(AsmToken::TokenKind T);
265 
parseComma()266   bool parseComma() { return parseToken(AsmToken::Comma, "expected comma"); }
parseRParen()267   bool parseRParen() { return parseToken(AsmToken::RParen, "expected ')'"); }
268   bool parseEOL();
269   bool parseEOL(const Twine &ErrMsg);
270 
271   bool parseMany(function_ref<bool()> parseOne, bool hasComma = true);
272 
273   bool parseIntToken(int64_t &V, const Twine &ErrMsg = "expected integer");
274 
275   bool check(bool P, const Twine &Msg);
276   bool check(bool P, SMLoc Loc, const Twine &Msg);
277 
278   /// Parse an identifier or string (as a quoted identifier) and set \p
279   /// Res to the identifier contents.
280   virtual bool parseIdentifier(StringRef &Res) = 0;
281 
282   /// Parse identifier and get or create symbol for it.
283   bool parseSymbol(MCSymbol *&Res);
284 
285   /// Parse up to the end of statement and return the contents from the
286   /// current token until the end of the statement; the current token on exit
287   /// will be either the EndOfStatement or EOF.
288   virtual StringRef parseStringToEndOfStatement() = 0;
289 
290   /// Parse the current token as a string which may include escaped
291   /// characters and return the string contents.
292   virtual bool parseEscapedString(std::string &Data) = 0;
293 
294   /// Parse an angle-bracket delimited string at the current position if one is
295   /// present, returning the string contents.
296   virtual bool parseAngleBracketString(std::string &Data) = 0;
297 
298   /// Skip to the end of the current statement, for error recovery.
299   virtual void eatToEndOfStatement() = 0;
300 
301   /// Parse an arbitrary expression.
302   ///
303   /// \param Res - The value of the expression. The result is undefined
304   /// on error.
305   /// \return - False on success.
306   virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) = 0;
307   bool parseExpression(const MCExpr *&Res);
308 
309   /// Parse a primary expression.
310   ///
311   /// \param Res - The value of the expression. The result is undefined
312   /// on error.
313   /// \return - False on success.
314   virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc,
315                                 AsmTypeInfo *TypeInfo = nullptr) = 0;
316 
317   /// Parse an arbitrary expression, assuming that an initial '(' has
318   /// already been consumed.
319   ///
320   /// \param Res - The value of the expression. The result is undefined
321   /// on error.
322   /// \return - False on success.
323   virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) = 0;
324 
325   /// Parse an expression which must evaluate to an absolute value.
326   ///
327   /// \param Res - The value of the absolute expression. The result is undefined
328   /// on error.
329   /// \return - False on success.
330   virtual bool parseAbsoluteExpression(int64_t &Res) = 0;
331 
332   /// Ensure that we have a valid section set in the streamer. Otherwise,
333   /// report an error and switch to .text.
334   /// \return - False on success.
335   virtual bool checkForValidSection() = 0;
336 
337   /// Parse a .gnu_attribute.
338   bool parseGNUAttribute(SMLoc L, int64_t &Tag, int64_t &IntegerValue);
339 
340   bool parseAtSpecifier(const MCExpr *&Res, SMLoc &EndLoc);
341   const MCExpr *applySpecifier(const MCExpr *E, uint32_t Variant);
342 };
343 
344 /// Create an MCAsmParser instance for parsing assembly similar to gas syntax
345 LLVM_ABI MCAsmParser *createMCAsmParser(SourceMgr &, MCContext &, MCStreamer &,
346                                         const MCAsmInfo &, unsigned CB = 0);
347 
348 /// Create an MCAsmParser instance for parsing Microsoft MASM-style assembly
349 LLVM_ABI MCAsmParser *createMCMasmParser(SourceMgr &, MCContext &, MCStreamer &,
350                                          const MCAsmInfo &, struct tm,
351                                          unsigned CB = 0);
352 
353 } // end namespace llvm
354 
355 #endif // LLVM_MC_MCPARSER_MCASMPARSER_H
356