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 "ARMAddressingModes.h"
12 #include "ARMMCExpr.h"
13 #include "ARMBaseRegisterInfo.h"
14 #include "ARMSubtarget.h"
15 #include "llvm/MC/MCParser/MCAsmLexer.h"
16 #include "llvm/MC/MCParser/MCAsmParser.h"
17 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/Target/TargetRegistry.h"
23 #include "llvm/Target/TargetAsmParser.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/ADT/Twine.h"
32 /// Shift types used for register controlled shifts in ARM memory addressing.
45 class ARMAsmParser : public TargetAsmParser {
49 MCAsmParser &getParser() const { return Parser; }
50 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
52 void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
53 bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
55 int TryParseRegister();
56 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
57 bool TryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &);
58 bool ParseCoprocNumOperand(SmallVectorImpl<MCParsedAsmOperand*>&);
59 bool ParseCoprocRegOperand(SmallVectorImpl<MCParsedAsmOperand*>&);
60 bool ParseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &);
61 bool ParseMemBarrierOptOperand(SmallVectorImpl<MCParsedAsmOperand*> &);
62 bool ParseMemory(SmallVectorImpl<MCParsedAsmOperand*> &);
63 bool ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &, StringRef Mnemonic);
64 bool ParsePrefix(ARMMCExpr::VariantKind &RefKind);
65 const MCExpr *ApplyPrefixToExpr(const MCExpr *E,
66 MCSymbolRefExpr::VariantKind Variant);
69 bool ParseMemoryOffsetReg(bool &Negative,
70 bool &OffsetRegShifted,
71 enum ShiftType &ShiftType,
72 const MCExpr *&ShiftAmount,
73 const MCExpr *&Offset,
77 bool ParseShift(enum ShiftType &St, const MCExpr *&ShiftAmount, SMLoc &E);
78 bool ParseDirectiveWord(unsigned Size, SMLoc L);
79 bool ParseDirectiveThumb(SMLoc L);
80 bool ParseDirectiveThumbFunc(SMLoc L);
81 bool ParseDirectiveCode(SMLoc L);
82 bool ParseDirectiveSyntax(SMLoc L);
84 bool MatchAndEmitInstruction(SMLoc IDLoc,
85 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
87 void GetMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
88 bool &CanAcceptPredicationCode);
90 /// @name Auto-generated Match Functions
93 #define GET_ASSEMBLER_HEADER
94 #include "ARMGenAsmMatcher.inc"
99 ARMAsmParser(const Target &T, MCAsmParser &_Parser, TargetMachine &_TM)
100 : TargetAsmParser(T), Parser(_Parser), TM(_TM) {
101 // Initialize the set of available features.
102 setAvailableFeatures(ComputeAvailableFeatures(
103 &TM.getSubtarget<ARMSubtarget>()));
106 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
107 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
108 virtual bool ParseDirective(AsmToken DirectiveID);
110 } // end anonymous namespace
114 /// ARMOperand - Instances of this class represent a parsed ARM machine
116 class ARMOperand : public MCParsedAsmOperand {
132 SMLoc StartLoc, EndLoc;
133 SmallVector<unsigned, 8> Registers;
137 ARMCC::CondCodes Val;
161 /// Combined record for all forms of ARM address expressions.
165 unsigned RegNum; ///< Offset register num, when OffsetIsReg.
166 const MCExpr *Value; ///< Offset value, when !OffsetIsReg.
168 const MCExpr *ShiftAmount; // used when OffsetRegShifted is true
169 enum ShiftType ShiftType; // used when OffsetRegShifted is true
170 unsigned OffsetRegShifted : 1; // only used when OffsetIsReg is true
171 unsigned Preindexed : 1;
172 unsigned Postindexed : 1;
173 unsigned OffsetIsReg : 1;
174 unsigned Negative : 1; // only used when OffsetIsReg is true
175 unsigned Writeback : 1;
179 ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
181 ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
183 StartLoc = o.StartLoc;
197 case DPRRegisterList:
198 case SPRRegisterList:
199 Registers = o.Registers;
217 /// getStartLoc - Get the location of the first token of this operand.
218 SMLoc getStartLoc() const { return StartLoc; }
219 /// getEndLoc - Get the location of the last token of this operand.
220 SMLoc getEndLoc() const { return EndLoc; }
222 ARMCC::CondCodes getCondCode() const {
223 assert(Kind == CondCode && "Invalid access!");
227 unsigned getCoproc() const {
228 assert((Kind == CoprocNum || Kind == CoprocReg) && "Invalid access!");
232 StringRef getToken() const {
233 assert(Kind == Token && "Invalid access!");
234 return StringRef(Tok.Data, Tok.Length);
237 unsigned getReg() const {
238 assert((Kind == Register || Kind == CCOut) && "Invalid access!");
242 const SmallVectorImpl<unsigned> &getRegList() const {
243 assert((Kind == RegisterList || Kind == DPRRegisterList ||
244 Kind == SPRRegisterList) && "Invalid access!");
248 const MCExpr *getImm() const {
249 assert(Kind == Immediate && "Invalid access!");
253 ARM_MB::MemBOpt getMemBarrierOpt() const {
254 assert(Kind == MemBarrierOpt && "Invalid access!");
258 /// @name Memory Operand Accessors
261 unsigned getMemBaseRegNum() const {
262 return Mem.BaseRegNum;
264 unsigned getMemOffsetRegNum() const {
265 assert(Mem.OffsetIsReg && "Invalid access!");
266 return Mem.Offset.RegNum;
268 const MCExpr *getMemOffset() const {
269 assert(!Mem.OffsetIsReg && "Invalid access!");
270 return Mem.Offset.Value;
272 unsigned getMemOffsetRegShifted() const {
273 assert(Mem.OffsetIsReg && "Invalid access!");
274 return Mem.OffsetRegShifted;
276 const MCExpr *getMemShiftAmount() const {
277 assert(Mem.OffsetIsReg && Mem.OffsetRegShifted && "Invalid access!");
278 return Mem.ShiftAmount;
280 enum ShiftType getMemShiftType() const {
281 assert(Mem.OffsetIsReg && Mem.OffsetRegShifted && "Invalid access!");
282 return Mem.ShiftType;
284 bool getMemPreindexed() const { return Mem.Preindexed; }
285 bool getMemPostindexed() const { return Mem.Postindexed; }
286 bool getMemOffsetIsReg() const { return Mem.OffsetIsReg; }
287 bool getMemNegative() const { return Mem.Negative; }
288 bool getMemWriteback() const { return Mem.Writeback; }
292 bool isCoprocNum() const { return Kind == CoprocNum; }
293 bool isCoprocReg() const { return Kind == CoprocReg; }
294 bool isCondCode() const { return Kind == CondCode; }
295 bool isCCOut() const { return Kind == CCOut; }
296 bool isImm() const { return Kind == Immediate; }
297 bool isReg() const { return Kind == Register; }
298 bool isRegList() const { return Kind == RegisterList; }
299 bool isDPRRegList() const { return Kind == DPRRegisterList; }
300 bool isSPRRegList() const { return Kind == SPRRegisterList; }
301 bool isToken() const { return Kind == Token; }
302 bool isMemBarrierOpt() const { return Kind == MemBarrierOpt; }
303 bool isMemory() const { return Kind == Memory; }
304 bool isMemMode5() const {
305 if (!isMemory() || getMemOffsetIsReg() || getMemWriteback() ||
309 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
310 if (!CE) return false;
312 // The offset must be a multiple of 4 in the range 0-1020.
313 int64_t Value = CE->getValue();
314 return ((Value & 0x3) == 0 && Value <= 1020 && Value >= -1020);
316 bool isMemModeRegThumb() const {
317 if (!isMemory() || !getMemOffsetIsReg() || getMemWriteback())
321 bool isMemModeImmThumb() const {
322 if (!isMemory() || getMemOffsetIsReg() || getMemWriteback())
325 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
326 if (!CE) return false;
328 // The offset must be a multiple of 4 in the range 0-124.
329 uint64_t Value = CE->getValue();
330 return ((Value & 0x3) == 0 && Value <= 124);
333 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
334 // Add as immediates when possible. Null MCExpr = 0.
336 Inst.addOperand(MCOperand::CreateImm(0));
337 else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
338 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
340 Inst.addOperand(MCOperand::CreateExpr(Expr));
343 void addCondCodeOperands(MCInst &Inst, unsigned N) const {
344 assert(N == 2 && "Invalid number of operands!");
345 Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
346 unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
347 Inst.addOperand(MCOperand::CreateReg(RegNum));
350 void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
351 assert(N == 1 && "Invalid number of operands!");
352 Inst.addOperand(MCOperand::CreateImm(getCoproc()));
355 void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
356 assert(N == 1 && "Invalid number of operands!");
357 Inst.addOperand(MCOperand::CreateImm(getCoproc()));
360 void addCCOutOperands(MCInst &Inst, unsigned N) const {
361 assert(N == 1 && "Invalid number of operands!");
362 Inst.addOperand(MCOperand::CreateReg(getReg()));
365 void addRegOperands(MCInst &Inst, unsigned N) const {
366 assert(N == 1 && "Invalid number of operands!");
367 Inst.addOperand(MCOperand::CreateReg(getReg()));
370 void addRegListOperands(MCInst &Inst, unsigned N) const {
371 assert(N == 1 && "Invalid number of operands!");
372 const SmallVectorImpl<unsigned> &RegList = getRegList();
373 for (SmallVectorImpl<unsigned>::const_iterator
374 I = RegList.begin(), E = RegList.end(); I != E; ++I)
375 Inst.addOperand(MCOperand::CreateReg(*I));
378 void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
379 addRegListOperands(Inst, N);
382 void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
383 addRegListOperands(Inst, N);
386 void addImmOperands(MCInst &Inst, unsigned N) const {
387 assert(N == 1 && "Invalid number of operands!");
388 addExpr(Inst, getImm());
391 void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
392 assert(N == 1 && "Invalid number of operands!");
393 Inst.addOperand(MCOperand::CreateImm(unsigned(getMemBarrierOpt())));
396 void addMemMode5Operands(MCInst &Inst, unsigned N) const {
397 assert(N == 2 && isMemMode5() && "Invalid number of operands!");
399 Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
400 assert(!getMemOffsetIsReg() && "Invalid mode 5 operand");
402 // FIXME: #-0 is encoded differently than #0. Does the parser preserve
404 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
405 assert(CE && "Non-constant mode 5 offset operand!");
407 // The MCInst offset operand doesn't include the low two bits (like
408 // the instruction encoding).
409 int64_t Offset = CE->getValue() / 4;
411 Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::add,
414 Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::sub,
418 void addMemModeRegThumbOperands(MCInst &Inst, unsigned N) const {
419 assert(N == 2 && isMemModeRegThumb() && "Invalid number of operands!");
420 Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
421 Inst.addOperand(MCOperand::CreateReg(getMemOffsetRegNum()));
424 void addMemModeImmThumbOperands(MCInst &Inst, unsigned N) const {
425 assert(N == 2 && isMemModeImmThumb() && "Invalid number of operands!");
426 Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
427 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
428 assert(CE && "Non-constant mode offset operand!");
429 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
432 virtual void dump(raw_ostream &OS) const;
434 static ARMOperand *CreateCondCode(ARMCC::CondCodes CC, SMLoc S) {
435 ARMOperand *Op = new ARMOperand(CondCode);
442 static ARMOperand *CreateCoprocNum(unsigned CopVal, SMLoc S) {
443 ARMOperand *Op = new ARMOperand(CoprocNum);
444 Op->Cop.Val = CopVal;
450 static ARMOperand *CreateCoprocReg(unsigned CopVal, SMLoc S) {
451 ARMOperand *Op = new ARMOperand(CoprocReg);
452 Op->Cop.Val = CopVal;
458 static ARMOperand *CreateCCOut(unsigned RegNum, SMLoc S) {
459 ARMOperand *Op = new ARMOperand(CCOut);
460 Op->Reg.RegNum = RegNum;
466 static ARMOperand *CreateToken(StringRef Str, SMLoc S) {
467 ARMOperand *Op = new ARMOperand(Token);
468 Op->Tok.Data = Str.data();
469 Op->Tok.Length = Str.size();
475 static ARMOperand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
476 ARMOperand *Op = new ARMOperand(Register);
477 Op->Reg.RegNum = RegNum;
484 CreateRegList(const SmallVectorImpl<std::pair<unsigned, SMLoc> > &Regs,
485 SMLoc StartLoc, SMLoc EndLoc) {
486 KindTy Kind = RegisterList;
488 if (ARM::DPRRegClass.contains(Regs.front().first))
489 Kind = DPRRegisterList;
490 else if (ARM::SPRRegClass.contains(Regs.front().first))
491 Kind = SPRRegisterList;
493 ARMOperand *Op = new ARMOperand(Kind);
494 for (SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
495 I = Regs.begin(), E = Regs.end(); I != E; ++I)
496 Op->Registers.push_back(I->first);
497 array_pod_sort(Op->Registers.begin(), Op->Registers.end());
498 Op->StartLoc = StartLoc;
503 static ARMOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
504 ARMOperand *Op = new ARMOperand(Immediate);
511 static ARMOperand *CreateMem(unsigned BaseRegNum, bool OffsetIsReg,
512 const MCExpr *Offset, int OffsetRegNum,
513 bool OffsetRegShifted, enum ShiftType ShiftType,
514 const MCExpr *ShiftAmount, bool Preindexed,
515 bool Postindexed, bool Negative, bool Writeback,
517 assert((OffsetRegNum == -1 || OffsetIsReg) &&
518 "OffsetRegNum must imply OffsetIsReg!");
519 assert((!OffsetRegShifted || OffsetIsReg) &&
520 "OffsetRegShifted must imply OffsetIsReg!");
521 assert((Offset || OffsetIsReg) &&
522 "Offset must exists unless register offset is used!");
523 assert((!ShiftAmount || (OffsetIsReg && OffsetRegShifted)) &&
524 "Cannot have shift amount without shifted register offset!");
525 assert((!Offset || !OffsetIsReg) &&
526 "Cannot have expression offset and register offset!");
528 ARMOperand *Op = new ARMOperand(Memory);
529 Op->Mem.BaseRegNum = BaseRegNum;
530 Op->Mem.OffsetIsReg = OffsetIsReg;
532 Op->Mem.Offset.RegNum = OffsetRegNum;
534 Op->Mem.Offset.Value = Offset;
535 Op->Mem.OffsetRegShifted = OffsetRegShifted;
536 Op->Mem.ShiftType = ShiftType;
537 Op->Mem.ShiftAmount = ShiftAmount;
538 Op->Mem.Preindexed = Preindexed;
539 Op->Mem.Postindexed = Postindexed;
540 Op->Mem.Negative = Negative;
541 Op->Mem.Writeback = Writeback;
548 static ARMOperand *CreateMemBarrierOpt(ARM_MB::MemBOpt Opt, SMLoc S) {
549 ARMOperand *Op = new ARMOperand(MemBarrierOpt);
557 } // end anonymous namespace.
559 void ARMOperand::dump(raw_ostream &OS) const {
562 OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
565 OS << "<ccout " << getReg() << ">";
568 OS << "<coprocessor number: " << getCoproc() << ">";
571 OS << "<coprocessor register: " << getCoproc() << ">";
577 OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt()) << ">";
581 << "base:" << getMemBaseRegNum();
582 if (getMemOffsetIsReg()) {
583 OS << " offset:<register " << getMemOffsetRegNum();
584 if (getMemOffsetRegShifted()) {
585 OS << " offset-shift-type:" << getMemShiftType();
586 OS << " offset-shift-amount:" << *getMemShiftAmount();
589 OS << " offset:" << *getMemOffset();
591 if (getMemOffsetIsReg())
592 OS << " (offset-is-reg)";
593 if (getMemPreindexed())
594 OS << " (pre-indexed)";
595 if (getMemPostindexed())
596 OS << " (post-indexed)";
597 if (getMemNegative())
599 if (getMemWriteback())
600 OS << " (writeback)";
604 OS << "<register " << getReg() << ">";
607 case DPRRegisterList:
608 case SPRRegisterList: {
609 OS << "<register_list ";
611 const SmallVectorImpl<unsigned> &RegList = getRegList();
612 for (SmallVectorImpl<unsigned>::const_iterator
613 I = RegList.begin(), E = RegList.end(); I != E; ) {
615 if (++I < E) OS << ", ";
622 OS << "'" << getToken() << "'";
627 /// @name Auto-generated Match Functions
630 static unsigned MatchRegisterName(StringRef Name);
634 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
635 SMLoc &StartLoc, SMLoc &EndLoc) {
636 RegNo = TryParseRegister();
638 return (RegNo == (unsigned)-1);
641 /// Try to parse a register name. The token must be an Identifier when called,
642 /// and if it is a register name the token is eaten and the register number is
643 /// returned. Otherwise return -1.
645 int ARMAsmParser::TryParseRegister() {
646 const AsmToken &Tok = Parser.getTok();
647 assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
649 // FIXME: Validate register for the current architecture; we have to do
650 // validation later, so maybe there is no need for this here.
651 std::string upperCase = Tok.getString().str();
652 std::string lowerCase = LowercaseString(upperCase);
653 unsigned RegNum = MatchRegisterName(lowerCase);
655 RegNum = StringSwitch<unsigned>(lowerCase)
656 .Case("r13", ARM::SP)
657 .Case("r14", ARM::LR)
658 .Case("r15", ARM::PC)
659 .Case("ip", ARM::R12)
662 if (!RegNum) return -1;
664 Parser.Lex(); // Eat identifier token.
668 /// Try to parse a register name. The token must be an Identifier when called.
669 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
670 /// if there is a "writeback". 'true' if it's not a register.
672 /// TODO this is likely to change to allow different register types and or to
673 /// parse for a specific register type.
675 TryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
676 SMLoc S = Parser.getTok().getLoc();
677 int RegNo = TryParseRegister();
681 Operands.push_back(ARMOperand::CreateReg(RegNo, S, Parser.getTok().getLoc()));
683 const AsmToken &ExclaimTok = Parser.getTok();
684 if (ExclaimTok.is(AsmToken::Exclaim)) {
685 Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
686 ExclaimTok.getLoc()));
687 Parser.Lex(); // Eat exclaim token
693 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
694 /// instruction with a symbolic operand name. Example: "p1", "p7", "c3",
696 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
697 // Use the same layout as the tablegen'erated register name matcher. Ugly,
699 switch (Name.size()) {
702 if (Name[0] != CoprocOp)
719 if (Name[0] != CoprocOp || Name[1] != '1')
733 llvm_unreachable("Unhandled coprocessor operand string!");
737 /// ParseCoprocNumOperand - Try to parse an coprocessor number operand. The
738 /// token must be an Identifier when called, and if it is a coprocessor
739 /// number, the token is eaten and the operand is added to the operand list.
741 ParseCoprocNumOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
742 SMLoc S = Parser.getTok().getLoc();
743 const AsmToken &Tok = Parser.getTok();
744 assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
746 int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
750 Parser.Lex(); // Eat identifier token.
751 Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
755 /// ParseCoprocRegOperand - Try to parse an coprocessor register operand. The
756 /// token must be an Identifier when called, and if it is a coprocessor
757 /// number, the token is eaten and the operand is added to the operand list.
759 ParseCoprocRegOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
760 SMLoc S = Parser.getTok().getLoc();
761 const AsmToken &Tok = Parser.getTok();
762 assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
764 int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
768 Parser.Lex(); // Eat identifier token.
769 Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
773 /// Parse a register list, return it if successful else return null. The first
774 /// token must be a '{' when called.
776 ParseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
777 assert(Parser.getTok().is(AsmToken::LCurly) &&
778 "Token is not a Left Curly Brace");
779 SMLoc S = Parser.getTok().getLoc();
781 // Read the rest of the registers in the list.
782 unsigned PrevRegNum = 0;
783 SmallVector<std::pair<unsigned, SMLoc>, 32> Registers;
786 bool IsRange = Parser.getTok().is(AsmToken::Minus);
787 Parser.Lex(); // Eat non-identifier token.
789 const AsmToken &RegTok = Parser.getTok();
790 SMLoc RegLoc = RegTok.getLoc();
791 if (RegTok.isNot(AsmToken::Identifier)) {
792 Error(RegLoc, "register expected");
796 int RegNum = TryParseRegister();
798 Error(RegLoc, "register expected");
803 int Reg = PrevRegNum;
806 Registers.push_back(std::make_pair(Reg, RegLoc));
807 } while (Reg != RegNum);
809 Registers.push_back(std::make_pair(RegNum, RegLoc));
813 } while (Parser.getTok().is(AsmToken::Comma) ||
814 Parser.getTok().is(AsmToken::Minus));
816 // Process the right curly brace of the list.
817 const AsmToken &RCurlyTok = Parser.getTok();
818 if (RCurlyTok.isNot(AsmToken::RCurly)) {
819 Error(RCurlyTok.getLoc(), "'}' expected");
823 SMLoc E = RCurlyTok.getLoc();
824 Parser.Lex(); // Eat right curly brace token.
826 // Verify the register list.
827 SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
828 RI = Registers.begin(), RE = Registers.end();
830 unsigned HighRegNum = getARMRegisterNumbering(RI->first);
831 bool EmittedWarning = false;
833 DenseMap<unsigned, bool> RegMap;
834 RegMap[HighRegNum] = true;
836 for (++RI; RI != RE; ++RI) {
837 const std::pair<unsigned, SMLoc> &RegInfo = *RI;
838 unsigned Reg = getARMRegisterNumbering(RegInfo.first);
841 Error(RegInfo.second, "register duplicated in register list");
845 if (!EmittedWarning && Reg < HighRegNum)
846 Warning(RegInfo.second,
847 "register not in ascending order in register list");
850 HighRegNum = std::max(Reg, HighRegNum);
853 Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
857 /// ParseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
859 ParseMemBarrierOptOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
860 SMLoc S = Parser.getTok().getLoc();
861 const AsmToken &Tok = Parser.getTok();
862 assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
863 StringRef OptStr = Tok.getString();
865 unsigned Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()))
866 .Case("sy", ARM_MB::SY)
867 .Case("st", ARM_MB::ST)
868 .Case("ish", ARM_MB::ISH)
869 .Case("ishst", ARM_MB::ISHST)
870 .Case("nsh", ARM_MB::NSH)
871 .Case("nshst", ARM_MB::NSHST)
872 .Case("osh", ARM_MB::OSH)
873 .Case("oshst", ARM_MB::OSHST)
879 Parser.Lex(); // Eat identifier token.
880 Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
884 /// Parse an ARM memory expression, return false if successful else return true
885 /// or an error. The first token must be a '[' when called.
887 /// TODO Only preindexing and postindexing addressing are started, unindexed
888 /// with option, etc are still to do.
890 ParseMemory(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
892 assert(Parser.getTok().is(AsmToken::LBrac) &&
893 "Token is not a Left Bracket");
894 S = Parser.getTok().getLoc();
895 Parser.Lex(); // Eat left bracket token.
897 const AsmToken &BaseRegTok = Parser.getTok();
898 if (BaseRegTok.isNot(AsmToken::Identifier)) {
899 Error(BaseRegTok.getLoc(), "register expected");
902 int BaseRegNum = TryParseRegister();
903 if (BaseRegNum == -1) {
904 Error(BaseRegTok.getLoc(), "register expected");
908 // The next token must either be a comma or a closing bracket.
909 const AsmToken &Tok = Parser.getTok();
910 if (!Tok.is(AsmToken::Comma) && !Tok.is(AsmToken::RBrac))
913 bool Preindexed = false;
914 bool Postindexed = false;
915 bool OffsetIsReg = false;
916 bool Negative = false;
917 bool Writeback = false;
918 ARMOperand *WBOp = 0;
919 int OffsetRegNum = -1;
920 bool OffsetRegShifted = false;
921 enum ShiftType ShiftType = Lsl;
922 const MCExpr *ShiftAmount = 0;
923 const MCExpr *Offset = 0;
925 // First look for preindexed address forms, that is after the "[Rn" we now
926 // have to see if the next token is a comma.
927 if (Tok.is(AsmToken::Comma)) {
929 Parser.Lex(); // Eat comma token.
931 if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType, ShiftAmount,
932 Offset, OffsetIsReg, OffsetRegNum, E))
934 const AsmToken &RBracTok = Parser.getTok();
935 if (RBracTok.isNot(AsmToken::RBrac)) {
936 Error(RBracTok.getLoc(), "']' expected");
939 E = RBracTok.getLoc();
940 Parser.Lex(); // Eat right bracket token.
942 const AsmToken &ExclaimTok = Parser.getTok();
943 if (ExclaimTok.is(AsmToken::Exclaim)) {
944 WBOp = ARMOperand::CreateToken(ExclaimTok.getString(),
945 ExclaimTok.getLoc());
947 Parser.Lex(); // Eat exclaim token
950 // The "[Rn" we have so far was not followed by a comma.
952 // If there's anything other than the right brace, this is a post indexing
955 Parser.Lex(); // Eat right bracket token.
957 const AsmToken &NextTok = Parser.getTok();
959 if (NextTok.isNot(AsmToken::EndOfStatement)) {
963 if (NextTok.isNot(AsmToken::Comma)) {
964 Error(NextTok.getLoc(), "',' expected");
968 Parser.Lex(); // Eat comma token.
970 if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType,
971 ShiftAmount, Offset, OffsetIsReg, OffsetRegNum,
977 // Force Offset to exist if used.
980 Offset = MCConstantExpr::Create(0, getContext());
983 Operands.push_back(ARMOperand::CreateMem(BaseRegNum, OffsetIsReg, Offset,
984 OffsetRegNum, OffsetRegShifted,
985 ShiftType, ShiftAmount, Preindexed,
986 Postindexed, Negative, Writeback,
989 Operands.push_back(WBOp);
994 /// Parse the offset of a memory operand after we have seen "[Rn," or "[Rn],"
995 /// we will parse the following (were +/- means that a plus or minus is
1000 /// we return false on success or an error otherwise.
1001 bool ARMAsmParser::ParseMemoryOffsetReg(bool &Negative,
1002 bool &OffsetRegShifted,
1003 enum ShiftType &ShiftType,
1004 const MCExpr *&ShiftAmount,
1005 const MCExpr *&Offset,
1010 OffsetRegShifted = false;
1011 OffsetIsReg = false;
1013 const AsmToken &NextTok = Parser.getTok();
1014 E = NextTok.getLoc();
1015 if (NextTok.is(AsmToken::Plus))
1016 Parser.Lex(); // Eat plus token.
1017 else if (NextTok.is(AsmToken::Minus)) {
1019 Parser.Lex(); // Eat minus token
1021 // See if there is a register following the "[Rn," or "[Rn]," we have so far.
1022 const AsmToken &OffsetRegTok = Parser.getTok();
1023 if (OffsetRegTok.is(AsmToken::Identifier)) {
1024 SMLoc CurLoc = OffsetRegTok.getLoc();
1025 OffsetRegNum = TryParseRegister();
1026 if (OffsetRegNum != -1) {
1032 // If we parsed a register as the offset then there can be a shift after that.
1033 if (OffsetRegNum != -1) {
1034 // Look for a comma then a shift
1035 const AsmToken &Tok = Parser.getTok();
1036 if (Tok.is(AsmToken::Comma)) {
1037 Parser.Lex(); // Eat comma token.
1039 const AsmToken &Tok = Parser.getTok();
1040 if (ParseShift(ShiftType, ShiftAmount, E))
1041 return Error(Tok.getLoc(), "shift expected");
1042 OffsetRegShifted = true;
1045 else { // the "[Rn," or "[Rn,]" we have so far was not followed by "Rm"
1046 // Look for #offset following the "[Rn," or "[Rn],"
1047 const AsmToken &HashTok = Parser.getTok();
1048 if (HashTok.isNot(AsmToken::Hash))
1049 return Error(HashTok.getLoc(), "'#' expected");
1051 Parser.Lex(); // Eat hash token.
1053 if (getParser().ParseExpression(Offset))
1055 E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1060 /// ParseShift as one of these two:
1061 /// ( lsl | lsr | asr | ror ) , # shift_amount
1063 /// and returns true if it parses a shift otherwise it returns false.
1064 bool ARMAsmParser::ParseShift(ShiftType &St, const MCExpr *&ShiftAmount,
1066 const AsmToken &Tok = Parser.getTok();
1067 if (Tok.isNot(AsmToken::Identifier))
1069 StringRef ShiftName = Tok.getString();
1070 if (ShiftName == "lsl" || ShiftName == "LSL")
1072 else if (ShiftName == "lsr" || ShiftName == "LSR")
1074 else if (ShiftName == "asr" || ShiftName == "ASR")
1076 else if (ShiftName == "ror" || ShiftName == "ROR")
1078 else if (ShiftName == "rrx" || ShiftName == "RRX")
1082 Parser.Lex(); // Eat shift type token.
1084 // Rrx stands alone.
1088 // Otherwise, there must be a '#' and a shift amount.
1089 const AsmToken &HashTok = Parser.getTok();
1090 if (HashTok.isNot(AsmToken::Hash))
1091 return Error(HashTok.getLoc(), "'#' expected");
1092 Parser.Lex(); // Eat hash token.
1094 if (getParser().ParseExpression(ShiftAmount))
1100 /// Parse a arm instruction operand. For now this parses the operand regardless
1101 /// of the mnemonic.
1102 bool ARMAsmParser::ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1103 StringRef Mnemonic) {
1106 // Check if the current operand has a custom associated parser, if so, try to
1107 // custom parse the operand, or fallback to the general approach.
1108 MatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
1109 if (ResTy == Match_Success)
1112 switch (getLexer().getKind()) {
1114 Error(Parser.getTok().getLoc(), "unexpected token in operand");
1116 case AsmToken::Identifier:
1117 if (!TryParseRegisterWithWriteBack(Operands))
1120 // Fall though for the Identifier case that is not a register or a
1122 case AsmToken::Integer: // things like 1f and 2b as a branch targets
1123 case AsmToken::Dot: { // . as a branch target
1124 // This was not a register so parse other operands that start with an
1125 // identifier (like labels) as expressions and create them as immediates.
1126 const MCExpr *IdVal;
1127 S = Parser.getTok().getLoc();
1128 if (getParser().ParseExpression(IdVal))
1130 E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1131 Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
1134 case AsmToken::LBrac:
1135 return ParseMemory(Operands);
1136 case AsmToken::LCurly:
1137 return ParseRegisterList(Operands);
1138 case AsmToken::Hash:
1139 // #42 -> immediate.
1140 // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
1141 S = Parser.getTok().getLoc();
1143 const MCExpr *ImmVal;
1144 if (getParser().ParseExpression(ImmVal))
1146 E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1147 Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
1149 case AsmToken::Colon: {
1150 // ":lower16:" and ":upper16:" expression prefixes
1151 // FIXME: Check it's an expression prefix,
1152 // e.g. (FOO - :lower16:BAR) isn't legal.
1153 ARMMCExpr::VariantKind RefKind;
1154 if (ParsePrefix(RefKind))
1157 const MCExpr *SubExprVal;
1158 if (getParser().ParseExpression(SubExprVal))
1161 const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal,
1163 E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1164 Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
1170 // ParsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
1171 // :lower16: and :upper16:.
1172 bool ARMAsmParser::ParsePrefix(ARMMCExpr::VariantKind &RefKind) {
1173 RefKind = ARMMCExpr::VK_ARM_None;
1175 // :lower16: and :upper16: modifiers
1176 assert(getLexer().is(AsmToken::Colon) && "expected a :");
1177 Parser.Lex(); // Eat ':'
1179 if (getLexer().isNot(AsmToken::Identifier)) {
1180 Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
1184 StringRef IDVal = Parser.getTok().getIdentifier();
1185 if (IDVal == "lower16") {
1186 RefKind = ARMMCExpr::VK_ARM_LO16;
1187 } else if (IDVal == "upper16") {
1188 RefKind = ARMMCExpr::VK_ARM_HI16;
1190 Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
1195 if (getLexer().isNot(AsmToken::Colon)) {
1196 Error(Parser.getTok().getLoc(), "unexpected token after prefix");
1199 Parser.Lex(); // Eat the last ':'
1204 ARMAsmParser::ApplyPrefixToExpr(const MCExpr *E,
1205 MCSymbolRefExpr::VariantKind Variant) {
1206 // Recurse over the given expression, rebuilding it to apply the given variant
1207 // to the leftmost symbol.
1208 if (Variant == MCSymbolRefExpr::VK_None)
1211 switch (E->getKind()) {
1212 case MCExpr::Target:
1213 llvm_unreachable("Can't handle target expr yet");
1214 case MCExpr::Constant:
1215 llvm_unreachable("Can't handle lower16/upper16 of constant yet");
1217 case MCExpr::SymbolRef: {
1218 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1220 if (SRE->getKind() != MCSymbolRefExpr::VK_None)
1223 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
1227 llvm_unreachable("Can't handle unary expressions yet");
1229 case MCExpr::Binary: {
1230 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1231 const MCExpr *LHS = ApplyPrefixToExpr(BE->getLHS(), Variant);
1232 const MCExpr *RHS = BE->getRHS();
1236 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1240 assert(0 && "Invalid expression kind!");
1244 /// \brief Given a mnemonic, split out possible predication code and carry
1245 /// setting letters to form a canonical mnemonic and flags.
1247 // FIXME: Would be nice to autogen this.
1248 static StringRef SplitMnemonicAndCC(StringRef Mnemonic,
1249 unsigned &PredicationCode,
1250 bool &CarrySetting) {
1251 PredicationCode = ARMCC::AL;
1252 CarrySetting = false;
1254 // Ignore some mnemonics we know aren't predicated forms.
1256 // FIXME: Would be nice to autogen this.
1257 if (Mnemonic == "teq" || Mnemonic == "vceq" ||
1258 Mnemonic == "movs" ||
1259 Mnemonic == "svc" ||
1260 (Mnemonic == "mls" || Mnemonic == "smmls" || Mnemonic == "vcls" ||
1261 Mnemonic == "vmls" || Mnemonic == "vnmls") ||
1262 Mnemonic == "vacge" || Mnemonic == "vcge" ||
1263 Mnemonic == "vclt" ||
1264 Mnemonic == "vacgt" || Mnemonic == "vcgt" ||
1265 Mnemonic == "vcle" ||
1266 (Mnemonic == "smlal" || Mnemonic == "umaal" || Mnemonic == "umlal" ||
1267 Mnemonic == "vabal" || Mnemonic == "vmlal" || Mnemonic == "vpadal" ||
1268 Mnemonic == "vqdmlal"))
1271 // First, split out any predication code.
1272 unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
1273 .Case("eq", ARMCC::EQ)
1274 .Case("ne", ARMCC::NE)
1275 .Case("hs", ARMCC::HS)
1276 .Case("lo", ARMCC::LO)
1277 .Case("mi", ARMCC::MI)
1278 .Case("pl", ARMCC::PL)
1279 .Case("vs", ARMCC::VS)
1280 .Case("vc", ARMCC::VC)
1281 .Case("hi", ARMCC::HI)
1282 .Case("ls", ARMCC::LS)
1283 .Case("ge", ARMCC::GE)
1284 .Case("lt", ARMCC::LT)
1285 .Case("gt", ARMCC::GT)
1286 .Case("le", ARMCC::LE)
1287 .Case("al", ARMCC::AL)
1290 Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
1291 PredicationCode = CC;
1294 // Next, determine if we have a carry setting bit. We explicitly ignore all
1295 // the instructions we know end in 's'.
1296 if (Mnemonic.endswith("s") &&
1297 !(Mnemonic == "asrs" || Mnemonic == "cps" || Mnemonic == "mls" ||
1298 Mnemonic == "movs" || Mnemonic == "mrs" || Mnemonic == "smmls" ||
1299 Mnemonic == "vabs" || Mnemonic == "vcls" || Mnemonic == "vmls" ||
1300 Mnemonic == "vmrs" || Mnemonic == "vnmls" || Mnemonic == "vqabs" ||
1301 Mnemonic == "vrecps" || Mnemonic == "vrsqrts")) {
1302 Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
1303 CarrySetting = true;
1309 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
1310 /// inclusion of carry set or predication code operands.
1312 // FIXME: It would be nice to autogen this.
1314 GetMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
1315 bool &CanAcceptPredicationCode) {
1316 bool isThumb = TM.getSubtarget<ARMSubtarget>().isThumb();
1318 if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
1319 Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
1320 Mnemonic == "smull" || Mnemonic == "add" || Mnemonic == "adc" ||
1321 Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" ||
1322 Mnemonic == "umlal" || Mnemonic == "orr" || Mnemonic == "mov" ||
1323 Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" ||
1324 Mnemonic == "sbc" || Mnemonic == "mla" || Mnemonic == "umull" ||
1325 Mnemonic == "eor" || Mnemonic == "smlal" || Mnemonic == "mvn") {
1326 CanAcceptCarrySet = true;
1328 CanAcceptCarrySet = false;
1331 if (Mnemonic == "cbnz" || Mnemonic == "setend" || Mnemonic == "dmb" ||
1332 Mnemonic == "cps" || Mnemonic == "mcr2" || Mnemonic == "it" ||
1333 Mnemonic == "mcrr2" || Mnemonic == "cbz" || Mnemonic == "cdp2" ||
1334 Mnemonic == "trap" || Mnemonic == "mrc2" || Mnemonic == "mrrc2" ||
1335 Mnemonic == "dsb" || Mnemonic == "movs" || Mnemonic == "isb" ||
1336 Mnemonic == "clrex") {
1337 CanAcceptPredicationCode = false;
1339 CanAcceptPredicationCode = true;
1343 if (Mnemonic == "bkpt" || Mnemonic == "mcr" || Mnemonic == "mcrr" ||
1344 Mnemonic == "mrc" || Mnemonic == "mrrc" || Mnemonic == "cdp")
1345 CanAcceptPredicationCode = false;
1348 /// Parse an arm instruction mnemonic followed by its operands.
1349 bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
1350 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1351 // Create the leading tokens for the mnemonic, split by '.' characters.
1352 size_t Start = 0, Next = Name.find('.');
1353 StringRef Head = Name.slice(Start, Next);
1355 // Split out the predication code and carry setting flag from the mnemonic.
1356 unsigned PredicationCode;
1358 Head = SplitMnemonicAndCC(Head, PredicationCode, CarrySetting);
1360 Operands.push_back(ARMOperand::CreateToken(Head, NameLoc));
1362 // Next, add the CCOut and ConditionCode operands, if needed.
1364 // For mnemonics which can ever incorporate a carry setting bit or predication
1365 // code, our matching model involves us always generating CCOut and
1366 // ConditionCode operands to match the mnemonic "as written" and then we let
1367 // the matcher deal with finding the right instruction or generating an
1368 // appropriate error.
1369 bool CanAcceptCarrySet, CanAcceptPredicationCode;
1370 GetMnemonicAcceptInfo(Head, CanAcceptCarrySet, CanAcceptPredicationCode);
1372 // Add the carry setting operand, if necessary.
1374 // FIXME: It would be awesome if we could somehow invent a location such that
1375 // match errors on this operand would print a nice diagnostic about how the
1376 // 's' character in the mnemonic resulted in a CCOut operand.
1377 if (CanAcceptCarrySet) {
1378 Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
1381 // This mnemonic can't ever accept a carry set, but the user wrote one (or
1382 // misspelled another mnemonic).
1384 // FIXME: Issue a nice error.
1387 // Add the predication code operand, if necessary.
1388 if (CanAcceptPredicationCode) {
1389 Operands.push_back(ARMOperand::CreateCondCode(
1390 ARMCC::CondCodes(PredicationCode), NameLoc));
1392 // This mnemonic can't ever accept a predication code, but the user wrote
1393 // one (or misspelled another mnemonic).
1395 // FIXME: Issue a nice error.
1398 // Add the remaining tokens in the mnemonic.
1399 while (Next != StringRef::npos) {
1401 Next = Name.find('.', Start + 1);
1402 Head = Name.slice(Start, Next);
1404 Operands.push_back(ARMOperand::CreateToken(Head, NameLoc));
1407 // Read the remaining operands.
1408 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1409 // Read the first operand.
1410 if (ParseOperand(Operands, Head)) {
1411 Parser.EatToEndOfStatement();
1415 while (getLexer().is(AsmToken::Comma)) {
1416 Parser.Lex(); // Eat the comma.
1418 // Parse and remember the operand.
1419 if (ParseOperand(Operands, Head)) {
1420 Parser.EatToEndOfStatement();
1426 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1427 Parser.EatToEndOfStatement();
1428 return TokError("unexpected token in argument list");
1431 Parser.Lex(); // Consume the EndOfStatement
1436 MatchAndEmitInstruction(SMLoc IDLoc,
1437 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1441 MatchResultTy MatchResult, MatchResult2;
1442 MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo);
1443 if (MatchResult != Match_Success) {
1444 // If we get a Match_InvalidOperand it might be some arithmetic instruction
1445 // that does not update the condition codes. So try adding a CCOut operand
1446 // with a value of reg0.
1447 if (MatchResult == Match_InvalidOperand) {
1448 Operands.insert(Operands.begin() + 1,
1449 ARMOperand::CreateCCOut(0,
1450 ((ARMOperand*)Operands[0])->getStartLoc()));
1451 MatchResult2 = MatchInstructionImpl(Operands, Inst, ErrorInfo);
1452 if (MatchResult2 == Match_Success)
1453 MatchResult = Match_Success;
1455 ARMOperand *CCOut = ((ARMOperand*)Operands[1]);
1456 Operands.erase(Operands.begin() + 1);
1460 // If we get a Match_MnemonicFail it might be some arithmetic instruction
1461 // that updates the condition codes if it ends in 's'. So see if the
1462 // mnemonic ends in 's' and if so try removing the 's' and adding a CCOut
1463 // operand with a value of CPSR.
1464 else if(MatchResult == Match_MnemonicFail) {
1465 // Get the instruction mnemonic, which is the first token.
1466 StringRef Mnemonic = ((ARMOperand*)Operands[0])->getToken();
1467 if (Mnemonic.substr(Mnemonic.size()-1) == "s") {
1468 // removed the 's' from the mnemonic for matching.
1469 StringRef MnemonicNoS = Mnemonic.slice(0, Mnemonic.size() - 1);
1470 SMLoc NameLoc = ((ARMOperand*)Operands[0])->getStartLoc();
1471 ARMOperand *OldMnemonic = ((ARMOperand*)Operands[0]);
1472 Operands.erase(Operands.begin());
1474 Operands.insert(Operands.begin(),
1475 ARMOperand::CreateToken(MnemonicNoS, NameLoc));
1476 Operands.insert(Operands.begin() + 1,
1477 ARMOperand::CreateCCOut(ARM::CPSR, NameLoc));
1478 MatchResult2 = MatchInstructionImpl(Operands, Inst, ErrorInfo);
1479 if (MatchResult2 == Match_Success)
1480 MatchResult = Match_Success;
1482 ARMOperand *OldMnemonic = ((ARMOperand*)Operands[0]);
1483 Operands.erase(Operands.begin());
1485 Operands.insert(Operands.begin(),
1486 ARMOperand::CreateToken(Mnemonic, NameLoc));
1487 ARMOperand *CCOut = ((ARMOperand*)Operands[1]);
1488 Operands.erase(Operands.begin() + 1);
1494 switch (MatchResult) {
1496 Out.EmitInstruction(Inst);
1498 case Match_MissingFeature:
1499 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1501 case Match_InvalidOperand: {
1502 SMLoc ErrorLoc = IDLoc;
1503 if (ErrorInfo != ~0U) {
1504 if (ErrorInfo >= Operands.size())
1505 return Error(IDLoc, "too few operands for instruction");
1507 ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc();
1508 if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
1511 return Error(ErrorLoc, "invalid operand for instruction");
1513 case Match_MnemonicFail:
1514 return Error(IDLoc, "unrecognized instruction mnemonic");
1515 case Match_ConversionFail:
1516 return Error(IDLoc, "unable to convert operands to instruction");
1519 llvm_unreachable("Implement any new match types added!");
1523 /// ParseDirective parses the arm specific directives
1524 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
1525 StringRef IDVal = DirectiveID.getIdentifier();
1526 if (IDVal == ".word")
1527 return ParseDirectiveWord(4, DirectiveID.getLoc());
1528 else if (IDVal == ".thumb")
1529 return ParseDirectiveThumb(DirectiveID.getLoc());
1530 else if (IDVal == ".thumb_func")
1531 return ParseDirectiveThumbFunc(DirectiveID.getLoc());
1532 else if (IDVal == ".code")
1533 return ParseDirectiveCode(DirectiveID.getLoc());
1534 else if (IDVal == ".syntax")
1535 return ParseDirectiveSyntax(DirectiveID.getLoc());
1539 /// ParseDirectiveWord
1540 /// ::= .word [ expression (, expression)* ]
1541 bool ARMAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1542 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1544 const MCExpr *Value;
1545 if (getParser().ParseExpression(Value))
1548 getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/);
1550 if (getLexer().is(AsmToken::EndOfStatement))
1553 // FIXME: Improve diagnostic.
1554 if (getLexer().isNot(AsmToken::Comma))
1555 return Error(L, "unexpected token in directive");
1564 /// ParseDirectiveThumb
1566 bool ARMAsmParser::ParseDirectiveThumb(SMLoc L) {
1567 if (getLexer().isNot(AsmToken::EndOfStatement))
1568 return Error(L, "unexpected token in directive");
1571 // TODO: set thumb mode
1572 // TODO: tell the MC streamer the mode
1573 // getParser().getStreamer().Emit???();
1577 /// ParseDirectiveThumbFunc
1578 /// ::= .thumbfunc symbol_name
1579 bool ARMAsmParser::ParseDirectiveThumbFunc(SMLoc L) {
1580 const AsmToken &Tok = Parser.getTok();
1581 if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
1582 return Error(L, "unexpected token in .thumb_func directive");
1583 StringRef Name = Tok.getString();
1584 Parser.Lex(); // Consume the identifier token.
1585 if (getLexer().isNot(AsmToken::EndOfStatement))
1586 return Error(L, "unexpected token in directive");
1589 // Mark symbol as a thumb symbol.
1590 MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name);
1591 getParser().getStreamer().EmitThumbFunc(Func);
1595 /// ParseDirectiveSyntax
1596 /// ::= .syntax unified | divided
1597 bool ARMAsmParser::ParseDirectiveSyntax(SMLoc L) {
1598 const AsmToken &Tok = Parser.getTok();
1599 if (Tok.isNot(AsmToken::Identifier))
1600 return Error(L, "unexpected token in .syntax directive");
1601 StringRef Mode = Tok.getString();
1602 if (Mode == "unified" || Mode == "UNIFIED")
1604 else if (Mode == "divided" || Mode == "DIVIDED")
1605 return Error(L, "'.syntax divided' arm asssembly not supported");
1607 return Error(L, "unrecognized syntax mode in .syntax directive");
1609 if (getLexer().isNot(AsmToken::EndOfStatement))
1610 return Error(Parser.getTok().getLoc(), "unexpected token in directive");
1613 // TODO tell the MC streamer the mode
1614 // getParser().getStreamer().Emit???();
1618 /// ParseDirectiveCode
1619 /// ::= .code 16 | 32
1620 bool ARMAsmParser::ParseDirectiveCode(SMLoc L) {
1621 const AsmToken &Tok = Parser.getTok();
1622 if (Tok.isNot(AsmToken::Integer))
1623 return Error(L, "unexpected token in .code directive");
1624 int64_t Val = Parser.getTok().getIntVal();
1630 return Error(L, "invalid operand to .code directive");
1632 if (getLexer().isNot(AsmToken::EndOfStatement))
1633 return Error(Parser.getTok().getLoc(), "unexpected token in directive");
1636 // FIXME: We need to be able switch subtargets at this point so that
1637 // MatchInstructionImpl() will work when it gets the AvailableFeatures which
1638 // includes Feature_IsThumb or not to match the right instructions. This is
1639 // blocked on the FIXME in llvm-mc.cpp when creating the TargetMachine.
1641 assert(TM.getSubtarget<ARMSubtarget>().isThumb() &&
1642 "switching between arm/thumb not yet suppported via .code 16)");
1643 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
1646 assert(!TM.getSubtarget<ARMSubtarget>().isThumb() &&
1647 "switching between thumb/arm not yet suppported via .code 32)");
1648 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1654 extern "C" void LLVMInitializeARMAsmLexer();
1656 /// Force static initialization.
1657 extern "C" void LLVMInitializeARMAsmParser() {
1658 RegisterAsmParser<ARMAsmParser> X(TheARMTarget);
1659 RegisterAsmParser<ARMAsmParser> Y(TheThumbTarget);
1660 LLVMInitializeARMAsmLexer();
1663 #define GET_REGISTER_MATCHER
1664 #define GET_MATCHER_IMPLEMENTATION
1665 #include "ARMGenAsmMatcher.inc"