1 //===-- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 #include "llvm/ADT/SmallVector.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAsmLexer.h"
14 #include "llvm/MC/MCAsmParser.h"
15 #include "llvm/MC/MCStreamer.h"
16 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCInst.h"
18 #include "llvm/Support/Compiler.h"
19 #include "llvm/Support/SourceMgr.h"
20 #include "llvm/Target/TargetRegistry.h"
21 #include "llvm/Target/TargetAsmParser.h"
27 // The shift types for register controlled shifts in arm memory addressing
36 class ARMAsmParser : public TargetAsmParser {
40 MCAsmParser &getParser() const { return Parser; }
42 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
44 void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
46 bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
48 bool MaybeParseRegister(ARMOperand &Op, bool ParseWriteBack);
50 bool ParseRegisterList(ARMOperand &Op);
52 bool ParseMemory(ARMOperand &Op);
54 bool ParseMemoryOffsetReg(bool &Negative,
55 bool &OffsetRegShifted,
56 enum ShiftType &ShiftType,
57 const MCExpr *&ShiftAmount,
58 const MCExpr *&Offset,
62 bool ParseShift(enum ShiftType &St, const MCExpr *&ShiftAmount);
64 bool ParseOperand(ARMOperand &Op);
66 bool ParseDirectiveWord(unsigned Size, SMLoc L);
68 bool ParseDirectiveThumb(SMLoc L);
70 bool ParseDirectiveThumbFunc(SMLoc L);
72 bool ParseDirectiveCode(SMLoc L);
74 bool ParseDirectiveSyntax(SMLoc L);
76 // TODO - For now hacked versions of the next two are in here in this file to
77 // allow some parser testing until the table gen versions are implemented.
79 /// @name Auto-generated Match Functions
81 bool MatchInstruction(SmallVectorImpl<ARMOperand> &Operands,
84 /// MatchRegisterName - Match the given string to a register name and return
85 /// its register number, or -1 if there is no match. To allow return values
86 /// to be used directly in register lists, arm registers have values between
88 int MatchRegisterName(const StringRef &Name);
94 ARMAsmParser(const Target &T, MCAsmParser &_Parser)
95 : TargetAsmParser(T), Parser(_Parser) {}
97 virtual bool ParseInstruction(const StringRef &Name, MCInst &Inst);
99 virtual bool ParseDirective(AsmToken DirectiveID);
102 /// ARMOperand - Instances of this class represent a parsed ARM machine
128 // This is for all forms of ARM address expressions
131 unsigned OffsetRegNum; // used when OffsetIsReg is true
132 const MCExpr *Offset; // used when OffsetIsReg is false
133 const MCExpr *ShiftAmount; // used when OffsetRegShifted is true
134 enum ShiftType ShiftType; // used when OffsetRegShifted is true
136 OffsetRegShifted : 1, // only used when OffsetIsReg is true
140 Negative : 1, // only used when OffsetIsReg is true
146 StringRef getToken() const {
147 assert(Kind == Token && "Invalid access!");
148 return StringRef(Tok.Data, Tok.Length);
151 unsigned getReg() const {
152 assert(Kind == Register && "Invalid access!");
156 const MCExpr *getImm() const {
157 assert(Kind == Immediate && "Invalid access!");
161 bool isToken() const {return Kind == Token; }
163 bool isReg() const { return Kind == Register; }
165 void addRegOperands(MCInst &Inst, unsigned N) const {
166 assert(N == 1 && "Invalid number of operands!");
167 Inst.addOperand(MCOperand::CreateReg(getReg()));
170 static ARMOperand CreateToken(StringRef Str) {
173 Res.Tok.Data = Str.data();
174 Res.Tok.Length = Str.size();
178 static ARMOperand CreateReg(unsigned RegNum, bool Writeback) {
181 Res.Reg.RegNum = RegNum;
182 Res.Reg.Writeback = Writeback;
186 static ARMOperand CreateImm(const MCExpr *Val) {
188 Res.Kind = Immediate;
193 static ARMOperand CreateMem(unsigned BaseRegNum, bool OffsetIsReg,
194 const MCExpr *Offset, unsigned OffsetRegNum,
195 bool OffsetRegShifted, enum ShiftType ShiftType,
196 const MCExpr *ShiftAmount, bool Preindexed,
197 bool Postindexed, bool Negative, bool Writeback) {
200 Res.Mem.BaseRegNum = BaseRegNum;
201 Res.Mem.OffsetIsReg = OffsetIsReg;
202 Res.Mem.Offset = Offset;
203 Res.Mem.OffsetRegNum = OffsetRegNum;
204 Res.Mem.OffsetRegShifted = OffsetRegShifted;
205 Res.Mem.ShiftType = ShiftType;
206 Res.Mem.ShiftAmount = ShiftAmount;
207 Res.Mem.Preindexed = Preindexed;
208 Res.Mem.Postindexed = Postindexed;
209 Res.Mem.Negative = Negative;
210 Res.Mem.Writeback = Writeback;
215 } // end anonymous namespace.
217 /// Try to parse a register name. The token must be an Identifier when called,
218 /// and if it is a register name a Reg operand is created, the token is eaten
219 /// and false is returned. Else true is returned and no token is eaten.
220 /// TODO this is likely to change to allow different register types and or to
221 /// parse for a specific register type.
222 bool ARMAsmParser::MaybeParseRegister(ARMOperand &Op, bool ParseWriteBack) {
223 const AsmToken &Tok = getLexer().getTok();
224 assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
226 // FIXME: Validate register for the current architecture; we have to do
227 // validation later, so maybe there is no need for this here.
230 RegNum = MatchRegisterName(Tok.getString());
233 getLexer().Lex(); // Eat identifier token.
235 bool Writeback = false;
236 if (ParseWriteBack) {
237 const AsmToken &ExclaimTok = getLexer().getTok();
238 if (ExclaimTok.is(AsmToken::Exclaim)) {
240 getLexer().Lex(); // Eat exclaim token
244 Op = ARMOperand::CreateReg(RegNum, Writeback);
249 /// Parse a register list, return false if successful else return true or an
250 /// error. The first token must be a '{' when called.
251 bool ARMAsmParser::ParseRegisterList(ARMOperand &Op) {
252 assert(getLexer().getTok().is(AsmToken::LCurly) &&
253 "Token is not an Left Curly Brace");
254 getLexer().Lex(); // Eat left curly brace token.
256 const AsmToken &RegTok = getLexer().getTok();
257 SMLoc RegLoc = RegTok.getLoc();
258 if (RegTok.isNot(AsmToken::Identifier))
259 return Error(RegLoc, "register expected");
260 int RegNum = MatchRegisterName(RegTok.getString());
262 return Error(RegLoc, "register expected");
263 getLexer().Lex(); // Eat identifier token.
264 unsigned RegList = 1 << RegNum;
266 int HighRegNum = RegNum;
267 // TODO ranges like "{Rn-Rm}"
268 while (getLexer().getTok().is(AsmToken::Comma)) {
269 getLexer().Lex(); // Eat comma token.
271 const AsmToken &RegTok = getLexer().getTok();
272 SMLoc RegLoc = RegTok.getLoc();
273 if (RegTok.isNot(AsmToken::Identifier))
274 return Error(RegLoc, "register expected");
275 int RegNum = MatchRegisterName(RegTok.getString());
277 return Error(RegLoc, "register expected");
279 if (RegList & (1 << RegNum))
280 Warning(RegLoc, "register duplicated in register list");
281 else if (RegNum <= HighRegNum)
282 Warning(RegLoc, "register not in ascending order in register list");
283 RegList |= 1 << RegNum;
286 getLexer().Lex(); // Eat identifier token.
288 const AsmToken &RCurlyTok = getLexer().getTok();
289 if (RCurlyTok.isNot(AsmToken::RCurly))
290 return Error(RCurlyTok.getLoc(), "'}' expected");
291 getLexer().Lex(); // Eat left curly brace token.
296 /// Parse an arm memory expression, return false if successful else return true
297 /// or an error. The first token must be a '[' when called.
298 /// TODO Only preindexing and postindexing addressing are started, unindexed
299 /// with option, etc are still to do.
300 bool ARMAsmParser::ParseMemory(ARMOperand &Op) {
301 assert(getLexer().getTok().is(AsmToken::LBrac) &&
302 "Token is not an Left Bracket");
303 getLexer().Lex(); // Eat left bracket token.
305 const AsmToken &BaseRegTok = getLexer().getTok();
306 if (BaseRegTok.isNot(AsmToken::Identifier))
307 return Error(BaseRegTok.getLoc(), "register expected");
308 if (MaybeParseRegister(Op, false))
309 return Error(BaseRegTok.getLoc(), "register expected");
310 int BaseRegNum = Op.getReg();
312 bool Preindexed = false;
313 bool Postindexed = false;
314 bool OffsetIsReg = false;
315 bool Negative = false;
316 bool Writeback = false;
318 // First look for preindexed address forms, that is after the "[Rn" we now
319 // have to see if the next token is a comma.
320 const AsmToken &Tok = getLexer().getTok();
321 if (Tok.is(AsmToken::Comma)) {
323 getLexer().Lex(); // Eat comma token.
325 bool OffsetRegShifted;
326 enum ShiftType ShiftType;
327 const MCExpr *ShiftAmount;
328 const MCExpr *Offset;
329 if(ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType, ShiftAmount,
330 Offset, OffsetIsReg, OffsetRegNum))
332 const AsmToken &RBracTok = getLexer().getTok();
333 if (RBracTok.isNot(AsmToken::RBrac))
334 return Error(RBracTok.getLoc(), "']' expected");
335 getLexer().Lex(); // Eat right bracket token.
337 const AsmToken &ExclaimTok = getLexer().getTok();
338 if (ExclaimTok.is(AsmToken::Exclaim)) {
340 getLexer().Lex(); // Eat exclaim token
342 Op = ARMOperand::CreateMem(BaseRegNum, OffsetIsReg, Offset, OffsetRegNum,
343 OffsetRegShifted, ShiftType, ShiftAmount,
344 Preindexed, Postindexed, Negative, Writeback);
347 // The "[Rn" we have so far was not followed by a comma.
348 else if (Tok.is(AsmToken::RBrac)) {
349 // This is a post indexing addressing forms, that is a ']' follows after
353 getLexer().Lex(); // Eat right bracket token.
355 int OffsetRegNum = 0;
356 bool OffsetRegShifted = false;
357 enum ShiftType ShiftType;
358 const MCExpr *ShiftAmount;
359 const MCExpr *Offset;
361 const AsmToken &NextTok = getLexer().getTok();
362 if (NextTok.isNot(AsmToken::EndOfStatement)) {
363 if (NextTok.isNot(AsmToken::Comma))
364 return Error(NextTok.getLoc(), "',' expected");
365 getLexer().Lex(); // Eat comma token.
366 if(ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType,
367 ShiftAmount, Offset, OffsetIsReg, OffsetRegNum))
371 Op = ARMOperand::CreateMem(BaseRegNum, OffsetIsReg, Offset, OffsetRegNum,
372 OffsetRegShifted, ShiftType, ShiftAmount,
373 Preindexed, Postindexed, Negative, Writeback);
380 /// Parse the offset of a memory operand after we have seen "[Rn," or "[Rn],"
381 /// we will parse the following (were +/- means that a plus or minus is
386 /// we return false on success or an error otherwise.
387 bool ARMAsmParser::ParseMemoryOffsetReg(bool &Negative,
388 bool &OffsetRegShifted,
389 enum ShiftType &ShiftType,
390 const MCExpr *&ShiftAmount,
391 const MCExpr *&Offset,
396 OffsetRegShifted = false;
399 const AsmToken &NextTok = getLexer().getTok();
400 if (NextTok.is(AsmToken::Plus))
401 getLexer().Lex(); // Eat plus token.
402 else if (NextTok.is(AsmToken::Minus)) {
404 getLexer().Lex(); // Eat minus token
406 // See if there is a register following the "[Rn," or "[Rn]," we have so far.
407 const AsmToken &OffsetRegTok = getLexer().getTok();
408 if (OffsetRegTok.is(AsmToken::Identifier)) {
409 OffsetIsReg = !MaybeParseRegister(Op, false);
411 OffsetRegNum = Op.getReg();
413 // If we parsed a register as the offset then their can be a shift after that
414 if (OffsetRegNum != -1) {
415 // Look for a comma then a shift
416 const AsmToken &Tok = getLexer().getTok();
417 if (Tok.is(AsmToken::Comma)) {
418 getLexer().Lex(); // Eat comma token.
420 const AsmToken &Tok = getLexer().getTok();
421 if (ParseShift(ShiftType, ShiftAmount))
422 return Error(Tok.getLoc(), "shift expected");
423 OffsetRegShifted = true;
426 else { // the "[Rn," or "[Rn,]" we have so far was not followed by "Rm"
427 // Look for #offset following the "[Rn," or "[Rn],"
428 const AsmToken &HashTok = getLexer().getTok();
429 if (HashTok.isNot(AsmToken::Hash))
430 return Error(HashTok.getLoc(), "'#' expected");
431 getLexer().Lex(); // Eat hash token.
433 if (getParser().ParseExpression(Offset))
439 /// ParseShift as one of these two:
440 /// ( lsl | lsr | asr | ror ) , # shift_amount
442 /// and returns true if it parses a shift otherwise it returns false.
443 bool ARMAsmParser::ParseShift(ShiftType &St, const MCExpr *&ShiftAmount) {
444 const AsmToken &Tok = getLexer().getTok();
445 if (Tok.isNot(AsmToken::Identifier))
447 const StringRef &ShiftName = Tok.getString();
448 if (ShiftName == "lsl" || ShiftName == "LSL")
450 else if (ShiftName == "lsr" || ShiftName == "LSR")
452 else if (ShiftName == "asr" || ShiftName == "ASR")
454 else if (ShiftName == "ror" || ShiftName == "ROR")
456 else if (ShiftName == "rrx" || ShiftName == "RRX")
460 getLexer().Lex(); // Eat shift type token.
466 // Otherwise, there must be a '#' and a shift amount.
467 const AsmToken &HashTok = getLexer().getTok();
468 if (HashTok.isNot(AsmToken::Hash))
469 return Error(HashTok.getLoc(), "'#' expected");
470 getLexer().Lex(); // Eat hash token.
472 if (getParser().ParseExpression(ShiftAmount))
478 /// A hack to allow some testing, to be replaced by a real table gen version.
479 int ARMAsmParser::MatchRegisterName(const StringRef &Name) {
480 if (Name == "r0" || Name == "R0")
482 else if (Name == "r1" || Name == "R1")
484 else if (Name == "r2" || Name == "R2")
486 else if (Name == "r3" || Name == "R3")
488 else if (Name == "r3" || Name == "R3")
490 else if (Name == "r4" || Name == "R4")
492 else if (Name == "r5" || Name == "R5")
494 else if (Name == "r6" || Name == "R6")
496 else if (Name == "r7" || Name == "R7")
498 else if (Name == "r8" || Name == "R8")
500 else if (Name == "r9" || Name == "R9")
502 else if (Name == "r10" || Name == "R10")
504 else if (Name == "r11" || Name == "R11" || Name == "fp")
506 else if (Name == "r12" || Name == "R12" || Name == "ip")
508 else if (Name == "r13" || Name == "R13" || Name == "sp")
510 else if (Name == "r14" || Name == "R14" || Name == "lr")
512 else if (Name == "r15" || Name == "R15" || Name == "pc")
517 /// A hack to allow some testing, to be replaced by a real table gen version.
518 bool ARMAsmParser::MatchInstruction(SmallVectorImpl<ARMOperand> &Operands,
520 struct ARMOperand Op0 = Operands[0];
521 assert(Op0.Kind == ARMOperand::Token && "First operand not a Token");
522 const StringRef &Mnemonic = Op0.getToken();
523 if (Mnemonic == "add" ||
524 Mnemonic == "stmfd" ||
526 Mnemonic == "ldmfd" ||
531 Mnemonic == "push" ||
534 // Hard-coded to a valid instruction, till we have a real matcher.
536 Inst.setOpcode(ARM::MOVr);
537 Inst.addOperand(MCOperand::CreateReg(2));
538 Inst.addOperand(MCOperand::CreateReg(2));
539 Inst.addOperand(MCOperand::CreateImm(0));
540 Inst.addOperand(MCOperand::CreateImm(0));
541 Inst.addOperand(MCOperand::CreateReg(0));
548 /// Parse a arm instruction operand. For now this parses the operand regardless
550 bool ARMAsmParser::ParseOperand(ARMOperand &Op) {
551 switch (getLexer().getKind()) {
552 case AsmToken::Identifier:
553 if (!MaybeParseRegister(Op, true))
555 // This was not a register so parse other operands that start with an
556 // identifier (like labels) as expressions and create them as immediates.
558 if (getParser().ParseExpression(IdVal))
560 Op = ARMOperand::CreateImm(IdVal);
562 case AsmToken::LBrac:
563 return ParseMemory(Op);
564 case AsmToken::LCurly:
565 return ParseRegisterList(Op);
568 // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
570 const MCExpr *ImmVal;
571 if (getParser().ParseExpression(ImmVal))
573 Op = ARMOperand::CreateImm(ImmVal);
576 return Error(getLexer().getTok().getLoc(), "unexpected token in operand");
580 /// Parse an arm instruction mnemonic followed by its operands.
581 bool ARMAsmParser::ParseInstruction(const StringRef &Name, MCInst &Inst) {
582 SmallVector<ARMOperand, 7> Operands;
584 Operands.push_back(ARMOperand::CreateToken(Name));
586 SMLoc Loc = getLexer().getTok().getLoc();
587 if (getLexer().isNot(AsmToken::EndOfStatement)) {
589 // Read the first operand.
590 Operands.push_back(ARMOperand());
591 if (ParseOperand(Operands.back()))
594 while (getLexer().is(AsmToken::Comma)) {
595 getLexer().Lex(); // Eat the comma.
597 // Parse and remember the operand.
598 Operands.push_back(ARMOperand());
599 if (ParseOperand(Operands.back()))
603 if (!MatchInstruction(Operands, Inst))
606 Error(Loc, "ARMAsmParser::ParseInstruction only partly implemented");
610 /// ParseDirective parses the arm specific directives
611 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
612 StringRef IDVal = DirectiveID.getIdentifier();
613 if (IDVal == ".word")
614 return ParseDirectiveWord(4, DirectiveID.getLoc());
615 else if (IDVal == ".thumb")
616 return ParseDirectiveThumb(DirectiveID.getLoc());
617 else if (IDVal == ".thumb_func")
618 return ParseDirectiveThumbFunc(DirectiveID.getLoc());
619 else if (IDVal == ".code")
620 return ParseDirectiveCode(DirectiveID.getLoc());
621 else if (IDVal == ".syntax")
622 return ParseDirectiveSyntax(DirectiveID.getLoc());
626 /// ParseDirectiveWord
627 /// ::= .word [ expression (, expression)* ]
628 bool ARMAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
629 if (getLexer().isNot(AsmToken::EndOfStatement)) {
632 if (getParser().ParseExpression(Value))
635 getParser().getStreamer().EmitValue(Value, Size);
637 if (getLexer().is(AsmToken::EndOfStatement))
640 // FIXME: Improve diagnostic.
641 if (getLexer().isNot(AsmToken::Comma))
642 return Error(L, "unexpected token in directive");
651 /// ParseDirectiveThumb
653 bool ARMAsmParser::ParseDirectiveThumb(SMLoc L) {
654 if (getLexer().isNot(AsmToken::EndOfStatement))
655 return Error(L, "unexpected token in directive");
658 // TODO: set thumb mode
659 // TODO: tell the MC streamer the mode
660 // getParser().getStreamer().Emit???();
664 /// ParseDirectiveThumbFunc
665 /// ::= .thumbfunc symbol_name
666 bool ARMAsmParser::ParseDirectiveThumbFunc(SMLoc L) {
667 const AsmToken &Tok = getLexer().getTok();
668 if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
669 return Error(L, "unexpected token in .syntax directive");
670 StringRef ATTRIBUTE_UNUSED SymbolName = getLexer().getTok().getIdentifier();
671 getLexer().Lex(); // Consume the identifier token.
673 if (getLexer().isNot(AsmToken::EndOfStatement))
674 return Error(L, "unexpected token in directive");
677 // TODO: mark symbol as a thumb symbol
678 // getParser().getStreamer().Emit???();
682 /// ParseDirectiveSyntax
683 /// ::= .syntax unified | divided
684 bool ARMAsmParser::ParseDirectiveSyntax(SMLoc L) {
685 const AsmToken &Tok = getLexer().getTok();
686 if (Tok.isNot(AsmToken::Identifier))
687 return Error(L, "unexpected token in .syntax directive");
688 const StringRef &Mode = Tok.getString();
690 if (Mode == "unified" || Mode == "UNIFIED") {
692 unified_syntax = true;
694 else if (Mode == "divided" || Mode == "DIVIDED") {
696 unified_syntax = false;
699 return Error(L, "unrecognized syntax mode in .syntax directive");
701 if (getLexer().isNot(AsmToken::EndOfStatement))
702 return Error(getLexer().getTok().getLoc(), "unexpected token in directive");
705 // TODO tell the MC streamer the mode
706 // getParser().getStreamer().Emit???();
710 /// ParseDirectiveCode
711 /// ::= .code 16 | 32
712 bool ARMAsmParser::ParseDirectiveCode(SMLoc L) {
713 const AsmToken &Tok = getLexer().getTok();
714 if (Tok.isNot(AsmToken::Integer))
715 return Error(L, "unexpected token in .code directive");
716 int64_t Val = getLexer().getTok().getIntVal();
722 else if (Val == 32) {
727 return Error(L, "invalid operand to .code directive");
729 if (getLexer().isNot(AsmToken::EndOfStatement))
730 return Error(getLexer().getTok().getLoc(), "unexpected token in directive");
733 // TODO tell the MC streamer the mode
734 // getParser().getStreamer().Emit???();
738 /// Force static initialization.
739 extern "C" void LLVMInitializeARMAsmParser() {
740 RegisterAsmParser<ARMAsmParser> X(TheARMTarget);
741 RegisterAsmParser<ARMAsmParser> Y(TheThumbTarget);