ARMAsmParser.cpp revision 2637dc9a252f25fd1c63acfe0606860ee7c8cfdf
1//===-- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions ------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9 10#include "ARM.h" 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" 30using namespace llvm; 31 32/// Shift types used for register controlled shifts in ARM memory addressing. 33enum ShiftType { 34 Lsl, 35 Lsr, 36 Asr, 37 Ror, 38 Rrx 39}; 40 41namespace { 42 43class ARMOperand; 44 45class ARMAsmParser : public TargetAsmParser { 46 MCAsmParser &Parser; 47 TargetMachine &TM; 48 49 MCAsmParser &getParser() const { return Parser; } 50 MCAsmLexer &getLexer() const { return Parser.getLexer(); } 51 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); } 54 55 int TryParseRegister(); 56 bool TryParseMCRName(SmallVectorImpl<MCParsedAsmOperand*>&); 57 bool TryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &); 58 bool ParseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &); 59 bool ParseMemory(SmallVectorImpl<MCParsedAsmOperand*> &); 60 bool ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &, bool isMCR); 61 bool ParsePrefix(ARMMCExpr::VariantKind &RefKind); 62 const MCExpr *ApplyPrefixToExpr(const MCExpr *E, 63 MCSymbolRefExpr::VariantKind Variant); 64 65 66 bool ParseMemoryOffsetReg(bool &Negative, 67 bool &OffsetRegShifted, 68 enum ShiftType &ShiftType, 69 const MCExpr *&ShiftAmount, 70 const MCExpr *&Offset, 71 bool &OffsetIsReg, 72 int &OffsetRegNum, 73 SMLoc &E); 74 bool ParseShift(enum ShiftType &St, const MCExpr *&ShiftAmount, SMLoc &E); 75 bool ParseDirectiveWord(unsigned Size, SMLoc L); 76 bool ParseDirectiveThumb(SMLoc L); 77 bool ParseDirectiveThumbFunc(SMLoc L); 78 bool ParseDirectiveCode(SMLoc L); 79 bool ParseDirectiveSyntax(SMLoc L); 80 81 bool MatchAndEmitInstruction(SMLoc IDLoc, 82 SmallVectorImpl<MCParsedAsmOperand*> &Operands, 83 MCStreamer &Out); 84 85 /// @name Auto-generated Match Functions 86 /// { 87 88#define GET_ASSEMBLER_HEADER 89#include "ARMGenAsmMatcher.inc" 90 91 /// } 92 93public: 94 ARMAsmParser(const Target &T, MCAsmParser &_Parser, TargetMachine &_TM) 95 : TargetAsmParser(T), Parser(_Parser), TM(_TM) { 96 // Initialize the set of available features. 97 setAvailableFeatures(ComputeAvailableFeatures( 98 &TM.getSubtarget<ARMSubtarget>())); 99 } 100 101 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc, 102 SmallVectorImpl<MCParsedAsmOperand*> &Operands); 103 virtual bool ParseDirective(AsmToken DirectiveID); 104}; 105} // end anonymous namespace 106 107namespace { 108 109/// ARMOperand - Instances of this class represent a parsed ARM machine 110/// instruction. 111class ARMOperand : public MCParsedAsmOperand { 112 enum KindTy { 113 CondCode, 114 CCOut, 115 Immediate, 116 Memory, 117 Register, 118 RegisterList, 119 DPRRegisterList, 120 SPRRegisterList, 121 Token 122 } Kind; 123 124 SMLoc StartLoc, EndLoc; 125 SmallVector<unsigned, 8> Registers; 126 127 union { 128 struct { 129 ARMCC::CondCodes Val; 130 } CC; 131 132 struct { 133 const char *Data; 134 unsigned Length; 135 } Tok; 136 137 struct { 138 unsigned RegNum; 139 } Reg; 140 141 struct { 142 const MCExpr *Val; 143 } Imm; 144 145 /// Combined record for all forms of ARM address expressions. 146 struct { 147 unsigned BaseRegNum; 148 union { 149 unsigned RegNum; ///< Offset register num, when OffsetIsReg. 150 const MCExpr *Value; ///< Offset value, when !OffsetIsReg. 151 } Offset; 152 const MCExpr *ShiftAmount; // used when OffsetRegShifted is true 153 enum ShiftType ShiftType; // used when OffsetRegShifted is true 154 unsigned OffsetRegShifted : 1; // only used when OffsetIsReg is true 155 unsigned Preindexed : 1; 156 unsigned Postindexed : 1; 157 unsigned OffsetIsReg : 1; 158 unsigned Negative : 1; // only used when OffsetIsReg is true 159 unsigned Writeback : 1; 160 } Mem; 161 }; 162 163 ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {} 164public: 165 ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() { 166 Kind = o.Kind; 167 StartLoc = o.StartLoc; 168 EndLoc = o.EndLoc; 169 switch (Kind) { 170 case CondCode: 171 CC = o.CC; 172 break; 173 case Token: 174 Tok = o.Tok; 175 break; 176 case CCOut: 177 case Register: 178 Reg = o.Reg; 179 break; 180 case RegisterList: 181 case DPRRegisterList: 182 case SPRRegisterList: 183 Registers = o.Registers; 184 break; 185 case Immediate: 186 Imm = o.Imm; 187 break; 188 case Memory: 189 Mem = o.Mem; 190 break; 191 } 192 } 193 194 /// getStartLoc - Get the location of the first token of this operand. 195 SMLoc getStartLoc() const { return StartLoc; } 196 /// getEndLoc - Get the location of the last token of this operand. 197 SMLoc getEndLoc() const { return EndLoc; } 198 199 ARMCC::CondCodes getCondCode() const { 200 assert(Kind == CondCode && "Invalid access!"); 201 return CC.Val; 202 } 203 204 StringRef getToken() const { 205 assert(Kind == Token && "Invalid access!"); 206 return StringRef(Tok.Data, Tok.Length); 207 } 208 209 unsigned getReg() const { 210 assert((Kind == Register || Kind == CCOut) && "Invalid access!"); 211 return Reg.RegNum; 212 } 213 214 const SmallVectorImpl<unsigned> &getRegList() const { 215 assert((Kind == RegisterList || Kind == DPRRegisterList || 216 Kind == SPRRegisterList) && "Invalid access!"); 217 return Registers; 218 } 219 220 const MCExpr *getImm() const { 221 assert(Kind == Immediate && "Invalid access!"); 222 return Imm.Val; 223 } 224 225 bool isCondCode() const { return Kind == CondCode; } 226 bool isCCOut() const { return Kind == CCOut; } 227 bool isImm() const { return Kind == Immediate; } 228 bool isReg() const { return Kind == Register; } 229 bool isRegList() const { return Kind == RegisterList; } 230 bool isDPRRegList() const { return Kind == DPRRegisterList; } 231 bool isSPRRegList() const { return Kind == SPRRegisterList; } 232 bool isToken() const { return Kind == Token; } 233 bool isMemory() const { return Kind == Memory; } 234 bool isMemMode5() const { 235 if (!isMemory() || Mem.OffsetIsReg || Mem.OffsetRegShifted || 236 Mem.Writeback || Mem.Negative) 237 return false; 238 239 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.Offset.Value); 240 if (!CE) return false; 241 242 // The offset must be a multiple of 4 in the range 0-1020. 243 int64_t Value = CE->getValue(); 244 return ((Value & 0x3) == 0 && Value <= 1020 && Value >= -1020); 245 } 246 bool isMemModeRegThumb() const { 247 if (!isMemory() || !Mem.OffsetIsReg || Mem.Writeback) 248 return false; 249 return true; 250 } 251 bool isMemModeImmThumb() const { 252 if (!isMemory() || Mem.OffsetIsReg || Mem.Writeback) 253 return false; 254 255 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.Offset.Value); 256 if (!CE) return false; 257 258 // The offset must be a multiple of 4 in the range 0-124. 259 uint64_t Value = CE->getValue(); 260 return ((Value & 0x3) == 0 && Value <= 124); 261 } 262 263 void addExpr(MCInst &Inst, const MCExpr *Expr) const { 264 // Add as immediates when possible. Null MCExpr = 0. 265 if (Expr == 0) 266 Inst.addOperand(MCOperand::CreateImm(0)); 267 else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr)) 268 Inst.addOperand(MCOperand::CreateImm(CE->getValue())); 269 else 270 Inst.addOperand(MCOperand::CreateExpr(Expr)); 271 } 272 273 void addCondCodeOperands(MCInst &Inst, unsigned N) const { 274 assert(N == 2 && "Invalid number of operands!"); 275 Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode()))); 276 unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR; 277 Inst.addOperand(MCOperand::CreateReg(RegNum)); 278 } 279 280 void addCCOutOperands(MCInst &Inst, unsigned N) const { 281 assert(N == 1 && "Invalid number of operands!"); 282 Inst.addOperand(MCOperand::CreateReg(getReg())); 283 } 284 285 void addRegOperands(MCInst &Inst, unsigned N) const { 286 assert(N == 1 && "Invalid number of operands!"); 287 Inst.addOperand(MCOperand::CreateReg(getReg())); 288 } 289 290 void addRegListOperands(MCInst &Inst, unsigned N) const { 291 assert(N == 1 && "Invalid number of operands!"); 292 const SmallVectorImpl<unsigned> &RegList = getRegList(); 293 for (SmallVectorImpl<unsigned>::const_iterator 294 I = RegList.begin(), E = RegList.end(); I != E; ++I) 295 Inst.addOperand(MCOperand::CreateReg(*I)); 296 } 297 298 void addDPRRegListOperands(MCInst &Inst, unsigned N) const { 299 addRegListOperands(Inst, N); 300 } 301 302 void addSPRRegListOperands(MCInst &Inst, unsigned N) const { 303 addRegListOperands(Inst, N); 304 } 305 306 void addImmOperands(MCInst &Inst, unsigned N) const { 307 assert(N == 1 && "Invalid number of operands!"); 308 addExpr(Inst, getImm()); 309 } 310 311 void addMemMode5Operands(MCInst &Inst, unsigned N) const { 312 assert(N == 2 && isMemMode5() && "Invalid number of operands!"); 313 314 Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum)); 315 assert(!Mem.OffsetIsReg && "Invalid mode 5 operand"); 316 317 // FIXME: #-0 is encoded differently than #0. Does the parser preserve 318 // the difference? 319 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.Offset.Value); 320 assert(CE && "Non-constant mode 5 offset operand!"); 321 322 // The MCInst offset operand doesn't include the low two bits (like 323 // the instruction encoding). 324 int64_t Offset = CE->getValue() / 4; 325 if (Offset >= 0) 326 Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::add, 327 Offset))); 328 else 329 Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::sub, 330 -Offset))); 331 } 332 333 void addMemModeRegThumbOperands(MCInst &Inst, unsigned N) const { 334 assert(N == 2 && isMemModeRegThumb() && "Invalid number of operands!"); 335 Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum)); 336 Inst.addOperand(MCOperand::CreateReg(Mem.Offset.RegNum)); 337 } 338 339 void addMemModeImmThumbOperands(MCInst &Inst, unsigned N) const { 340 assert(N == 2 && isMemModeImmThumb() && "Invalid number of operands!"); 341 Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum)); 342 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.Offset.Value); 343 assert(CE && "Non-constant mode offset operand!"); 344 Inst.addOperand(MCOperand::CreateImm(CE->getValue())); 345 } 346 347 virtual void dump(raw_ostream &OS) const; 348 349 static ARMOperand *CreateCondCode(ARMCC::CondCodes CC, SMLoc S) { 350 ARMOperand *Op = new ARMOperand(CondCode); 351 Op->CC.Val = CC; 352 Op->StartLoc = S; 353 Op->EndLoc = S; 354 return Op; 355 } 356 357 static ARMOperand *CreateCCOut(unsigned RegNum, SMLoc S) { 358 ARMOperand *Op = new ARMOperand(CCOut); 359 Op->Reg.RegNum = RegNum; 360 Op->StartLoc = S; 361 Op->EndLoc = S; 362 return Op; 363 } 364 365 static ARMOperand *CreateToken(StringRef Str, SMLoc S) { 366 ARMOperand *Op = new ARMOperand(Token); 367 Op->Tok.Data = Str.data(); 368 Op->Tok.Length = Str.size(); 369 Op->StartLoc = S; 370 Op->EndLoc = S; 371 return Op; 372 } 373 374 static ARMOperand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) { 375 ARMOperand *Op = new ARMOperand(Register); 376 Op->Reg.RegNum = RegNum; 377 Op->StartLoc = S; 378 Op->EndLoc = E; 379 return Op; 380 } 381 382 static ARMOperand * 383 CreateRegList(const SmallVectorImpl<std::pair<unsigned, SMLoc> > &Regs, 384 SMLoc StartLoc, SMLoc EndLoc) { 385 KindTy Kind = RegisterList; 386 387 if (ARM::DPRRegClass.contains(Regs.front().first)) 388 Kind = DPRRegisterList; 389 else if (ARM::SPRRegClass.contains(Regs.front().first)) 390 Kind = SPRRegisterList; 391 392 ARMOperand *Op = new ARMOperand(Kind); 393 for (SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator 394 I = Regs.begin(), E = Regs.end(); I != E; ++I) 395 Op->Registers.push_back(I->first); 396 array_pod_sort(Op->Registers.begin(), Op->Registers.end()); 397 Op->StartLoc = StartLoc; 398 Op->EndLoc = EndLoc; 399 return Op; 400 } 401 402 static ARMOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) { 403 ARMOperand *Op = new ARMOperand(Immediate); 404 Op->Imm.Val = Val; 405 Op->StartLoc = S; 406 Op->EndLoc = E; 407 return Op; 408 } 409 410 static ARMOperand *CreateMem(unsigned BaseRegNum, bool OffsetIsReg, 411 const MCExpr *Offset, int OffsetRegNum, 412 bool OffsetRegShifted, enum ShiftType ShiftType, 413 const MCExpr *ShiftAmount, bool Preindexed, 414 bool Postindexed, bool Negative, bool Writeback, 415 SMLoc S, SMLoc E) { 416 assert((OffsetRegNum == -1 || OffsetIsReg) && 417 "OffsetRegNum must imply OffsetIsReg!"); 418 assert((!OffsetRegShifted || OffsetIsReg) && 419 "OffsetRegShifted must imply OffsetIsReg!"); 420 assert((Offset || OffsetIsReg) && 421 "Offset must exists unless register offset is used!"); 422 assert((!ShiftAmount || (OffsetIsReg && OffsetRegShifted)) && 423 "Cannot have shift amount without shifted register offset!"); 424 assert((!Offset || !OffsetIsReg) && 425 "Cannot have expression offset and register offset!"); 426 427 ARMOperand *Op = new ARMOperand(Memory); 428 Op->Mem.BaseRegNum = BaseRegNum; 429 Op->Mem.OffsetIsReg = OffsetIsReg; 430 if (OffsetIsReg) 431 Op->Mem.Offset.RegNum = OffsetRegNum; 432 else 433 Op->Mem.Offset.Value = Offset; 434 Op->Mem.OffsetRegShifted = OffsetRegShifted; 435 Op->Mem.ShiftType = ShiftType; 436 Op->Mem.ShiftAmount = ShiftAmount; 437 Op->Mem.Preindexed = Preindexed; 438 Op->Mem.Postindexed = Postindexed; 439 Op->Mem.Negative = Negative; 440 Op->Mem.Writeback = Writeback; 441 442 Op->StartLoc = S; 443 Op->EndLoc = E; 444 return Op; 445 } 446}; 447 448} // end anonymous namespace. 449 450void ARMOperand::dump(raw_ostream &OS) const { 451 switch (Kind) { 452 case CondCode: 453 OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">"; 454 break; 455 case CCOut: 456 OS << "<ccout " << getReg() << ">"; 457 break; 458 case Immediate: 459 getImm()->print(OS); 460 break; 461 case Memory: 462 OS << "<memory>"; 463 break; 464 case Register: 465 OS << "<register " << getReg() << ">"; 466 break; 467 case RegisterList: 468 case DPRRegisterList: 469 case SPRRegisterList: { 470 OS << "<register_list "; 471 472 const SmallVectorImpl<unsigned> &RegList = getRegList(); 473 for (SmallVectorImpl<unsigned>::const_iterator 474 I = RegList.begin(), E = RegList.end(); I != E; ) { 475 OS << *I; 476 if (++I < E) OS << ", "; 477 } 478 479 OS << ">"; 480 break; 481 } 482 case Token: 483 OS << "'" << getToken() << "'"; 484 break; 485 } 486} 487 488/// @name Auto-generated Match Functions 489/// { 490 491static unsigned MatchRegisterName(StringRef Name); 492 493/// } 494 495/// Try to parse a register name. The token must be an Identifier when called, 496/// and if it is a register name the token is eaten and the register number is 497/// returned. Otherwise return -1. 498/// 499int ARMAsmParser::TryParseRegister() { 500 const AsmToken &Tok = Parser.getTok(); 501 assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier"); 502 503 // FIXME: Validate register for the current architecture; we have to do 504 // validation later, so maybe there is no need for this here. 505 std::string upperCase = Tok.getString().str(); 506 std::string lowerCase = LowercaseString(upperCase); 507 unsigned RegNum = MatchRegisterName(lowerCase); 508 if (!RegNum) { 509 RegNum = StringSwitch<unsigned>(lowerCase) 510 .Case("r13", ARM::SP) 511 .Case("r14", ARM::LR) 512 .Case("r15", ARM::PC) 513 .Case("ip", ARM::R12) 514 .Default(0); 515 } 516 if (!RegNum) return -1; 517 518 Parser.Lex(); // Eat identifier token. 519 return RegNum; 520} 521 522 523/// Try to parse a register name. The token must be an Identifier when called. 524/// If it's a register, an AsmOperand is created. Another AsmOperand is created 525/// if there is a "writeback". 'true' if it's not a register. 526/// 527/// TODO this is likely to change to allow different register types and or to 528/// parse for a specific register type. 529bool ARMAsmParser:: 530TryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &Operands) { 531 SMLoc S = Parser.getTok().getLoc(); 532 int RegNo = TryParseRegister(); 533 if (RegNo == -1) 534 return true; 535 536 Operands.push_back(ARMOperand::CreateReg(RegNo, S, Parser.getTok().getLoc())); 537 538 const AsmToken &ExclaimTok = Parser.getTok(); 539 if (ExclaimTok.is(AsmToken::Exclaim)) { 540 Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(), 541 ExclaimTok.getLoc())); 542 Parser.Lex(); // Eat exclaim token 543 } 544 545 return false; 546} 547 548static int MatchMCRName(StringRef Name) { 549 // Use the same layout as the tablegen'erated register name matcher. Ugly, 550 // but efficient. 551 switch (Name.size()) { 552 default: break; 553 case 2: 554 if (Name[0] != 'p' && Name[0] != 'c') 555 return -1; 556 switch (Name[1]) { 557 default: return -1; 558 case '0': return 0; 559 case '1': return 1; 560 case '2': return 2; 561 case '3': return 3; 562 case '4': return 4; 563 case '5': return 5; 564 case '6': return 6; 565 case '7': return 7; 566 case '8': return 8; 567 case '9': return 9; 568 } 569 break; 570 case 3: 571 if ((Name[0] != 'p' && Name[0] != 'c') || Name[1] != '1') 572 return -1; 573 switch (Name[2]) { 574 default: return -1; 575 case '0': return 10; 576 case '1': return 11; 577 case '2': return 12; 578 case '3': return 13; 579 case '4': return 14; 580 case '5': return 15; 581 } 582 break; 583 } 584 585 llvm_unreachable("Unhandled coprocessor operand string!"); 586 return -1; 587} 588 589/// TryParseMCRName - Try to parse an MCR/MRC symbolic operand 590/// name. The token must be an Identifier when called, and if it is a MCR 591/// operand name, the token is eaten and the operand is added to the 592/// operand list. 593bool ARMAsmParser:: 594TryParseMCRName(SmallVectorImpl<MCParsedAsmOperand*> &Operands) { 595 SMLoc S = Parser.getTok().getLoc(); 596 const AsmToken &Tok = Parser.getTok(); 597 assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier"); 598 599 int Num = MatchMCRName(Tok.getString()); 600 if (Num == -1) 601 return true; 602 603 Parser.Lex(); // Eat identifier token. 604 Operands.push_back(ARMOperand::CreateImm( 605 MCConstantExpr::Create(Num, getContext()), S, Parser.getTok().getLoc())); 606 return false; 607} 608 609/// Parse a register list, return it if successful else return null. The first 610/// token must be a '{' when called. 611bool ARMAsmParser:: 612ParseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) { 613 assert(Parser.getTok().is(AsmToken::LCurly) && 614 "Token is not a Left Curly Brace"); 615 SMLoc S = Parser.getTok().getLoc(); 616 617 // Read the rest of the registers in the list. 618 unsigned PrevRegNum = 0; 619 SmallVector<std::pair<unsigned, SMLoc>, 32> Registers; 620 621 do { 622 bool IsRange = Parser.getTok().is(AsmToken::Minus); 623 Parser.Lex(); // Eat non-identifier token. 624 625 const AsmToken &RegTok = Parser.getTok(); 626 SMLoc RegLoc = RegTok.getLoc(); 627 if (RegTok.isNot(AsmToken::Identifier)) { 628 Error(RegLoc, "register expected"); 629 return true; 630 } 631 632 int RegNum = TryParseRegister(); 633 if (RegNum == -1) { 634 Error(RegLoc, "register expected"); 635 return true; 636 } 637 638 if (IsRange) { 639 int Reg = PrevRegNum; 640 do { 641 ++Reg; 642 Registers.push_back(std::make_pair(Reg, RegLoc)); 643 } while (Reg != RegNum); 644 } else { 645 Registers.push_back(std::make_pair(RegNum, RegLoc)); 646 } 647 648 PrevRegNum = RegNum; 649 } while (Parser.getTok().is(AsmToken::Comma) || 650 Parser.getTok().is(AsmToken::Minus)); 651 652 // Process the right curly brace of the list. 653 const AsmToken &RCurlyTok = Parser.getTok(); 654 if (RCurlyTok.isNot(AsmToken::RCurly)) { 655 Error(RCurlyTok.getLoc(), "'}' expected"); 656 return true; 657 } 658 659 SMLoc E = RCurlyTok.getLoc(); 660 Parser.Lex(); // Eat right curly brace token. 661 662 // Verify the register list. 663 SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator 664 RI = Registers.begin(), RE = Registers.end(); 665 666 unsigned HighRegNum = getARMRegisterNumbering(RI->first); 667 bool EmittedWarning = false; 668 669 DenseMap<unsigned, bool> RegMap; 670 RegMap[HighRegNum] = true; 671 672 for (++RI; RI != RE; ++RI) { 673 const std::pair<unsigned, SMLoc> &RegInfo = *RI; 674 unsigned Reg = getARMRegisterNumbering(RegInfo.first); 675 676 if (RegMap[Reg]) { 677 Error(RegInfo.second, "register duplicated in register list"); 678 return true; 679 } 680 681 if (!EmittedWarning && Reg < HighRegNum) 682 Warning(RegInfo.second, 683 "register not in ascending order in register list"); 684 685 RegMap[Reg] = true; 686 HighRegNum = std::max(Reg, HighRegNum); 687 } 688 689 Operands.push_back(ARMOperand::CreateRegList(Registers, S, E)); 690 return false; 691} 692 693/// Parse an ARM memory expression, return false if successful else return true 694/// or an error. The first token must be a '[' when called. 695/// 696/// TODO Only preindexing and postindexing addressing are started, unindexed 697/// with option, etc are still to do. 698bool ARMAsmParser:: 699ParseMemory(SmallVectorImpl<MCParsedAsmOperand*> &Operands) { 700 SMLoc S, E; 701 assert(Parser.getTok().is(AsmToken::LBrac) && 702 "Token is not a Left Bracket"); 703 S = Parser.getTok().getLoc(); 704 Parser.Lex(); // Eat left bracket token. 705 706 const AsmToken &BaseRegTok = Parser.getTok(); 707 if (BaseRegTok.isNot(AsmToken::Identifier)) { 708 Error(BaseRegTok.getLoc(), "register expected"); 709 return true; 710 } 711 int BaseRegNum = TryParseRegister(); 712 if (BaseRegNum == -1) { 713 Error(BaseRegTok.getLoc(), "register expected"); 714 return true; 715 } 716 717 // The next token must either be a comma or a closing bracket. 718 const AsmToken &Tok = Parser.getTok(); 719 if (!Tok.is(AsmToken::Comma) && !Tok.is(AsmToken::RBrac)) 720 return true; 721 722 bool Preindexed = false; 723 bool Postindexed = false; 724 bool OffsetIsReg = false; 725 bool Negative = false; 726 bool Writeback = false; 727 ARMOperand *WBOp = 0; 728 int OffsetRegNum = -1; 729 bool OffsetRegShifted = false; 730 enum ShiftType ShiftType = Lsl; 731 const MCExpr *ShiftAmount = 0; 732 const MCExpr *Offset = 0; 733 734 // First look for preindexed address forms, that is after the "[Rn" we now 735 // have to see if the next token is a comma. 736 if (Tok.is(AsmToken::Comma)) { 737 Preindexed = true; 738 Parser.Lex(); // Eat comma token. 739 740 if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType, ShiftAmount, 741 Offset, OffsetIsReg, OffsetRegNum, E)) 742 return true; 743 const AsmToken &RBracTok = Parser.getTok(); 744 if (RBracTok.isNot(AsmToken::RBrac)) { 745 Error(RBracTok.getLoc(), "']' expected"); 746 return true; 747 } 748 E = RBracTok.getLoc(); 749 Parser.Lex(); // Eat right bracket token. 750 751 const AsmToken &ExclaimTok = Parser.getTok(); 752 if (ExclaimTok.is(AsmToken::Exclaim)) { 753 WBOp = ARMOperand::CreateToken(ExclaimTok.getString(), 754 ExclaimTok.getLoc()); 755 Writeback = true; 756 Parser.Lex(); // Eat exclaim token 757 } 758 } else { 759 // The "[Rn" we have so far was not followed by a comma. 760 761 // If there's anything other than the right brace, this is a post indexing 762 // addressing form. 763 E = Tok.getLoc(); 764 Parser.Lex(); // Eat right bracket token. 765 766 const AsmToken &NextTok = Parser.getTok(); 767 768 if (NextTok.isNot(AsmToken::EndOfStatement)) { 769 Postindexed = true; 770 Writeback = true; 771 772 if (NextTok.isNot(AsmToken::Comma)) { 773 Error(NextTok.getLoc(), "',' expected"); 774 return true; 775 } 776 777 Parser.Lex(); // Eat comma token. 778 779 if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType, 780 ShiftAmount, Offset, OffsetIsReg, OffsetRegNum, 781 E)) 782 return true; 783 } 784 } 785 786 // Force Offset to exist if used. 787 if (!OffsetIsReg) { 788 if (!Offset) 789 Offset = MCConstantExpr::Create(0, getContext()); 790 } 791 792 Operands.push_back(ARMOperand::CreateMem(BaseRegNum, OffsetIsReg, Offset, 793 OffsetRegNum, OffsetRegShifted, 794 ShiftType, ShiftAmount, Preindexed, 795 Postindexed, Negative, Writeback, 796 S, E)); 797 if (WBOp) 798 Operands.push_back(WBOp); 799 800 return false; 801} 802 803/// Parse the offset of a memory operand after we have seen "[Rn," or "[Rn]," 804/// we will parse the following (were +/- means that a plus or minus is 805/// optional): 806/// +/-Rm 807/// +/-Rm, shift 808/// #offset 809/// we return false on success or an error otherwise. 810bool ARMAsmParser::ParseMemoryOffsetReg(bool &Negative, 811 bool &OffsetRegShifted, 812 enum ShiftType &ShiftType, 813 const MCExpr *&ShiftAmount, 814 const MCExpr *&Offset, 815 bool &OffsetIsReg, 816 int &OffsetRegNum, 817 SMLoc &E) { 818 Negative = false; 819 OffsetRegShifted = false; 820 OffsetIsReg = false; 821 OffsetRegNum = -1; 822 const AsmToken &NextTok = Parser.getTok(); 823 E = NextTok.getLoc(); 824 if (NextTok.is(AsmToken::Plus)) 825 Parser.Lex(); // Eat plus token. 826 else if (NextTok.is(AsmToken::Minus)) { 827 Negative = true; 828 Parser.Lex(); // Eat minus token 829 } 830 // See if there is a register following the "[Rn," or "[Rn]," we have so far. 831 const AsmToken &OffsetRegTok = Parser.getTok(); 832 if (OffsetRegTok.is(AsmToken::Identifier)) { 833 SMLoc CurLoc = OffsetRegTok.getLoc(); 834 OffsetRegNum = TryParseRegister(); 835 if (OffsetRegNum != -1) { 836 OffsetIsReg = true; 837 E = CurLoc; 838 } 839 } 840 841 // If we parsed a register as the offset then there can be a shift after that. 842 if (OffsetRegNum != -1) { 843 // Look for a comma then a shift 844 const AsmToken &Tok = Parser.getTok(); 845 if (Tok.is(AsmToken::Comma)) { 846 Parser.Lex(); // Eat comma token. 847 848 const AsmToken &Tok = Parser.getTok(); 849 if (ParseShift(ShiftType, ShiftAmount, E)) 850 return Error(Tok.getLoc(), "shift expected"); 851 OffsetRegShifted = true; 852 } 853 } 854 else { // the "[Rn," or "[Rn,]" we have so far was not followed by "Rm" 855 // Look for #offset following the "[Rn," or "[Rn]," 856 const AsmToken &HashTok = Parser.getTok(); 857 if (HashTok.isNot(AsmToken::Hash)) 858 return Error(HashTok.getLoc(), "'#' expected"); 859 860 Parser.Lex(); // Eat hash token. 861 862 if (getParser().ParseExpression(Offset)) 863 return true; 864 E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1); 865 } 866 return false; 867} 868 869/// ParseShift as one of these two: 870/// ( lsl | lsr | asr | ror ) , # shift_amount 871/// rrx 872/// and returns true if it parses a shift otherwise it returns false. 873bool ARMAsmParser::ParseShift(ShiftType &St, const MCExpr *&ShiftAmount, 874 SMLoc &E) { 875 const AsmToken &Tok = Parser.getTok(); 876 if (Tok.isNot(AsmToken::Identifier)) 877 return true; 878 StringRef ShiftName = Tok.getString(); 879 if (ShiftName == "lsl" || ShiftName == "LSL") 880 St = Lsl; 881 else if (ShiftName == "lsr" || ShiftName == "LSR") 882 St = Lsr; 883 else if (ShiftName == "asr" || ShiftName == "ASR") 884 St = Asr; 885 else if (ShiftName == "ror" || ShiftName == "ROR") 886 St = Ror; 887 else if (ShiftName == "rrx" || ShiftName == "RRX") 888 St = Rrx; 889 else 890 return true; 891 Parser.Lex(); // Eat shift type token. 892 893 // Rrx stands alone. 894 if (St == Rrx) 895 return false; 896 897 // Otherwise, there must be a '#' and a shift amount. 898 const AsmToken &HashTok = Parser.getTok(); 899 if (HashTok.isNot(AsmToken::Hash)) 900 return Error(HashTok.getLoc(), "'#' expected"); 901 Parser.Lex(); // Eat hash token. 902 903 if (getParser().ParseExpression(ShiftAmount)) 904 return true; 905 906 return false; 907} 908 909/// Parse a arm instruction operand. For now this parses the operand regardless 910/// of the mnemonic. 911bool ARMAsmParser::ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands, 912 bool isMCR){ 913 SMLoc S, E; 914 switch (getLexer().getKind()) { 915 default: 916 Error(Parser.getTok().getLoc(), "unexpected token in operand"); 917 return true; 918 case AsmToken::Identifier: 919 if (!TryParseRegisterWithWriteBack(Operands)) 920 return false; 921 if (isMCR && !TryParseMCRName(Operands)) 922 return false; 923 924 // Fall though for the Identifier case that is not a register or a 925 // special name. 926 case AsmToken::Integer: // things like 1f and 2b as a branch targets 927 case AsmToken::Dot: { // . as a branch target 928 // This was not a register so parse other operands that start with an 929 // identifier (like labels) as expressions and create them as immediates. 930 const MCExpr *IdVal; 931 S = Parser.getTok().getLoc(); 932 if (getParser().ParseExpression(IdVal)) 933 return true; 934 E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1); 935 Operands.push_back(ARMOperand::CreateImm(IdVal, S, E)); 936 return false; 937 } 938 case AsmToken::LBrac: 939 return ParseMemory(Operands); 940 case AsmToken::LCurly: 941 return ParseRegisterList(Operands); 942 case AsmToken::Hash: 943 // #42 -> immediate. 944 // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate 945 S = Parser.getTok().getLoc(); 946 Parser.Lex(); 947 const MCExpr *ImmVal; 948 if (getParser().ParseExpression(ImmVal)) 949 return true; 950 E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1); 951 Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E)); 952 return false; 953 case AsmToken::Colon: { 954 // ":lower16:" and ":upper16:" expression prefixes 955 // FIXME: Check it's an expression prefix, 956 // e.g. (FOO - :lower16:BAR) isn't legal. 957 ARMMCExpr::VariantKind RefKind; 958 if (ParsePrefix(RefKind)) 959 return true; 960 961 const MCExpr *SubExprVal; 962 if (getParser().ParseExpression(SubExprVal)) 963 return true; 964 965 const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal, 966 getContext()); 967 E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1); 968 Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E)); 969 return false; 970 } 971 } 972} 973 974// ParsePrefix - Parse ARM 16-bit relocations expression prefix, i.e. 975// :lower16: and :upper16:. 976bool ARMAsmParser::ParsePrefix(ARMMCExpr::VariantKind &RefKind) { 977 RefKind = ARMMCExpr::VK_ARM_None; 978 979 // :lower16: and :upper16: modifiers 980 assert(getLexer().is(AsmToken::Colon) && "expected a :"); 981 Parser.Lex(); // Eat ':' 982 983 if (getLexer().isNot(AsmToken::Identifier)) { 984 Error(Parser.getTok().getLoc(), "expected prefix identifier in operand"); 985 return true; 986 } 987 988 StringRef IDVal = Parser.getTok().getIdentifier(); 989 if (IDVal == "lower16") { 990 RefKind = ARMMCExpr::VK_ARM_LO16; 991 } else if (IDVal == "upper16") { 992 RefKind = ARMMCExpr::VK_ARM_HI16; 993 } else { 994 Error(Parser.getTok().getLoc(), "unexpected prefix in operand"); 995 return true; 996 } 997 Parser.Lex(); 998 999 if (getLexer().isNot(AsmToken::Colon)) { 1000 Error(Parser.getTok().getLoc(), "unexpected token after prefix"); 1001 return true; 1002 } 1003 Parser.Lex(); // Eat the last ':' 1004 return false; 1005} 1006 1007const MCExpr * 1008ARMAsmParser::ApplyPrefixToExpr(const MCExpr *E, 1009 MCSymbolRefExpr::VariantKind Variant) { 1010 // Recurse over the given expression, rebuilding it to apply the given variant 1011 // to the leftmost symbol. 1012 if (Variant == MCSymbolRefExpr::VK_None) 1013 return E; 1014 1015 switch (E->getKind()) { 1016 case MCExpr::Target: 1017 llvm_unreachable("Can't handle target expr yet"); 1018 case MCExpr::Constant: 1019 llvm_unreachable("Can't handle lower16/upper16 of constant yet"); 1020 1021 case MCExpr::SymbolRef: { 1022 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E); 1023 1024 if (SRE->getKind() != MCSymbolRefExpr::VK_None) 1025 return 0; 1026 1027 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext()); 1028 } 1029 1030 case MCExpr::Unary: 1031 llvm_unreachable("Can't handle unary expressions yet"); 1032 1033 case MCExpr::Binary: { 1034 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E); 1035 const MCExpr *LHS = ApplyPrefixToExpr(BE->getLHS(), Variant); 1036 const MCExpr *RHS = BE->getRHS(); 1037 if (!LHS) 1038 return 0; 1039 1040 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext()); 1041 } 1042 } 1043 1044 assert(0 && "Invalid expression kind!"); 1045 return 0; 1046} 1047 1048/// \brief Given a mnemonic, split out possible predication code and carry 1049/// setting letters to form a canonical mnemonic and flags. 1050// 1051// FIXME: Would be nice to autogen this. 1052static StringRef SplitMnemonicAndCC(StringRef Mnemonic, 1053 unsigned &PredicationCode, 1054 bool &CarrySetting) { 1055 PredicationCode = ARMCC::AL; 1056 CarrySetting = false; 1057 1058 // Ignore some mnemonics we know aren't predicated forms. 1059 // 1060 // FIXME: Would be nice to autogen this. 1061 if (Mnemonic == "teq" || Mnemonic == "vceq" || 1062 Mnemonic == "movs" || 1063 Mnemonic == "svc" || 1064 (Mnemonic == "mls" || Mnemonic == "smmls" || Mnemonic == "vcls" || 1065 Mnemonic == "vmls" || Mnemonic == "vnmls") || 1066 Mnemonic == "vacge" || Mnemonic == "vcge" || 1067 Mnemonic == "vclt" || 1068 Mnemonic == "vacgt" || Mnemonic == "vcgt" || 1069 Mnemonic == "vcle" || 1070 (Mnemonic == "smlal" || Mnemonic == "umaal" || Mnemonic == "umlal" || 1071 Mnemonic == "vabal" || Mnemonic == "vmlal" || Mnemonic == "vpadal" || 1072 Mnemonic == "vqdmlal")) 1073 return Mnemonic; 1074 1075 // First, split out any predication code. 1076 unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2)) 1077 .Case("eq", ARMCC::EQ) 1078 .Case("ne", ARMCC::NE) 1079 .Case("hs", ARMCC::HS) 1080 .Case("lo", ARMCC::LO) 1081 .Case("mi", ARMCC::MI) 1082 .Case("pl", ARMCC::PL) 1083 .Case("vs", ARMCC::VS) 1084 .Case("vc", ARMCC::VC) 1085 .Case("hi", ARMCC::HI) 1086 .Case("ls", ARMCC::LS) 1087 .Case("ge", ARMCC::GE) 1088 .Case("lt", ARMCC::LT) 1089 .Case("gt", ARMCC::GT) 1090 .Case("le", ARMCC::LE) 1091 .Case("al", ARMCC::AL) 1092 .Default(~0U); 1093 if (CC != ~0U) { 1094 Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2); 1095 PredicationCode = CC; 1096 } 1097 1098 // Next, determine if we have a carry setting bit. We explicitly ignore all 1099 // the instructions we know end in 's'. 1100 if (Mnemonic.endswith("s") && 1101 !(Mnemonic == "asrs" || Mnemonic == "cps" || Mnemonic == "mls" || 1102 Mnemonic == "movs" || Mnemonic == "mrs" || Mnemonic == "smmls" || 1103 Mnemonic == "vabs" || Mnemonic == "vcls" || Mnemonic == "vmls" || 1104 Mnemonic == "vmrs" || Mnemonic == "vnmls" || Mnemonic == "vqabs" || 1105 Mnemonic == "vrecps" || Mnemonic == "vrsqrts")) { 1106 Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1); 1107 CarrySetting = true; 1108 } 1109 1110 return Mnemonic; 1111} 1112 1113/// \brief Given a canonical mnemonic, determine if the instruction ever allows 1114/// inclusion of carry set or predication code operands. 1115// 1116// FIXME: It would be nice to autogen this. 1117static void GetMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet, 1118 bool &CanAcceptPredicationCode) { 1119 if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" || 1120 Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" || 1121 Mnemonic == "smull" || Mnemonic == "add" || Mnemonic == "adc" || 1122 Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" || 1123 Mnemonic == "umlal" || Mnemonic == "orr" || Mnemonic == "mov" || 1124 Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" || 1125 Mnemonic == "sbc" || Mnemonic == "mla" || Mnemonic == "umull" || 1126 Mnemonic == "eor" || Mnemonic == "smlal" || Mnemonic == "mvn") { 1127 CanAcceptCarrySet = true; 1128 } else { 1129 CanAcceptCarrySet = false; 1130 } 1131 1132 if (Mnemonic == "cbnz" || Mnemonic == "setend" || Mnemonic == "dmb" || 1133 Mnemonic == "cps" || Mnemonic == "mcr2" || Mnemonic == "it" || 1134 Mnemonic == "mcrr2" || Mnemonic == "cbz" || Mnemonic == "cdp2" || 1135 Mnemonic == "trap" || Mnemonic == "mrc2" || Mnemonic == "mrrc2" || 1136 Mnemonic == "dsb" || Mnemonic == "movs") { 1137 CanAcceptPredicationCode = false; 1138 } else { 1139 CanAcceptPredicationCode = true; 1140 } 1141} 1142 1143/// Parse an arm instruction mnemonic followed by its operands. 1144bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc, 1145 SmallVectorImpl<MCParsedAsmOperand*> &Operands) { 1146 // Create the leading tokens for the mnemonic, split by '.' characters. 1147 size_t Start = 0, Next = Name.find('.'); 1148 StringRef Head = Name.slice(Start, Next); 1149 1150 // Split out the predication code and carry setting flag from the mnemonic. 1151 unsigned PredicationCode; 1152 bool CarrySetting; 1153 Head = SplitMnemonicAndCC(Head, PredicationCode, CarrySetting); 1154 1155 Operands.push_back(ARMOperand::CreateToken(Head, NameLoc)); 1156 1157 // Next, add the CCOut and ConditionCode operands, if needed. 1158 // 1159 // For mnemonics which can ever incorporate a carry setting bit or predication 1160 // code, our matching model involves us always generating CCOut and 1161 // ConditionCode operands to match the mnemonic "as written" and then we let 1162 // the matcher deal with finding the right instruction or generating an 1163 // appropriate error. 1164 bool CanAcceptCarrySet, CanAcceptPredicationCode; 1165 GetMnemonicAcceptInfo(Head, CanAcceptCarrySet, CanAcceptPredicationCode); 1166 1167 // Add the carry setting operand, if necessary. 1168 // 1169 // FIXME: It would be awesome if we could somehow invent a location such that 1170 // match errors on this operand would print a nice diagnostic about how the 1171 // 's' character in the mnemonic resulted in a CCOut operand. 1172 if (CanAcceptCarrySet) { 1173 Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0, 1174 NameLoc)); 1175 } else { 1176 // This mnemonic can't ever accept a carry set, but the user wrote one (or 1177 // misspelled another mnemonic). 1178 1179 // FIXME: Issue a nice error. 1180 } 1181 1182 // Add the predication code operand, if necessary. 1183 if (CanAcceptPredicationCode) { 1184 Operands.push_back(ARMOperand::CreateCondCode( 1185 ARMCC::CondCodes(PredicationCode), NameLoc)); 1186 } else { 1187 // This mnemonic can't ever accept a predication code, but the user wrote 1188 // one (or misspelled another mnemonic). 1189 1190 // FIXME: Issue a nice error. 1191 } 1192 1193 // Add the remaining tokens in the mnemonic. 1194 while (Next != StringRef::npos) { 1195 Start = Next; 1196 Next = Name.find('.', Start + 1); 1197 Head = Name.slice(Start, Next); 1198 1199 Operands.push_back(ARMOperand::CreateToken(Head, NameLoc)); 1200 } 1201 1202 bool isMCR = (Head == "mcr" || Head == "mcr2" || 1203 Head == "mcrr" || Head == "mcrr2" || 1204 Head == "mrc" || Head == "mrc2" || 1205 Head == "mrrc" || Head == "mrrc2"); 1206 1207 // Read the remaining operands. 1208 if (getLexer().isNot(AsmToken::EndOfStatement)) { 1209 // Read the first operand. 1210 if (ParseOperand(Operands, isMCR)) { 1211 Parser.EatToEndOfStatement(); 1212 return true; 1213 } 1214 1215 while (getLexer().is(AsmToken::Comma)) { 1216 Parser.Lex(); // Eat the comma. 1217 1218 // Parse and remember the operand. 1219 if (ParseOperand(Operands, isMCR)) { 1220 Parser.EatToEndOfStatement(); 1221 return true; 1222 } 1223 } 1224 } 1225 1226 if (getLexer().isNot(AsmToken::EndOfStatement)) { 1227 Parser.EatToEndOfStatement(); 1228 return TokError("unexpected token in argument list"); 1229 } 1230 1231 Parser.Lex(); // Consume the EndOfStatement 1232 return false; 1233} 1234 1235bool ARMAsmParser:: 1236MatchAndEmitInstruction(SMLoc IDLoc, 1237 SmallVectorImpl<MCParsedAsmOperand*> &Operands, 1238 MCStreamer &Out) { 1239 MCInst Inst; 1240 unsigned ErrorInfo; 1241 MatchResultTy MatchResult, MatchResult2; 1242 MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo); 1243 if (MatchResult != Match_Success) { 1244 // If we get a Match_InvalidOperand it might be some arithmetic instruction 1245 // that does not update the condition codes. So try adding a CCOut operand 1246 // with a value of reg0. 1247 if (MatchResult == Match_InvalidOperand) { 1248 Operands.insert(Operands.begin() + 1, 1249 ARMOperand::CreateCCOut(0, 1250 ((ARMOperand*)Operands[0])->getStartLoc())); 1251 MatchResult2 = MatchInstructionImpl(Operands, Inst, ErrorInfo); 1252 if (MatchResult2 == Match_Success) 1253 MatchResult = Match_Success; 1254 else { 1255 ARMOperand *CCOut = ((ARMOperand*)Operands[1]); 1256 Operands.erase(Operands.begin() + 1); 1257 delete CCOut; 1258 } 1259 } 1260 // If we get a Match_MnemonicFail it might be some arithmetic instruction 1261 // that updates the condition codes if it ends in 's'. So see if the 1262 // mnemonic ends in 's' and if so try removing the 's' and adding a CCOut 1263 // operand with a value of CPSR. 1264 else if(MatchResult == Match_MnemonicFail) { 1265 // Get the instruction mnemonic, which is the first token. 1266 StringRef Mnemonic = ((ARMOperand*)Operands[0])->getToken(); 1267 if (Mnemonic.substr(Mnemonic.size()-1) == "s") { 1268 // removed the 's' from the mnemonic for matching. 1269 StringRef MnemonicNoS = Mnemonic.slice(0, Mnemonic.size() - 1); 1270 SMLoc NameLoc = ((ARMOperand*)Operands[0])->getStartLoc(); 1271 ARMOperand *OldMnemonic = ((ARMOperand*)Operands[0]); 1272 Operands.erase(Operands.begin()); 1273 delete OldMnemonic; 1274 Operands.insert(Operands.begin(), 1275 ARMOperand::CreateToken(MnemonicNoS, NameLoc)); 1276 Operands.insert(Operands.begin() + 1, 1277 ARMOperand::CreateCCOut(ARM::CPSR, NameLoc)); 1278 MatchResult2 = MatchInstructionImpl(Operands, Inst, ErrorInfo); 1279 if (MatchResult2 == Match_Success) 1280 MatchResult = Match_Success; 1281 else { 1282 ARMOperand *OldMnemonic = ((ARMOperand*)Operands[0]); 1283 Operands.erase(Operands.begin()); 1284 delete OldMnemonic; 1285 Operands.insert(Operands.begin(), 1286 ARMOperand::CreateToken(Mnemonic, NameLoc)); 1287 ARMOperand *CCOut = ((ARMOperand*)Operands[1]); 1288 Operands.erase(Operands.begin() + 1); 1289 delete CCOut; 1290 } 1291 } 1292 } 1293 } 1294 switch (MatchResult) { 1295 case Match_Success: 1296 Out.EmitInstruction(Inst); 1297 return false; 1298 case Match_MissingFeature: 1299 Error(IDLoc, "instruction requires a CPU feature not currently enabled"); 1300 return true; 1301 case Match_InvalidOperand: { 1302 SMLoc ErrorLoc = IDLoc; 1303 if (ErrorInfo != ~0U) { 1304 if (ErrorInfo >= Operands.size()) 1305 return Error(IDLoc, "too few operands for instruction"); 1306 1307 ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc(); 1308 if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc; 1309 } 1310 1311 return Error(ErrorLoc, "invalid operand for instruction"); 1312 } 1313 case Match_MnemonicFail: 1314 return Error(IDLoc, "unrecognized instruction mnemonic"); 1315 } 1316 1317 llvm_unreachable("Implement any new match types added!"); 1318 return true; 1319} 1320 1321/// ParseDirective parses the arm specific directives 1322bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) { 1323 StringRef IDVal = DirectiveID.getIdentifier(); 1324 if (IDVal == ".word") 1325 return ParseDirectiveWord(4, DirectiveID.getLoc()); 1326 else if (IDVal == ".thumb") 1327 return ParseDirectiveThumb(DirectiveID.getLoc()); 1328 else if (IDVal == ".thumb_func") 1329 return ParseDirectiveThumbFunc(DirectiveID.getLoc()); 1330 else if (IDVal == ".code") 1331 return ParseDirectiveCode(DirectiveID.getLoc()); 1332 else if (IDVal == ".syntax") 1333 return ParseDirectiveSyntax(DirectiveID.getLoc()); 1334 return true; 1335} 1336 1337/// ParseDirectiveWord 1338/// ::= .word [ expression (, expression)* ] 1339bool ARMAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) { 1340 if (getLexer().isNot(AsmToken::EndOfStatement)) { 1341 for (;;) { 1342 const MCExpr *Value; 1343 if (getParser().ParseExpression(Value)) 1344 return true; 1345 1346 getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/); 1347 1348 if (getLexer().is(AsmToken::EndOfStatement)) 1349 break; 1350 1351 // FIXME: Improve diagnostic. 1352 if (getLexer().isNot(AsmToken::Comma)) 1353 return Error(L, "unexpected token in directive"); 1354 Parser.Lex(); 1355 } 1356 } 1357 1358 Parser.Lex(); 1359 return false; 1360} 1361 1362/// ParseDirectiveThumb 1363/// ::= .thumb 1364bool ARMAsmParser::ParseDirectiveThumb(SMLoc L) { 1365 if (getLexer().isNot(AsmToken::EndOfStatement)) 1366 return Error(L, "unexpected token in directive"); 1367 Parser.Lex(); 1368 1369 // TODO: set thumb mode 1370 // TODO: tell the MC streamer the mode 1371 // getParser().getStreamer().Emit???(); 1372 return false; 1373} 1374 1375/// ParseDirectiveThumbFunc 1376/// ::= .thumbfunc symbol_name 1377bool ARMAsmParser::ParseDirectiveThumbFunc(SMLoc L) { 1378 const AsmToken &Tok = Parser.getTok(); 1379 if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String)) 1380 return Error(L, "unexpected token in .thumb_func directive"); 1381 StringRef Name = Tok.getString(); 1382 Parser.Lex(); // Consume the identifier token. 1383 if (getLexer().isNot(AsmToken::EndOfStatement)) 1384 return Error(L, "unexpected token in directive"); 1385 Parser.Lex(); 1386 1387 // Mark symbol as a thumb symbol. 1388 MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name); 1389 getParser().getStreamer().EmitThumbFunc(Func); 1390 return false; 1391} 1392 1393/// ParseDirectiveSyntax 1394/// ::= .syntax unified | divided 1395bool ARMAsmParser::ParseDirectiveSyntax(SMLoc L) { 1396 const AsmToken &Tok = Parser.getTok(); 1397 if (Tok.isNot(AsmToken::Identifier)) 1398 return Error(L, "unexpected token in .syntax directive"); 1399 StringRef Mode = Tok.getString(); 1400 if (Mode == "unified" || Mode == "UNIFIED") 1401 Parser.Lex(); 1402 else if (Mode == "divided" || Mode == "DIVIDED") 1403 Parser.Lex(); 1404 else 1405 return Error(L, "unrecognized syntax mode in .syntax directive"); 1406 1407 if (getLexer().isNot(AsmToken::EndOfStatement)) 1408 return Error(Parser.getTok().getLoc(), "unexpected token in directive"); 1409 Parser.Lex(); 1410 1411 // TODO tell the MC streamer the mode 1412 // getParser().getStreamer().Emit???(); 1413 return false; 1414} 1415 1416/// ParseDirectiveCode 1417/// ::= .code 16 | 32 1418bool ARMAsmParser::ParseDirectiveCode(SMLoc L) { 1419 const AsmToken &Tok = Parser.getTok(); 1420 if (Tok.isNot(AsmToken::Integer)) 1421 return Error(L, "unexpected token in .code directive"); 1422 int64_t Val = Parser.getTok().getIntVal(); 1423 if (Val == 16) 1424 Parser.Lex(); 1425 else if (Val == 32) 1426 Parser.Lex(); 1427 else 1428 return Error(L, "invalid operand to .code directive"); 1429 1430 if (getLexer().isNot(AsmToken::EndOfStatement)) 1431 return Error(Parser.getTok().getLoc(), "unexpected token in directive"); 1432 Parser.Lex(); 1433 1434 // FIXME: We need to be able switch subtargets at this point so that 1435 // MatchInstructionImpl() will work when it gets the AvailableFeatures which 1436 // includes Feature_IsThumb or not to match the right instructions. This is 1437 // blocked on the FIXME in llvm-mc.cpp when creating the TargetMachine. 1438 if (Val == 16){ 1439 assert(TM.getSubtarget<ARMSubtarget>().isThumb() && 1440 "switching between arm/thumb not yet suppported via .code 16)"); 1441 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16); 1442 } 1443 else{ 1444 assert(!TM.getSubtarget<ARMSubtarget>().isThumb() && 1445 "switching between thumb/arm not yet suppported via .code 32)"); 1446 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32); 1447 } 1448 1449 return false; 1450} 1451 1452extern "C" void LLVMInitializeARMAsmLexer(); 1453 1454/// Force static initialization. 1455extern "C" void LLVMInitializeARMAsmParser() { 1456 RegisterAsmParser<ARMAsmParser> X(TheARMTarget); 1457 RegisterAsmParser<ARMAsmParser> Y(TheThumbTarget); 1458 LLVMInitializeARMAsmLexer(); 1459} 1460 1461#define GET_REGISTER_MATCHER 1462#define GET_MATCHER_IMPLEMENTATION 1463#include "ARMGenAsmMatcher.inc" 1464