MCTargetAsmParser.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/MC/MCTargetAsmParser.h - Target Assembly Parser -----*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_MC_MCPARSER_MCTARGETASMPARSER_H
  14. #define LLVM_MC_MCPARSER_MCTARGETASMPARSER_H
  15. #include "llvm/ADT/StringRef.h"
  16. #include "llvm/MC/MCExpr.h"
  17. #include "llvm/MC/MCInstrInfo.h"
  18. #include "llvm/MC/MCParser/MCAsmLexer.h"
  19. #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
  20. #include "llvm/MC/MCParser/MCAsmParserExtension.h"
  21. #include "llvm/MC/MCTargetOptions.h"
  22. #include "llvm/MC/SubtargetFeature.h"
  23. #include "llvm/Support/SMLoc.h"
  24. #include <cstdint>
  25. #include <memory>
  26. namespace llvm {
  27. class MCInst;
  28. class MCStreamer;
  29. class MCSubtargetInfo;
  30. template <typename T> class SmallVectorImpl;
  31. using OperandVector = SmallVectorImpl<std::unique_ptr<MCParsedAsmOperand>>;
  32. enum AsmRewriteKind {
  33. AOK_Align, // Rewrite align as .align.
  34. AOK_EVEN, // Rewrite even as .even.
  35. AOK_Emit, // Rewrite _emit as .byte.
  36. AOK_CallInput, // Rewrite in terms of ${N:P}.
  37. AOK_Input, // Rewrite in terms of $N.
  38. AOK_Output, // Rewrite in terms of $N.
  39. AOK_SizeDirective, // Add a sizing directive (e.g., dword ptr).
  40. AOK_Label, // Rewrite local labels.
  41. AOK_EndOfStatement, // Add EndOfStatement (e.g., "\n\t").
  42. AOK_Skip, // Skip emission (e.g., offset/type operators).
  43. AOK_IntelExpr // SizeDirective SymDisp [BaseReg + IndexReg * Scale + ImmDisp]
  44. };
  45. const char AsmRewritePrecedence [] = {
  46. 2, // AOK_Align
  47. 2, // AOK_EVEN
  48. 2, // AOK_Emit
  49. 3, // AOK_Input
  50. 3, // AOK_CallInput
  51. 3, // AOK_Output
  52. 5, // AOK_SizeDirective
  53. 1, // AOK_Label
  54. 5, // AOK_EndOfStatement
  55. 2, // AOK_Skip
  56. 2 // AOK_IntelExpr
  57. };
  58. // Represnt the various parts which makes up an intel expression,
  59. // used for emitting compound intel expressions
  60. struct IntelExpr {
  61. bool NeedBracs;
  62. int64_t Imm;
  63. StringRef BaseReg;
  64. StringRef IndexReg;
  65. StringRef OffsetName;
  66. unsigned Scale;
  67. IntelExpr()
  68. : NeedBracs(false), Imm(0), BaseReg(StringRef()), IndexReg(StringRef()),
  69. OffsetName(StringRef()), Scale(1) {}
  70. // [BaseReg + IndexReg * ScaleExpression + OFFSET name + ImmediateExpression]
  71. IntelExpr(StringRef baseReg, StringRef indexReg, unsigned scale,
  72. StringRef offsetName, int64_t imm, bool needBracs)
  73. : NeedBracs(needBracs), Imm(imm), BaseReg(baseReg), IndexReg(indexReg),
  74. OffsetName(offsetName), Scale(1) {
  75. if (scale)
  76. Scale = scale;
  77. }
  78. bool hasBaseReg() const { return !BaseReg.empty(); }
  79. bool hasIndexReg() const { return !IndexReg.empty(); }
  80. bool hasRegs() const { return hasBaseReg() || hasIndexReg(); }
  81. bool hasOffset() const { return !OffsetName.empty(); }
  82. // Normally we won't emit immediates unconditionally,
  83. // unless we've got no other components
  84. bool emitImm() const { return !(hasRegs() || hasOffset()); }
  85. bool isValid() const {
  86. return (Scale == 1) ||
  87. (hasIndexReg() && (Scale == 2 || Scale == 4 || Scale == 8));
  88. }
  89. };
  90. struct AsmRewrite {
  91. AsmRewriteKind Kind;
  92. SMLoc Loc;
  93. unsigned Len;
  94. bool Done;
  95. int64_t Val;
  96. StringRef Label;
  97. IntelExpr IntelExp;
  98. public:
  99. AsmRewrite(AsmRewriteKind kind, SMLoc loc, unsigned len = 0, int64_t val = 0)
  100. : Kind(kind), Loc(loc), Len(len), Done(false), Val(val) {}
  101. AsmRewrite(AsmRewriteKind kind, SMLoc loc, unsigned len, StringRef label)
  102. : AsmRewrite(kind, loc, len) { Label = label; }
  103. AsmRewrite(SMLoc loc, unsigned len, IntelExpr exp)
  104. : AsmRewrite(AOK_IntelExpr, loc, len) { IntelExp = exp; }
  105. };
  106. struct ParseInstructionInfo {
  107. SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
  108. ParseInstructionInfo() = default;
  109. ParseInstructionInfo(SmallVectorImpl<AsmRewrite> *rewrites)
  110. : AsmRewrites(rewrites) {}
  111. };
  112. enum OperandMatchResultTy {
  113. MatchOperand_Success, // operand matched successfully
  114. MatchOperand_NoMatch, // operand did not match
  115. MatchOperand_ParseFail // operand matched but had errors
  116. };
  117. enum class DiagnosticPredicateTy {
  118. Match,
  119. NearMatch,
  120. NoMatch,
  121. };
  122. // When an operand is parsed, the assembler will try to iterate through a set of
  123. // possible operand classes that the operand might match and call the
  124. // corresponding PredicateMethod to determine that.
  125. //
  126. // If there are two AsmOperands that would give a specific diagnostic if there
  127. // is no match, there is currently no mechanism to distinguish which operand is
  128. // a closer match. The DiagnosticPredicate distinguishes between 'completely
  129. // no match' and 'near match', so the assembler can decide whether to give a
  130. // specific diagnostic, or use 'InvalidOperand' and continue to find a
  131. // 'better matching' diagnostic.
  132. //
  133. // For example:
  134. // opcode opnd0, onpd1, opnd2
  135. //
  136. // where:
  137. // opnd2 could be an 'immediate of range [-8, 7]'
  138. // opnd2 could be a 'register + shift/extend'.
  139. //
  140. // If opnd2 is a valid register, but with a wrong shift/extend suffix, it makes
  141. // little sense to give a diagnostic that the operand should be an immediate
  142. // in range [-8, 7].
  143. //
  144. // This is a light-weight alternative to the 'NearMissInfo' approach
  145. // below which collects *all* possible diagnostics. This alternative
  146. // is optional and fully backward compatible with existing
  147. // PredicateMethods that return a 'bool' (match or no match).
  148. struct DiagnosticPredicate {
  149. DiagnosticPredicateTy Type;
  150. explicit DiagnosticPredicate(bool Match)
  151. : Type(Match ? DiagnosticPredicateTy::Match
  152. : DiagnosticPredicateTy::NearMatch) {}
  153. DiagnosticPredicate(DiagnosticPredicateTy T) : Type(T) {}
  154. DiagnosticPredicate(const DiagnosticPredicate &) = default;
  155. DiagnosticPredicate& operator=(const DiagnosticPredicate &) = default;
  156. operator bool() const { return Type == DiagnosticPredicateTy::Match; }
  157. bool isMatch() const { return Type == DiagnosticPredicateTy::Match; }
  158. bool isNearMatch() const { return Type == DiagnosticPredicateTy::NearMatch; }
  159. bool isNoMatch() const { return Type == DiagnosticPredicateTy::NoMatch; }
  160. };
  161. // When matching of an assembly instruction fails, there may be multiple
  162. // encodings that are close to being a match. It's often ambiguous which one
  163. // the programmer intended to use, so we want to report an error which mentions
  164. // each of these "near-miss" encodings. This struct contains information about
  165. // one such encoding, and why it did not match the parsed instruction.
  166. class NearMissInfo {
  167. public:
  168. enum NearMissKind {
  169. NoNearMiss,
  170. NearMissOperand,
  171. NearMissFeature,
  172. NearMissPredicate,
  173. NearMissTooFewOperands,
  174. };
  175. // The encoding is valid for the parsed assembly string. This is only used
  176. // internally to the table-generated assembly matcher.
  177. static NearMissInfo getSuccess() { return NearMissInfo(); }
  178. // The instruction encoding is not valid because it requires some target
  179. // features that are not currently enabled. MissingFeatures has a bit set for
  180. // each feature that the encoding needs but which is not enabled.
  181. static NearMissInfo getMissedFeature(const FeatureBitset &MissingFeatures) {
  182. NearMissInfo Result;
  183. Result.Kind = NearMissFeature;
  184. Result.Features = MissingFeatures;
  185. return Result;
  186. }
  187. // The instruction encoding is not valid because the target-specific
  188. // predicate function returned an error code. FailureCode is the
  189. // target-specific error code returned by the predicate.
  190. static NearMissInfo getMissedPredicate(unsigned FailureCode) {
  191. NearMissInfo Result;
  192. Result.Kind = NearMissPredicate;
  193. Result.PredicateError = FailureCode;
  194. return Result;
  195. }
  196. // The instruction encoding is not valid because one (and only one) parsed
  197. // operand is not of the correct type. OperandError is the error code
  198. // relating to the operand class expected by the encoding. OperandClass is
  199. // the type of the expected operand. Opcode is the opcode of the encoding.
  200. // OperandIndex is the index into the parsed operand list.
  201. static NearMissInfo getMissedOperand(unsigned OperandError,
  202. unsigned OperandClass, unsigned Opcode,
  203. unsigned OperandIndex) {
  204. NearMissInfo Result;
  205. Result.Kind = NearMissOperand;
  206. Result.MissedOperand.Error = OperandError;
  207. Result.MissedOperand.Class = OperandClass;
  208. Result.MissedOperand.Opcode = Opcode;
  209. Result.MissedOperand.Index = OperandIndex;
  210. return Result;
  211. }
  212. // The instruction encoding is not valid because it expects more operands
  213. // than were parsed. OperandClass is the class of the expected operand that
  214. // was not provided. Opcode is the instruction encoding.
  215. static NearMissInfo getTooFewOperands(unsigned OperandClass,
  216. unsigned Opcode) {
  217. NearMissInfo Result;
  218. Result.Kind = NearMissTooFewOperands;
  219. Result.TooFewOperands.Class = OperandClass;
  220. Result.TooFewOperands.Opcode = Opcode;
  221. return Result;
  222. }
  223. operator bool() const { return Kind != NoNearMiss; }
  224. NearMissKind getKind() const { return Kind; }
  225. // Feature flags required by the instruction, that the current target does
  226. // not have.
  227. const FeatureBitset& getFeatures() const {
  228. assert(Kind == NearMissFeature);
  229. return Features;
  230. }
  231. // Error code returned by the target predicate when validating this
  232. // instruction encoding.
  233. unsigned getPredicateError() const {
  234. assert(Kind == NearMissPredicate);
  235. return PredicateError;
  236. }
  237. // MatchClassKind of the operand that we expected to see.
  238. unsigned getOperandClass() const {
  239. assert(Kind == NearMissOperand || Kind == NearMissTooFewOperands);
  240. return MissedOperand.Class;
  241. }
  242. // Opcode of the encoding we were trying to match.
  243. unsigned getOpcode() const {
  244. assert(Kind == NearMissOperand || Kind == NearMissTooFewOperands);
  245. return MissedOperand.Opcode;
  246. }
  247. // Error code returned when validating the operand.
  248. unsigned getOperandError() const {
  249. assert(Kind == NearMissOperand);
  250. return MissedOperand.Error;
  251. }
  252. // Index of the actual operand we were trying to match in the list of parsed
  253. // operands.
  254. unsigned getOperandIndex() const {
  255. assert(Kind == NearMissOperand);
  256. return MissedOperand.Index;
  257. }
  258. private:
  259. NearMissKind Kind;
  260. // These two structs share a common prefix, so we can safely rely on the fact
  261. // that they overlap in the union.
  262. struct MissedOpInfo {
  263. unsigned Class;
  264. unsigned Opcode;
  265. unsigned Error;
  266. unsigned Index;
  267. };
  268. struct TooFewOperandsInfo {
  269. unsigned Class;
  270. unsigned Opcode;
  271. };
  272. union {
  273. FeatureBitset Features;
  274. unsigned PredicateError;
  275. MissedOpInfo MissedOperand;
  276. TooFewOperandsInfo TooFewOperands;
  277. };
  278. NearMissInfo() : Kind(NoNearMiss) {}
  279. };
  280. /// MCTargetAsmParser - Generic interface to target specific assembly parsers.
  281. class MCTargetAsmParser : public MCAsmParserExtension {
  282. public:
  283. enum MatchResultTy {
  284. Match_InvalidOperand,
  285. Match_InvalidTiedOperand,
  286. Match_MissingFeature,
  287. Match_MnemonicFail,
  288. Match_Success,
  289. Match_NearMisses,
  290. FIRST_TARGET_MATCH_RESULT_TY
  291. };
  292. protected: // Can only create subclasses.
  293. MCTargetAsmParser(MCTargetOptions const &, const MCSubtargetInfo &STI,
  294. const MCInstrInfo &MII);
  295. /// Create a copy of STI and return a non-const reference to it.
  296. MCSubtargetInfo &copySTI();
  297. /// AvailableFeatures - The current set of available features.
  298. FeatureBitset AvailableFeatures;
  299. /// ParsingMSInlineAsm - Are we parsing ms-style inline assembly?
  300. bool ParsingMSInlineAsm = false;
  301. /// SemaCallback - The Sema callback implementation. Must be set when parsing
  302. /// ms-style inline assembly.
  303. MCAsmParserSemaCallback *SemaCallback = nullptr;
  304. /// Set of options which affects instrumentation of inline assembly.
  305. MCTargetOptions MCOptions;
  306. /// Current STI.
  307. const MCSubtargetInfo *STI;
  308. const MCInstrInfo &MII;
  309. public:
  310. MCTargetAsmParser(const MCTargetAsmParser &) = delete;
  311. MCTargetAsmParser &operator=(const MCTargetAsmParser &) = delete;
  312. ~MCTargetAsmParser() override;
  313. const MCSubtargetInfo &getSTI() const;
  314. const FeatureBitset& getAvailableFeatures() const {
  315. return AvailableFeatures;
  316. }
  317. void setAvailableFeatures(const FeatureBitset& Value) {
  318. AvailableFeatures = Value;
  319. }
  320. bool isParsingMSInlineAsm () { return ParsingMSInlineAsm; }
  321. void setParsingMSInlineAsm (bool Value) { ParsingMSInlineAsm = Value; }
  322. MCTargetOptions getTargetOptions() const { return MCOptions; }
  323. void setSemaCallback(MCAsmParserSemaCallback *Callback) {
  324. SemaCallback = Callback;
  325. }
  326. // Target-specific parsing of expression.
  327. virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
  328. return getParser().parsePrimaryExpr(Res, EndLoc, nullptr);
  329. }
  330. virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
  331. SMLoc &EndLoc) = 0;
  332. /// tryParseRegister - parse one register if possible
  333. ///
  334. /// Check whether a register specification can be parsed at the current
  335. /// location, without failing the entire parse if it can't. Must not consume
  336. /// tokens if the parse fails.
  337. virtual OperandMatchResultTy
  338. tryParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) = 0;
  339. /// ParseInstruction - Parse one assembly instruction.
  340. ///
  341. /// The parser is positioned following the instruction name. The target
  342. /// specific instruction parser should parse the entire instruction and
  343. /// construct the appropriate MCInst, or emit an error. On success, the entire
  344. /// line should be parsed up to and including the end-of-statement token. On
  345. /// failure, the parser is not required to read to the end of the line.
  346. //
  347. /// \param Name - The instruction name.
  348. /// \param NameLoc - The source location of the name.
  349. /// \param Operands [out] - The list of parsed operands, this returns
  350. /// ownership of them to the caller.
  351. /// \return True on failure.
  352. virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
  353. SMLoc NameLoc, OperandVector &Operands) = 0;
  354. virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
  355. AsmToken Token, OperandVector &Operands) {
  356. return ParseInstruction(Info, Name, Token.getLoc(), Operands);
  357. }
  358. /// ParseDirective - Parse a target specific assembler directive
  359. ///
  360. /// The parser is positioned following the directive name. The target
  361. /// specific directive parser should parse the entire directive doing or
  362. /// recording any target specific work, or return true and do nothing if the
  363. /// directive is not target specific. If the directive is specific for
  364. /// the target, the entire line is parsed up to and including the
  365. /// end-of-statement token and false is returned.
  366. ///
  367. /// \param DirectiveID - the identifier token of the directive.
  368. virtual bool ParseDirective(AsmToken DirectiveID) = 0;
  369. /// MatchAndEmitInstruction - Recognize a series of operands of a parsed
  370. /// instruction as an actual MCInst and emit it to the specified MCStreamer.
  371. /// This returns false on success and returns true on failure to match.
  372. ///
  373. /// On failure, the target parser is responsible for emitting a diagnostic
  374. /// explaining the match failure.
  375. virtual bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
  376. OperandVector &Operands, MCStreamer &Out,
  377. uint64_t &ErrorInfo,
  378. bool MatchingInlineAsm) = 0;
  379. /// Allows targets to let registers opt out of clobber lists.
  380. virtual bool OmitRegisterFromClobberLists(unsigned RegNo) { return false; }
  381. /// Allow a target to add special case operand matching for things that
  382. /// tblgen doesn't/can't handle effectively. For example, literal
  383. /// immediates on ARM. TableGen expects a token operand, but the parser
  384. /// will recognize them as immediates.
  385. virtual unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
  386. unsigned Kind) {
  387. return Match_InvalidOperand;
  388. }
  389. /// Validate the instruction match against any complex target predicates
  390. /// before rendering any operands to it.
  391. virtual unsigned
  392. checkEarlyTargetMatchPredicate(MCInst &Inst, const OperandVector &Operands) {
  393. return Match_Success;
  394. }
  395. /// checkTargetMatchPredicate - Validate the instruction match against
  396. /// any complex target predicates not expressible via match classes.
  397. virtual unsigned checkTargetMatchPredicate(MCInst &Inst) {
  398. return Match_Success;
  399. }
  400. virtual void convertToMapAndConstraints(unsigned Kind,
  401. const OperandVector &Operands) = 0;
  402. /// Returns whether two registers are equal and is used by the tied-operands
  403. /// checks in the AsmMatcher. This method can be overridden allow e.g. a
  404. /// sub- or super-register as the tied operand.
  405. virtual bool regsEqual(const MCParsedAsmOperand &Op1,
  406. const MCParsedAsmOperand &Op2) const {
  407. assert(Op1.isReg() && Op2.isReg() && "Operands not all regs");
  408. return Op1.getReg() == Op2.getReg();
  409. }
  410. // Return whether this parser uses assignment statements with equals tokens
  411. virtual bool equalIsAsmAssignment() { return true; };
  412. // Return whether this start of statement identifier is a label
  413. virtual bool isLabel(AsmToken &Token) { return true; };
  414. // Return whether this parser accept star as start of statement
  415. virtual bool starIsStartOfStatement() { return false; };
  416. virtual const MCExpr *applyModifierToExpr(const MCExpr *E,
  417. MCSymbolRefExpr::VariantKind,
  418. MCContext &Ctx) {
  419. return nullptr;
  420. }
  421. // For actions that have to be performed before a label is emitted
  422. virtual void doBeforeLabelEmit(MCSymbol *Symbol) {}
  423. virtual void onLabelParsed(MCSymbol *Symbol) {}
  424. /// Ensure that all previously parsed instructions have been emitted to the
  425. /// output streamer, if the target does not emit them immediately.
  426. virtual void flushPendingInstructions(MCStreamer &Out) {}
  427. virtual const MCExpr *createTargetUnaryExpr(const MCExpr *E,
  428. AsmToken::TokenKind OperatorToken,
  429. MCContext &Ctx) {
  430. return nullptr;
  431. }
  432. // For any initialization at the beginning of parsing.
  433. virtual void onBeginOfFile() {}
  434. // For any checks or cleanups at the end of parsing.
  435. virtual void onEndOfFile() {}
  436. };
  437. } // end namespace llvm
  438. #endif // LLVM_MC_MCPARSER_MCTARGETASMPARSER_H
  439. #ifdef __GNUC__
  440. #pragma GCC diagnostic pop
  441. #endif