xref: /llvm-project/llvm/lib/Target/AVR/AsmParser/AVRAsmParser.cpp (revision 4d48ccfc88ca5af2f1fc419c87d4e7a8b3be9bd7)
1 //===---- AVRAsmParser.cpp - Parse AVR assembly to MCInst instructions ----===//
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 #include "AVR.h"
10 #include "AVRRegisterInfo.h"
11 #include "MCTargetDesc/AVRMCELFStreamer.h"
12 #include "MCTargetDesc/AVRMCExpr.h"
13 #include "MCTargetDesc/AVRMCTargetDesc.h"
14 #include "TargetInfo/AVRTargetInfo.h"
15 
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCInst.h"
20 #include "llvm/MC/MCInstBuilder.h"
21 #include "llvm/MC/MCParser/MCAsmLexer.h"
22 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
23 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCValue.h"
28 #include "llvm/MC/TargetRegistry.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
31 
32 #include <sstream>
33 
34 #define DEBUG_TYPE "avr-asm-parser"
35 
36 using namespace llvm;
37 
38 namespace {
39 /// Parses AVR assembly from a stream.
40 class AVRAsmParser : public MCTargetAsmParser {
41   const MCSubtargetInfo &STI;
42   MCAsmParser &Parser;
43   const MCRegisterInfo *MRI;
44   const std::string GENERATE_STUBS = "gs";
45 
46   enum AVRMatchResultTy {
47     Match_InvalidRegisterOnTiny = FIRST_TARGET_MATCH_RESULT_TY + 1,
48   };
49 
50 #define GET_ASSEMBLER_HEADER
51 #include "AVRGenAsmMatcher.inc"
52 
53   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
54                                OperandVector &Operands, MCStreamer &Out,
55                                uint64_t &ErrorInfo,
56                                bool MatchingInlineAsm) override;
57 
58   bool parseRegister(MCRegister &RegNo, SMLoc &StartLoc,
59                      SMLoc &EndLoc) override;
60   OperandMatchResultTy tryParseRegister(MCRegister &RegNo, SMLoc &StartLoc,
61                                         SMLoc &EndLoc) override;
62 
63   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
64                         SMLoc NameLoc, OperandVector &Operands) override;
65 
66   bool ParseDirective(AsmToken DirectiveID) override;
67 
68   OperandMatchResultTy parseMemriOperand(OperandVector &Operands);
69 
70   bool parseOperand(OperandVector &Operands);
71   int parseRegisterName(unsigned (*matchFn)(StringRef));
72   int parseRegisterName();
73   int parseRegister(bool RestoreOnFailure = false);
74   bool tryParseRegisterOperand(OperandVector &Operands);
75   bool tryParseExpression(OperandVector &Operands);
76   bool tryParseRelocExpression(OperandVector &Operands);
77   void eatComma();
78 
79   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
80                                       unsigned Kind) override;
81 
82   unsigned toDREG(unsigned Reg, unsigned From = AVR::sub_lo) {
83     MCRegisterClass const *Class = &AVRMCRegisterClasses[AVR::DREGSRegClassID];
84     return MRI->getMatchingSuperReg(Reg, From, Class);
85   }
86 
87   bool emit(MCInst &Instruction, SMLoc const &Loc, MCStreamer &Out) const;
88   bool invalidOperand(SMLoc const &Loc, OperandVector const &Operands,
89                       uint64_t const &ErrorInfo);
90   bool missingFeature(SMLoc const &Loc, uint64_t const &ErrorInfo);
91 
92   bool parseLiteralValues(unsigned SizeInBytes, SMLoc L);
93 
94 public:
95   AVRAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
96                const MCInstrInfo &MII, const MCTargetOptions &Options)
97       : MCTargetAsmParser(Options, STI, MII), STI(STI), Parser(Parser) {
98     MCAsmParserExtension::Initialize(Parser);
99     MRI = getContext().getRegisterInfo();
100 
101     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
102   }
103 
104   MCAsmParser &getParser() const { return Parser; }
105   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
106 };
107 
108 /// An parsed AVR assembly operand.
109 class AVROperand : public MCParsedAsmOperand {
110   typedef MCParsedAsmOperand Base;
111   enum KindTy { k_Immediate, k_Register, k_Token, k_Memri } Kind;
112 
113 public:
114   AVROperand(StringRef Tok, SMLoc const &S)
115       : Kind(k_Token), Tok(Tok), Start(S), End(S) {}
116   AVROperand(unsigned Reg, SMLoc const &S, SMLoc const &E)
117       : Kind(k_Register), RegImm({Reg, nullptr}), Start(S), End(E) {}
118   AVROperand(MCExpr const *Imm, SMLoc const &S, SMLoc const &E)
119       : Kind(k_Immediate), RegImm({0, Imm}), Start(S), End(E) {}
120   AVROperand(unsigned Reg, MCExpr const *Imm, SMLoc const &S, SMLoc const &E)
121       : Kind(k_Memri), RegImm({Reg, Imm}), Start(S), End(E) {}
122 
123   struct RegisterImmediate {
124     unsigned Reg;
125     MCExpr const *Imm;
126   };
127   union {
128     StringRef Tok;
129     RegisterImmediate RegImm;
130   };
131 
132   SMLoc Start, End;
133 
134 public:
135   void addRegOperands(MCInst &Inst, unsigned N) const {
136     assert(Kind == k_Register && "Unexpected operand kind");
137     assert(N == 1 && "Invalid number of operands!");
138 
139     Inst.addOperand(MCOperand::createReg(getReg()));
140   }
141 
142   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
143     // Add as immediate when possible
144     if (!Expr)
145       Inst.addOperand(MCOperand::createImm(0));
146     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
147       Inst.addOperand(MCOperand::createImm(CE->getValue()));
148     else
149       Inst.addOperand(MCOperand::createExpr(Expr));
150   }
151 
152   void addImmOperands(MCInst &Inst, unsigned N) const {
153     assert(Kind == k_Immediate && "Unexpected operand kind");
154     assert(N == 1 && "Invalid number of operands!");
155 
156     const MCExpr *Expr = getImm();
157     addExpr(Inst, Expr);
158   }
159 
160   /// Adds the contained reg+imm operand to an instruction.
161   void addMemriOperands(MCInst &Inst, unsigned N) const {
162     assert(Kind == k_Memri && "Unexpected operand kind");
163     assert(N == 2 && "Invalid number of operands");
164 
165     Inst.addOperand(MCOperand::createReg(getReg()));
166     addExpr(Inst, getImm());
167   }
168 
169   void addImmCom8Operands(MCInst &Inst, unsigned N) const {
170     assert(N == 1 && "Invalid number of operands!");
171     // The operand is actually a imm8, but we have its bitwise
172     // negation in the assembly source, so twiddle it here.
173     const auto *CE = cast<MCConstantExpr>(getImm());
174     Inst.addOperand(MCOperand::createImm(~(uint8_t)CE->getValue()));
175   }
176 
177   bool isImmCom8() const {
178     if (!isImm())
179       return false;
180     const auto *CE = dyn_cast<MCConstantExpr>(getImm());
181     if (!CE)
182       return false;
183     int64_t Value = CE->getValue();
184     return isUInt<8>(Value);
185   }
186 
187   bool isReg() const override { return Kind == k_Register; }
188   bool isImm() const override { return Kind == k_Immediate; }
189   bool isToken() const override { return Kind == k_Token; }
190   bool isMem() const override { return Kind == k_Memri; }
191   bool isMemri() const { return Kind == k_Memri; }
192 
193   StringRef getToken() const {
194     assert(Kind == k_Token && "Invalid access!");
195     return Tok;
196   }
197 
198   unsigned getReg() const override {
199     assert((Kind == k_Register || Kind == k_Memri) && "Invalid access!");
200 
201     return RegImm.Reg;
202   }
203 
204   const MCExpr *getImm() const {
205     assert((Kind == k_Immediate || Kind == k_Memri) && "Invalid access!");
206     return RegImm.Imm;
207   }
208 
209   static std::unique_ptr<AVROperand> CreateToken(StringRef Str, SMLoc S) {
210     return std::make_unique<AVROperand>(Str, S);
211   }
212 
213   static std::unique_ptr<AVROperand> CreateReg(unsigned RegNum, SMLoc S,
214                                                SMLoc E) {
215     return std::make_unique<AVROperand>(RegNum, S, E);
216   }
217 
218   static std::unique_ptr<AVROperand> CreateImm(const MCExpr *Val, SMLoc S,
219                                                SMLoc E) {
220     return std::make_unique<AVROperand>(Val, S, E);
221   }
222 
223   static std::unique_ptr<AVROperand>
224   CreateMemri(unsigned RegNum, const MCExpr *Val, SMLoc S, SMLoc E) {
225     return std::make_unique<AVROperand>(RegNum, Val, S, E);
226   }
227 
228   void makeToken(StringRef Token) {
229     Kind = k_Token;
230     Tok = Token;
231   }
232 
233   void makeReg(unsigned RegNo) {
234     Kind = k_Register;
235     RegImm = {RegNo, nullptr};
236   }
237 
238   void makeImm(MCExpr const *Ex) {
239     Kind = k_Immediate;
240     RegImm = {0, Ex};
241   }
242 
243   void makeMemri(unsigned RegNo, MCExpr const *Imm) {
244     Kind = k_Memri;
245     RegImm = {RegNo, Imm};
246   }
247 
248   SMLoc getStartLoc() const override { return Start; }
249   SMLoc getEndLoc() const override { return End; }
250 
251   void print(raw_ostream &O) const override {
252     switch (Kind) {
253     case k_Token:
254       O << "Token: \"" << getToken() << "\"";
255       break;
256     case k_Register:
257       O << "Register: " << getReg();
258       break;
259     case k_Immediate:
260       O << "Immediate: \"" << *getImm() << "\"";
261       break;
262     case k_Memri: {
263       // only manually print the size for non-negative values,
264       // as the sign is inserted automatically.
265       O << "Memri: \"" << getReg() << '+' << *getImm() << "\"";
266       break;
267     }
268     }
269     O << "\n";
270   }
271 };
272 
273 } // end anonymous namespace.
274 
275 // Auto-generated Match Functions
276 
277 /// Maps from the set of all register names to a register number.
278 /// \note Generated by TableGen.
279 static unsigned MatchRegisterName(StringRef Name);
280 
281 /// Maps from the set of all alternative registernames to a register number.
282 /// \note Generated by TableGen.
283 static unsigned MatchRegisterAltName(StringRef Name);
284 
285 bool AVRAsmParser::invalidOperand(SMLoc const &Loc,
286                                   OperandVector const &Operands,
287                                   uint64_t const &ErrorInfo) {
288   SMLoc ErrorLoc = Loc;
289   char const *Diag = nullptr;
290 
291   if (ErrorInfo != ~0U) {
292     if (ErrorInfo >= Operands.size()) {
293       Diag = "too few operands for instruction.";
294     } else {
295       AVROperand const &Op = (AVROperand const &)*Operands[ErrorInfo];
296 
297       // TODO: See if we can do a better error than just "invalid ...".
298       if (Op.getStartLoc() != SMLoc()) {
299         ErrorLoc = Op.getStartLoc();
300       }
301     }
302   }
303 
304   if (!Diag) {
305     Diag = "invalid operand for instruction";
306   }
307 
308   return Error(ErrorLoc, Diag);
309 }
310 
311 bool AVRAsmParser::missingFeature(llvm::SMLoc const &Loc,
312                                   uint64_t const &ErrorInfo) {
313   return Error(Loc, "instruction requires a CPU feature not currently enabled");
314 }
315 
316 bool AVRAsmParser::emit(MCInst &Inst, SMLoc const &Loc, MCStreamer &Out) const {
317   Inst.setLoc(Loc);
318   Out.emitInstruction(Inst, STI);
319 
320   return false;
321 }
322 
323 bool AVRAsmParser::MatchAndEmitInstruction(SMLoc Loc, unsigned &Opcode,
324                                            OperandVector &Operands,
325                                            MCStreamer &Out, uint64_t &ErrorInfo,
326                                            bool MatchingInlineAsm) {
327   MCInst Inst;
328   unsigned MatchResult =
329       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
330 
331   switch (MatchResult) {
332   case Match_Success:
333     return emit(Inst, Loc, Out);
334   case Match_MissingFeature:
335     return missingFeature(Loc, ErrorInfo);
336   case Match_InvalidOperand:
337     return invalidOperand(Loc, Operands, ErrorInfo);
338   case Match_MnemonicFail:
339     return Error(Loc, "invalid instruction");
340   case Match_InvalidRegisterOnTiny:
341     return Error(Loc, "invalid register on avrtiny");
342   default:
343     return true;
344   }
345 }
346 
347 /// Parses a register name using a given matching function.
348 /// Checks for lowercase or uppercase if necessary.
349 int AVRAsmParser::parseRegisterName(unsigned (*matchFn)(StringRef)) {
350   StringRef Name = Parser.getTok().getString();
351 
352   int RegNum = matchFn(Name);
353 
354   // GCC supports case insensitive register names. Some of the AVR registers
355   // are all lower case, some are all upper case but non are mixed. We prefer
356   // to use the original names in the register definitions. That is why we
357   // have to test both upper and lower case here.
358   if (RegNum == AVR::NoRegister) {
359     RegNum = matchFn(Name.lower());
360   }
361   if (RegNum == AVR::NoRegister) {
362     RegNum = matchFn(Name.upper());
363   }
364 
365   return RegNum;
366 }
367 
368 int AVRAsmParser::parseRegisterName() {
369   int RegNum = parseRegisterName(&MatchRegisterName);
370 
371   if (RegNum == AVR::NoRegister)
372     RegNum = parseRegisterName(&MatchRegisterAltName);
373 
374   return RegNum;
375 }
376 
377 int AVRAsmParser::parseRegister(bool RestoreOnFailure) {
378   int RegNum = AVR::NoRegister;
379 
380   if (Parser.getTok().is(AsmToken::Identifier)) {
381     // Check for register pair syntax
382     if (Parser.getLexer().peekTok().is(AsmToken::Colon)) {
383       AsmToken HighTok = Parser.getTok();
384       Parser.Lex();
385       AsmToken ColonTok = Parser.getTok();
386       Parser.Lex(); // Eat high (odd) register and colon
387 
388       if (Parser.getTok().is(AsmToken::Identifier)) {
389         // Convert lower (even) register to DREG
390         RegNum = toDREG(parseRegisterName());
391       }
392       if (RegNum == AVR::NoRegister && RestoreOnFailure) {
393         getLexer().UnLex(std::move(ColonTok));
394         getLexer().UnLex(std::move(HighTok));
395       }
396     } else {
397       RegNum = parseRegisterName();
398     }
399   }
400   return RegNum;
401 }
402 
403 bool AVRAsmParser::tryParseRegisterOperand(OperandVector &Operands) {
404   int RegNo = parseRegister();
405 
406   if (RegNo == AVR::NoRegister)
407     return true;
408 
409   // Reject R0~R15 on avrtiny.
410   if (AVR::R0 <= RegNo && RegNo <= AVR::R15 &&
411       STI.hasFeature(AVR::FeatureTinyEncoding))
412     return Error(Parser.getTok().getLoc(), "invalid register on avrtiny");
413 
414   AsmToken const &T = Parser.getTok();
415   Operands.push_back(AVROperand::CreateReg(RegNo, T.getLoc(), T.getEndLoc()));
416   Parser.Lex(); // Eat register token.
417 
418   return false;
419 }
420 
421 bool AVRAsmParser::tryParseExpression(OperandVector &Operands) {
422   SMLoc S = Parser.getTok().getLoc();
423 
424   if (!tryParseRelocExpression(Operands))
425     return false;
426 
427   if ((Parser.getTok().getKind() == AsmToken::Plus ||
428        Parser.getTok().getKind() == AsmToken::Minus) &&
429       Parser.getLexer().peekTok().getKind() == AsmToken::Identifier) {
430     // Don't handle this case - it should be split into two
431     // separate tokens.
432     return true;
433   }
434 
435   // Parse (potentially inner) expression
436   MCExpr const *Expression;
437   if (getParser().parseExpression(Expression))
438     return true;
439 
440   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
441   Operands.push_back(AVROperand::CreateImm(Expression, S, E));
442   return false;
443 }
444 
445 bool AVRAsmParser::tryParseRelocExpression(OperandVector &Operands) {
446   bool isNegated = false;
447   AVRMCExpr::VariantKind ModifierKind = AVRMCExpr::VK_AVR_None;
448 
449   SMLoc S = Parser.getTok().getLoc();
450 
451   // Check for sign
452   AsmToken tokens[2];
453   size_t ReadCount = Parser.getLexer().peekTokens(tokens);
454 
455   if (ReadCount == 2) {
456     if ((tokens[0].getKind() == AsmToken::Identifier &&
457          tokens[1].getKind() == AsmToken::LParen) ||
458         (tokens[0].getKind() == AsmToken::LParen &&
459          tokens[1].getKind() == AsmToken::Minus)) {
460 
461       AsmToken::TokenKind CurTok = Parser.getLexer().getKind();
462       if (CurTok == AsmToken::Minus || tokens[1].getKind() == AsmToken::Minus) {
463         isNegated = true;
464       } else {
465         assert(CurTok == AsmToken::Plus);
466         isNegated = false;
467       }
468 
469       // Eat the sign
470       if (CurTok == AsmToken::Minus || CurTok == AsmToken::Plus)
471         Parser.Lex();
472     }
473   }
474 
475   // Check if we have a target specific modifier (lo8, hi8, &c)
476   if (Parser.getTok().getKind() != AsmToken::Identifier ||
477       Parser.getLexer().peekTok().getKind() != AsmToken::LParen) {
478     // Not a reloc expr
479     return true;
480   }
481   StringRef ModifierName = Parser.getTok().getString();
482   ModifierKind = AVRMCExpr::getKindByName(ModifierName);
483 
484   if (ModifierKind != AVRMCExpr::VK_AVR_None) {
485     Parser.Lex();
486     Parser.Lex(); // Eat modifier name and parenthesis
487     if (Parser.getTok().getString() == GENERATE_STUBS &&
488         Parser.getTok().getKind() == AsmToken::Identifier) {
489       std::string GSModName = ModifierName.str() + "_" + GENERATE_STUBS;
490       ModifierKind = AVRMCExpr::getKindByName(GSModName);
491       if (ModifierKind != AVRMCExpr::VK_AVR_None)
492         Parser.Lex(); // Eat gs modifier name
493     }
494   } else {
495     return Error(Parser.getTok().getLoc(), "unknown modifier");
496   }
497 
498   if (tokens[1].getKind() == AsmToken::Minus ||
499       tokens[1].getKind() == AsmToken::Plus) {
500     Parser.Lex();
501     assert(Parser.getTok().getKind() == AsmToken::LParen);
502     Parser.Lex(); // Eat the sign and parenthesis
503   }
504 
505   MCExpr const *InnerExpression;
506   if (getParser().parseExpression(InnerExpression))
507     return true;
508 
509   if (tokens[1].getKind() == AsmToken::Minus ||
510       tokens[1].getKind() == AsmToken::Plus) {
511     assert(Parser.getTok().getKind() == AsmToken::RParen);
512     Parser.Lex(); // Eat closing parenthesis
513   }
514 
515   // If we have a modifier wrap the inner expression
516   assert(Parser.getTok().getKind() == AsmToken::RParen);
517   Parser.Lex(); // Eat closing parenthesis
518 
519   MCExpr const *Expression =
520       AVRMCExpr::create(ModifierKind, InnerExpression, isNegated, getContext());
521 
522   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
523   Operands.push_back(AVROperand::CreateImm(Expression, S, E));
524 
525   return false;
526 }
527 
528 bool AVRAsmParser::parseOperand(OperandVector &Operands) {
529   LLVM_DEBUG(dbgs() << "parseOperand\n");
530 
531   switch (getLexer().getKind()) {
532   default:
533     return Error(Parser.getTok().getLoc(), "unexpected token in operand");
534 
535   case AsmToken::Identifier:
536     // Try to parse a register, if it fails,
537     // fall through to the next case.
538     if (!tryParseRegisterOperand(Operands)) {
539       return false;
540     }
541     [[fallthrough]];
542   case AsmToken::LParen:
543   case AsmToken::Integer:
544   case AsmToken::Dot:
545     return tryParseExpression(Operands);
546   case AsmToken::Plus:
547   case AsmToken::Minus: {
548     // If the sign preceeds a number, parse the number,
549     // otherwise treat the sign a an independent token.
550     switch (getLexer().peekTok().getKind()) {
551     case AsmToken::Integer:
552     case AsmToken::BigNum:
553     case AsmToken::Identifier:
554     case AsmToken::Real:
555       if (!tryParseExpression(Operands))
556         return false;
557       break;
558     default:
559       break;
560     }
561     // Treat the token as an independent token.
562     Operands.push_back(AVROperand::CreateToken(Parser.getTok().getString(),
563                                                Parser.getTok().getLoc()));
564     Parser.Lex(); // Eat the token.
565     return false;
566   }
567   }
568 
569   // Could not parse operand
570   return true;
571 }
572 
573 OperandMatchResultTy AVRAsmParser::parseMemriOperand(OperandVector &Operands) {
574   LLVM_DEBUG(dbgs() << "parseMemriOperand()\n");
575 
576   SMLoc E, S;
577   MCExpr const *Expression;
578   int RegNo;
579 
580   // Parse register.
581   {
582     RegNo = parseRegister();
583 
584     if (RegNo == AVR::NoRegister)
585       return MatchOperand_ParseFail;
586 
587     S = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
588     Parser.Lex(); // Eat register token.
589   }
590 
591   // Parse immediate;
592   {
593     if (getParser().parseExpression(Expression))
594       return MatchOperand_ParseFail;
595 
596     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
597   }
598 
599   Operands.push_back(AVROperand::CreateMemri(RegNo, Expression, S, E));
600 
601   return MatchOperand_Success;
602 }
603 
604 bool AVRAsmParser::parseRegister(MCRegister &RegNo, SMLoc &StartLoc,
605                                  SMLoc &EndLoc) {
606   StartLoc = Parser.getTok().getLoc();
607   RegNo = parseRegister(/*RestoreOnFailure=*/false);
608   EndLoc = Parser.getTok().getLoc();
609 
610   return (RegNo == AVR::NoRegister);
611 }
612 
613 OperandMatchResultTy AVRAsmParser::tryParseRegister(MCRegister &RegNo,
614                                                     SMLoc &StartLoc,
615                                                     SMLoc &EndLoc) {
616   StartLoc = Parser.getTok().getLoc();
617   RegNo = parseRegister(/*RestoreOnFailure=*/true);
618   EndLoc = Parser.getTok().getLoc();
619 
620   if (RegNo == AVR::NoRegister)
621     return MatchOperand_NoMatch;
622   return MatchOperand_Success;
623 }
624 
625 void AVRAsmParser::eatComma() {
626   if (getLexer().is(AsmToken::Comma)) {
627     Parser.Lex();
628   } else {
629     // GCC allows commas to be omitted.
630   }
631 }
632 
633 bool AVRAsmParser::ParseInstruction(ParseInstructionInfo &Info,
634                                     StringRef Mnemonic, SMLoc NameLoc,
635                                     OperandVector &Operands) {
636   Operands.push_back(AVROperand::CreateToken(Mnemonic, NameLoc));
637 
638   bool first = true;
639   while (getLexer().isNot(AsmToken::EndOfStatement)) {
640     if (!first)
641       eatComma();
642 
643     first = false;
644 
645     auto MatchResult = MatchOperandParserImpl(Operands, Mnemonic);
646 
647     if (MatchResult == MatchOperand_Success) {
648       continue;
649     }
650 
651     if (MatchResult == MatchOperand_ParseFail) {
652       SMLoc Loc = getLexer().getLoc();
653       Parser.eatToEndOfStatement();
654 
655       return Error(Loc, "failed to parse register and immediate pair");
656     }
657 
658     if (parseOperand(Operands)) {
659       SMLoc Loc = getLexer().getLoc();
660       Parser.eatToEndOfStatement();
661       return Error(Loc, "unexpected token in argument list");
662     }
663   }
664   Parser.Lex(); // Consume the EndOfStatement
665   return false;
666 }
667 
668 bool AVRAsmParser::ParseDirective(llvm::AsmToken DirectiveID) {
669   StringRef IDVal = DirectiveID.getIdentifier();
670   if (IDVal.lower() == ".long") {
671     parseLiteralValues(SIZE_LONG, DirectiveID.getLoc());
672   } else if (IDVal.lower() == ".word" || IDVal.lower() == ".short") {
673     parseLiteralValues(SIZE_WORD, DirectiveID.getLoc());
674   } else if (IDVal.lower() == ".byte") {
675     parseLiteralValues(1, DirectiveID.getLoc());
676   }
677   return true;
678 }
679 
680 bool AVRAsmParser::parseLiteralValues(unsigned SizeInBytes, SMLoc L) {
681   MCAsmParser &Parser = getParser();
682   AVRMCELFStreamer &AVRStreamer =
683       static_cast<AVRMCELFStreamer &>(Parser.getStreamer());
684   AsmToken Tokens[2];
685   size_t ReadCount = Parser.getLexer().peekTokens(Tokens);
686   if (ReadCount == 2 && Parser.getTok().getKind() == AsmToken::Identifier &&
687       Tokens[0].getKind() == AsmToken::Minus &&
688       Tokens[1].getKind() == AsmToken::Identifier) {
689     MCSymbol *Symbol = getContext().getOrCreateSymbol(".text");
690     AVRStreamer.emitValueForModiferKind(Symbol, SizeInBytes, L,
691                                         AVRMCExpr::VK_AVR_None);
692     return false;
693   }
694 
695   if (Parser.getTok().getKind() == AsmToken::Identifier &&
696       Parser.getLexer().peekTok().getKind() == AsmToken::LParen) {
697     StringRef ModifierName = Parser.getTok().getString();
698     AVRMCExpr::VariantKind ModifierKind =
699         AVRMCExpr::getKindByName(ModifierName);
700     if (ModifierKind != AVRMCExpr::VK_AVR_None) {
701       Parser.Lex();
702       Parser.Lex(); // Eat the modifier and parenthesis
703     } else {
704       return Error(Parser.getTok().getLoc(), "unknown modifier");
705     }
706     MCSymbol *Symbol =
707         getContext().getOrCreateSymbol(Parser.getTok().getString());
708     AVRStreamer.emitValueForModiferKind(Symbol, SizeInBytes, L, ModifierKind);
709     return false;
710   }
711 
712   auto parseOne = [&]() -> bool {
713     const MCExpr *Value;
714     if (Parser.parseExpression(Value))
715       return true;
716     Parser.getStreamer().emitValue(Value, SizeInBytes, L);
717     return false;
718   };
719   return (parseMany(parseOne));
720 }
721 
722 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAVRAsmParser() {
723   RegisterMCAsmParser<AVRAsmParser> X(getTheAVRTarget());
724 }
725 
726 #define GET_REGISTER_MATCHER
727 #define GET_MATCHER_IMPLEMENTATION
728 #include "AVRGenAsmMatcher.inc"
729 
730 // Uses enums defined in AVRGenAsmMatcher.inc
731 unsigned AVRAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
732                                                   unsigned ExpectedKind) {
733   AVROperand &Op = static_cast<AVROperand &>(AsmOp);
734   MatchClassKind Expected = static_cast<MatchClassKind>(ExpectedKind);
735 
736   // If need be, GCC converts bare numbers to register names
737   // It's ugly, but GCC supports it.
738   if (Op.isImm()) {
739     if (MCConstantExpr const *Const = dyn_cast<MCConstantExpr>(Op.getImm())) {
740       int64_t RegNum = Const->getValue();
741 
742       // Reject R0~R15 on avrtiny.
743       if (0 <= RegNum && RegNum <= 15 &&
744           STI.hasFeature(AVR::FeatureTinyEncoding))
745         return Match_InvalidRegisterOnTiny;
746 
747       std::ostringstream RegName;
748       RegName << "r" << RegNum;
749       RegNum = MatchRegisterName(RegName.str());
750       if (RegNum != AVR::NoRegister) {
751         Op.makeReg(RegNum);
752         if (validateOperandClass(Op, Expected) == Match_Success) {
753           return Match_Success;
754         }
755       }
756       // Let the other quirks try their magic.
757     }
758   }
759 
760   if (Op.isReg()) {
761     // If the instruction uses a register pair but we got a single, lower
762     // register we perform a "class cast".
763     if (isSubclass(Expected, MCK_DREGS)) {
764       unsigned correspondingDREG = toDREG(Op.getReg());
765 
766       if (correspondingDREG != AVR::NoRegister) {
767         Op.makeReg(correspondingDREG);
768         return validateOperandClass(Op, Expected);
769       }
770     }
771   }
772   return Match_InvalidOperand;
773 }
774