1 //===-- X86AsmParser.cpp - Parse X86 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 //===----------------------------------------------------------------------===//
10 #include "MCTargetDesc/X86BaseInfo.h"
11 #include "llvm/MC/MCTargetAsmParser.h"
12 #include "llvm/MC/MCStreamer.h"
13 #include "llvm/MC/MCExpr.h"
14 #include "llvm/MC/MCInst.h"
15 #include "llvm/MC/MCRegisterInfo.h"
16 #include "llvm/MC/MCSubtargetInfo.h"
17 #include "llvm/MC/MCParser/MCAsmLexer.h"
18 #include "llvm/MC/MCParser/MCAsmParser.h"
19 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/TargetRegistry.h"
28 #include "llvm/Support/raw_ostream.h"
35 class X86ATTAsmParser : public MCTargetAsmParser {
40 MCAsmParser &getParser() const { return Parser; }
42 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
44 bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
46 X86Operand *ParseOperand();
47 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
49 bool ParseDirectiveWord(unsigned Size, SMLoc L);
50 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
52 bool MatchAndEmitInstruction(SMLoc IDLoc,
53 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
56 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
57 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
58 bool isSrcOp(X86Operand &Op);
60 /// isDstOp - Returns true if operand is either %es:(%rdi) in 64bit mode
61 /// or %es:(%edi) in 32bit mode.
62 bool isDstOp(X86Operand &Op);
64 bool is64BitMode() const {
65 // FIXME: Can tablegen auto-generate this?
66 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
69 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
70 setAvailableFeatures(FB);
73 /// @name Auto-generated Matcher Functions
76 #define GET_ASSEMBLER_HEADER
77 #include "X86GenAsmMatcher.inc"
82 X86ATTAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
83 : MCTargetAsmParser(), STI(sti), Parser(parser) {
85 // Initialize the set of available features.
86 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
88 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
90 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
91 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
93 virtual bool ParseDirective(AsmToken DirectiveID);
95 } // end anonymous namespace
97 /// @name Auto-generated Match Functions
100 static unsigned MatchRegisterName(StringRef Name);
106 /// X86Operand - Instances of this class represent a parsed X86 machine
108 struct X86Operand : public MCParsedAsmOperand {
116 SMLoc StartLoc, EndLoc;
141 X86Operand(KindTy K, SMLoc Start, SMLoc End)
142 : Kind(K), StartLoc(Start), EndLoc(End) {}
144 /// getStartLoc - Get the location of the first token of this operand.
145 SMLoc getStartLoc() const { return StartLoc; }
146 /// getEndLoc - Get the location of the last token of this operand.
147 SMLoc getEndLoc() const { return EndLoc; }
149 virtual void print(raw_ostream &OS) const {}
151 StringRef getToken() const {
152 assert(Kind == Token && "Invalid access!");
153 return StringRef(Tok.Data, Tok.Length);
155 void setTokenValue(StringRef Value) {
156 assert(Kind == Token && "Invalid access!");
157 Tok.Data = Value.data();
158 Tok.Length = Value.size();
161 unsigned getReg() const {
162 assert(Kind == Register && "Invalid access!");
166 const MCExpr *getImm() const {
167 assert(Kind == Immediate && "Invalid access!");
171 const MCExpr *getMemDisp() const {
172 assert(Kind == Memory && "Invalid access!");
175 unsigned getMemSegReg() const {
176 assert(Kind == Memory && "Invalid access!");
179 unsigned getMemBaseReg() const {
180 assert(Kind == Memory && "Invalid access!");
183 unsigned getMemIndexReg() const {
184 assert(Kind == Memory && "Invalid access!");
187 unsigned getMemScale() const {
188 assert(Kind == Memory && "Invalid access!");
192 bool isToken() const {return Kind == Token; }
194 bool isImm() const { return Kind == Immediate; }
196 bool isImmSExti16i8() const {
200 // If this isn't a constant expr, just assume it fits and let relaxation
202 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
206 // Otherwise, check the value is in a range that makes sense for this
208 uint64_t Value = CE->getValue();
209 return (( Value <= 0x000000000000007FULL)||
210 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
211 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
213 bool isImmSExti32i8() const {
217 // If this isn't a constant expr, just assume it fits and let relaxation
219 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
223 // Otherwise, check the value is in a range that makes sense for this
225 uint64_t Value = CE->getValue();
226 return (( Value <= 0x000000000000007FULL)||
227 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
228 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
230 bool isImmZExtu32u8() const {
234 // If this isn't a constant expr, just assume it fits and let relaxation
236 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
240 // Otherwise, check the value is in a range that makes sense for this
242 uint64_t Value = CE->getValue();
243 return (Value <= 0x00000000000000FFULL);
245 bool isImmSExti64i8() const {
249 // If this isn't a constant expr, just assume it fits and let relaxation
251 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
255 // Otherwise, check the value is in a range that makes sense for this
257 uint64_t Value = CE->getValue();
258 return (( Value <= 0x000000000000007FULL)||
259 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
261 bool isImmSExti64i32() const {
265 // If this isn't a constant expr, just assume it fits and let relaxation
267 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
271 // Otherwise, check the value is in a range that makes sense for this
273 uint64_t Value = CE->getValue();
274 return (( Value <= 0x000000007FFFFFFFULL)||
275 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
278 bool isMem() const { return Kind == Memory; }
280 bool isAbsMem() const {
281 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
282 !getMemIndexReg() && getMemScale() == 1;
285 bool isReg() const { return Kind == Register; }
287 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
288 // Add as immediates when possible.
289 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
290 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
292 Inst.addOperand(MCOperand::CreateExpr(Expr));
295 void addRegOperands(MCInst &Inst, unsigned N) const {
296 assert(N == 1 && "Invalid number of operands!");
297 Inst.addOperand(MCOperand::CreateReg(getReg()));
300 void addImmOperands(MCInst &Inst, unsigned N) const {
301 assert(N == 1 && "Invalid number of operands!");
302 addExpr(Inst, getImm());
305 void addMemOperands(MCInst &Inst, unsigned N) const {
306 assert((N == 5) && "Invalid number of operands!");
307 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
308 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
309 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
310 addExpr(Inst, getMemDisp());
311 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
314 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
315 assert((N == 1) && "Invalid number of operands!");
316 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
319 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
320 X86Operand *Res = new X86Operand(Token, Loc, Loc);
321 Res->Tok.Data = Str.data();
322 Res->Tok.Length = Str.size();
326 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
327 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
328 Res->Reg.RegNo = RegNo;
332 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
333 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
338 /// Create an absolute memory operand.
339 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
341 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
343 Res->Mem.Disp = Disp;
344 Res->Mem.BaseReg = 0;
345 Res->Mem.IndexReg = 0;
350 /// Create a generalized memory operand.
351 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
352 unsigned BaseReg, unsigned IndexReg,
353 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc) {
354 // We should never just have a displacement, that should be parsed as an
355 // absolute memory operand.
356 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
358 // The scale should always be one of {1,2,4,8}.
359 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
361 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
362 Res->Mem.SegReg = SegReg;
363 Res->Mem.Disp = Disp;
364 Res->Mem.BaseReg = BaseReg;
365 Res->Mem.IndexReg = IndexReg;
366 Res->Mem.Scale = Scale;
371 } // end anonymous namespace.
373 bool X86ATTAsmParser::isSrcOp(X86Operand &Op) {
374 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
376 return (Op.isMem() &&
377 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
378 isa<MCConstantExpr>(Op.Mem.Disp) &&
379 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
380 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
383 bool X86ATTAsmParser::isDstOp(X86Operand &Op) {
384 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
386 return Op.isMem() && Op.Mem.SegReg == X86::ES &&
387 isa<MCConstantExpr>(Op.Mem.Disp) &&
388 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
389 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
392 bool X86ATTAsmParser::ParseRegister(unsigned &RegNo,
393 SMLoc &StartLoc, SMLoc &EndLoc) {
395 const AsmToken &TokPercent = Parser.getTok();
396 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
397 StartLoc = TokPercent.getLoc();
398 Parser.Lex(); // Eat percent token.
400 const AsmToken &Tok = Parser.getTok();
401 if (Tok.isNot(AsmToken::Identifier))
402 return Error(Tok.getLoc(), "invalid register name");
404 RegNo = MatchRegisterName(Tok.getString());
406 // If the match failed, try the register name as lowercase.
408 RegNo = MatchRegisterName(LowercaseString(Tok.getString()));
410 if (!is64BitMode()) {
411 // FIXME: This should be done using Requires<In32BitMode> and
412 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
414 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
416 if (RegNo == X86::RIZ ||
417 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
418 X86II::isX86_64NonExtLowByteReg(RegNo) ||
419 X86II::isX86_64ExtendedReg(RegNo))
420 return Error(Tok.getLoc(), "register %"
421 + Tok.getString() + " is only available in 64-bit mode");
424 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
425 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
427 EndLoc = Tok.getLoc();
428 Parser.Lex(); // Eat 'st'
430 // Check to see if we have '(4)' after %st.
431 if (getLexer().isNot(AsmToken::LParen))
436 const AsmToken &IntTok = Parser.getTok();
437 if (IntTok.isNot(AsmToken::Integer))
438 return Error(IntTok.getLoc(), "expected stack index");
439 switch (IntTok.getIntVal()) {
440 case 0: RegNo = X86::ST0; break;
441 case 1: RegNo = X86::ST1; break;
442 case 2: RegNo = X86::ST2; break;
443 case 3: RegNo = X86::ST3; break;
444 case 4: RegNo = X86::ST4; break;
445 case 5: RegNo = X86::ST5; break;
446 case 6: RegNo = X86::ST6; break;
447 case 7: RegNo = X86::ST7; break;
448 default: return Error(IntTok.getLoc(), "invalid stack index");
451 if (getParser().Lex().isNot(AsmToken::RParen))
452 return Error(Parser.getTok().getLoc(), "expected ')'");
454 EndLoc = Tok.getLoc();
455 Parser.Lex(); // Eat ')'
459 // If this is "db[0-7]", match it as an alias
461 if (RegNo == 0 && Tok.getString().size() == 3 &&
462 Tok.getString().startswith("db")) {
463 switch (Tok.getString()[2]) {
464 case '0': RegNo = X86::DR0; break;
465 case '1': RegNo = X86::DR1; break;
466 case '2': RegNo = X86::DR2; break;
467 case '3': RegNo = X86::DR3; break;
468 case '4': RegNo = X86::DR4; break;
469 case '5': RegNo = X86::DR5; break;
470 case '6': RegNo = X86::DR6; break;
471 case '7': RegNo = X86::DR7; break;
475 EndLoc = Tok.getLoc();
476 Parser.Lex(); // Eat it.
482 return Error(Tok.getLoc(), "invalid register name");
484 EndLoc = Tok.getLoc();
485 Parser.Lex(); // Eat identifier token.
489 X86Operand *X86ATTAsmParser::ParseOperand() {
490 switch (getLexer().getKind()) {
492 // Parse a memory operand with no segment register.
493 return ParseMemOperand(0, Parser.getTok().getLoc());
494 case AsmToken::Percent: {
495 // Read the register.
498 if (ParseRegister(RegNo, Start, End)) return 0;
499 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
500 Error(Start, "%eiz and %riz can only be used as index registers");
504 // If this is a segment register followed by a ':', then this is the start
505 // of a memory reference, otherwise this is a normal register reference.
506 if (getLexer().isNot(AsmToken::Colon))
507 return X86Operand::CreateReg(RegNo, Start, End);
510 getParser().Lex(); // Eat the colon.
511 return ParseMemOperand(RegNo, Start);
513 case AsmToken::Dollar: {
515 SMLoc Start = Parser.getTok().getLoc(), End;
518 if (getParser().ParseExpression(Val, End))
520 return X86Operand::CreateImm(Val, Start, End);
525 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
526 /// has already been parsed if present.
527 X86Operand *X86ATTAsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
529 // We have to disambiguate a parenthesized expression "(4+5)" from the start
530 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
531 // only way to do this without lookahead is to eat the '(' and see what is
533 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
534 if (getLexer().isNot(AsmToken::LParen)) {
536 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
538 // After parsing the base expression we could either have a parenthesized
539 // memory address or not. If not, return now. If so, eat the (.
540 if (getLexer().isNot(AsmToken::LParen)) {
541 // Unless we have a segment register, treat this as an immediate.
543 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
544 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
550 // Okay, we have a '('. We don't know if this is an expression or not, but
551 // so we have to eat the ( to see beyond it.
552 SMLoc LParenLoc = Parser.getTok().getLoc();
553 Parser.Lex(); // Eat the '('.
555 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
556 // Nothing to do here, fall into the code below with the '(' part of the
557 // memory operand consumed.
561 // It must be an parenthesized expression, parse it now.
562 if (getParser().ParseParenExpression(Disp, ExprEnd))
565 // After parsing the base expression we could either have a parenthesized
566 // memory address or not. If not, return now. If so, eat the (.
567 if (getLexer().isNot(AsmToken::LParen)) {
568 // Unless we have a segment register, treat this as an immediate.
570 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
571 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
579 // If we reached here, then we just ate the ( of the memory operand. Process
580 // the rest of the memory operand.
581 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
583 if (getLexer().is(AsmToken::Percent)) {
585 if (ParseRegister(BaseReg, L, L)) return 0;
586 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
587 Error(L, "eiz and riz can only be used as index registers");
592 if (getLexer().is(AsmToken::Comma)) {
593 Parser.Lex(); // Eat the comma.
595 // Following the comma we should have either an index register, or a scale
596 // value. We don't support the later form, but we want to parse it
599 // Not that even though it would be completely consistent to support syntax
600 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
601 if (getLexer().is(AsmToken::Percent)) {
603 if (ParseRegister(IndexReg, L, L)) return 0;
605 if (getLexer().isNot(AsmToken::RParen)) {
606 // Parse the scale amount:
607 // ::= ',' [scale-expression]
608 if (getLexer().isNot(AsmToken::Comma)) {
609 Error(Parser.getTok().getLoc(),
610 "expected comma in scale expression");
613 Parser.Lex(); // Eat the comma.
615 if (getLexer().isNot(AsmToken::RParen)) {
616 SMLoc Loc = Parser.getTok().getLoc();
619 if (getParser().ParseAbsoluteExpression(ScaleVal))
622 // Validate the scale amount.
623 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
624 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
627 Scale = (unsigned)ScaleVal;
630 } else if (getLexer().isNot(AsmToken::RParen)) {
631 // A scale amount without an index is ignored.
633 SMLoc Loc = Parser.getTok().getLoc();
636 if (getParser().ParseAbsoluteExpression(Value))
640 Warning(Loc, "scale factor without index register is ignored");
645 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
646 if (getLexer().isNot(AsmToken::RParen)) {
647 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
650 SMLoc MemEnd = Parser.getTok().getLoc();
651 Parser.Lex(); // Eat the ')'.
653 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
657 bool X86ATTAsmParser::
658 ParseInstruction(StringRef Name, SMLoc NameLoc,
659 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
660 StringRef PatchedName = Name;
662 // FIXME: Hack to recognize setneb as setne.
663 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
664 PatchedName != "setb" && PatchedName != "setnb")
665 PatchedName = PatchedName.substr(0, Name.size()-1);
667 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
668 const MCExpr *ExtraImmOp = 0;
669 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
670 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
671 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
672 bool IsVCMP = PatchedName.startswith("vcmp");
673 unsigned SSECCIdx = IsVCMP ? 4 : 3;
674 unsigned SSEComparisonCode = StringSwitch<unsigned>(
675 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
688 .Case("neq_oq", 0x0C)
695 .Case("unord_s", 0x13)
696 .Case("neq_us", 0x14)
697 .Case("nlt_uq", 0x15)
698 .Case("nle_uq", 0x16)
701 .Case("nge_uq", 0x19)
702 .Case("ngt_uq", 0x1A)
703 .Case("false_os", 0x1B)
704 .Case("neq_os", 0x1C)
707 .Case("true_us", 0x1F)
709 if (SSEComparisonCode != ~0U) {
710 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
711 getParser().getContext());
712 if (PatchedName.endswith("ss")) {
713 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
714 } else if (PatchedName.endswith("sd")) {
715 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
716 } else if (PatchedName.endswith("ps")) {
717 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
719 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
720 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
725 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
728 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
731 // Determine whether this is an instruction prefix.
733 Name == "lock" || Name == "rep" ||
734 Name == "repe" || Name == "repz" ||
735 Name == "repne" || Name == "repnz" ||
736 Name == "rex64" || Name == "data16";
739 // This does the actual operand parsing. Don't parse any more if we have a
740 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
741 // just want to parse the "lock" as the first instruction and the "incl" as
743 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
745 // Parse '*' modifier.
746 if (getLexer().is(AsmToken::Star)) {
747 SMLoc Loc = Parser.getTok().getLoc();
748 Operands.push_back(X86Operand::CreateToken("*", Loc));
749 Parser.Lex(); // Eat the star.
752 // Read the first operand.
753 if (X86Operand *Op = ParseOperand())
754 Operands.push_back(Op);
756 Parser.EatToEndOfStatement();
760 while (getLexer().is(AsmToken::Comma)) {
761 Parser.Lex(); // Eat the comma.
763 // Parse and remember the operand.
764 if (X86Operand *Op = ParseOperand())
765 Operands.push_back(Op);
767 Parser.EatToEndOfStatement();
772 if (getLexer().isNot(AsmToken::EndOfStatement)) {
773 SMLoc Loc = getLexer().getLoc();
774 Parser.EatToEndOfStatement();
775 return Error(Loc, "unexpected token in argument list");
779 if (getLexer().is(AsmToken::EndOfStatement))
780 Parser.Lex(); // Consume the EndOfStatement
781 else if (isPrefix && getLexer().is(AsmToken::Slash))
782 Parser.Lex(); // Consume the prefix separator Slash
784 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
785 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
786 // documented form in various unofficial manuals, so a lot of code uses it.
787 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
788 Operands.size() == 3) {
789 X86Operand &Op = *(X86Operand*)Operands.back();
790 if (Op.isMem() && Op.Mem.SegReg == 0 &&
791 isa<MCConstantExpr>(Op.Mem.Disp) &&
792 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
793 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
794 SMLoc Loc = Op.getEndLoc();
795 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
799 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
800 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
801 Operands.size() == 3) {
802 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
803 if (Op.isMem() && Op.Mem.SegReg == 0 &&
804 isa<MCConstantExpr>(Op.Mem.Disp) &&
805 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
806 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
807 SMLoc Loc = Op.getEndLoc();
808 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
812 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
813 if (Name.startswith("ins") && Operands.size() == 3 &&
814 (Name == "insb" || Name == "insw" || Name == "insl")) {
815 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
816 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
817 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
825 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
826 if (Name.startswith("outs") && Operands.size() == 3 &&
827 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
828 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
829 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
830 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
838 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
839 if (Name.startswith("movs") && Operands.size() == 3 &&
840 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
841 (is64BitMode() && Name == "movsq"))) {
842 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
843 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
844 if (isSrcOp(Op) && isDstOp(Op2)) {
851 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
852 if (Name.startswith("lods") && Operands.size() == 3 &&
853 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
854 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
855 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
856 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
857 if (isSrcOp(*Op1) && Op2->isReg()) {
859 unsigned reg = Op2->getReg();
860 bool isLods = Name == "lods";
861 if (reg == X86::AL && (isLods || Name == "lodsb"))
863 else if (reg == X86::AX && (isLods || Name == "lodsw"))
865 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
867 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
877 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
881 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
882 if (Name.startswith("stos") && Operands.size() == 3 &&
883 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
884 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
885 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
886 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
887 if (isDstOp(*Op2) && Op1->isReg()) {
889 unsigned reg = Op1->getReg();
890 bool isStos = Name == "stos";
891 if (reg == X86::AL && (isStos || Name == "stosb"))
893 else if (reg == X86::AX && (isStos || Name == "stosw"))
895 else if (reg == X86::EAX && (isStos || Name == "stosl"))
897 else if (reg == X86::RAX && (isStos || Name == "stosq"))
907 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
912 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
914 if ((Name.startswith("shr") || Name.startswith("sar") ||
915 Name.startswith("shl") || Name.startswith("sal") ||
916 Name.startswith("rcl") || Name.startswith("rcr") ||
917 Name.startswith("rol") || Name.startswith("ror")) &&
918 Operands.size() == 3) {
919 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
920 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
921 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
923 Operands.erase(Operands.begin() + 1);
927 // Transforms "int $3" into "int3" as a size optimization. We can't write an
928 // instalias with an immediate operand yet.
929 if (Name == "int" && Operands.size() == 2) {
930 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
931 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
932 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
934 Operands.erase(Operands.begin() + 1);
935 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
942 bool X86ATTAsmParser::
943 MatchAndEmitInstruction(SMLoc IDLoc,
944 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
946 assert(!Operands.empty() && "Unexpect empty operand list!");
947 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
948 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
950 // First, handle aliases that expand to multiple instructions.
951 // FIXME: This should be replaced with a real .td file alias mechanism.
952 // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
954 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
955 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
956 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
957 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
959 Inst.setOpcode(X86::WAIT);
960 Out.EmitInstruction(Inst);
963 StringSwitch<const char*>(Op->getToken())
964 .Case("finit", "fninit")
965 .Case("fsave", "fnsave")
966 .Case("fstcw", "fnstcw")
967 .Case("fstcww", "fnstcw")
968 .Case("fstenv", "fnstenv")
969 .Case("fstsw", "fnstsw")
970 .Case("fstsww", "fnstsw")
971 .Case("fclex", "fnclex")
973 assert(Repl && "Unknown wait-prefixed instruction");
975 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
978 bool WasOriginallyInvalidOperand = false;
979 unsigned OrigErrorInfo;
982 // First, try a direct match.
983 switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo)) {
986 Out.EmitInstruction(Inst);
988 case Match_MissingFeature:
989 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
991 case Match_ConversionFail:
992 return Error(IDLoc, "unable to convert operands to instruction");
993 case Match_InvalidOperand:
994 WasOriginallyInvalidOperand = true;
996 case Match_MnemonicFail:
1000 // FIXME: Ideally, we would only attempt suffix matches for things which are
1001 // valid prefixes, and we could just infer the right unambiguous
1002 // type. However, that requires substantially more matcher support than the
1005 // Change the operand to point to a temporary token.
1006 StringRef Base = Op->getToken();
1007 SmallString<16> Tmp;
1010 Op->setTokenValue(Tmp.str());
1012 // If this instruction starts with an 'f', then it is a floating point stack
1013 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1014 // 80-bit floating point, which use the suffixes s,l,t respectively.
1016 // Otherwise, we assume that this may be an integer instruction, which comes
1017 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1018 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1020 // Check for the various suffix matches.
1021 Tmp[Base.size()] = Suffixes[0];
1022 unsigned ErrorInfoIgnore;
1023 unsigned Match1, Match2, Match3, Match4;
1025 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1026 Tmp[Base.size()] = Suffixes[1];
1027 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1028 Tmp[Base.size()] = Suffixes[2];
1029 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1030 Tmp[Base.size()] = Suffixes[3];
1031 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1033 // Restore the old token.
1034 Op->setTokenValue(Base);
1036 // If exactly one matched, then we treat that as a successful match (and the
1037 // instruction will already have been filled in correctly, since the failing
1038 // matches won't have modified it).
1039 unsigned NumSuccessfulMatches =
1040 (Match1 == Match_Success) + (Match2 == Match_Success) +
1041 (Match3 == Match_Success) + (Match4 == Match_Success);
1042 if (NumSuccessfulMatches == 1) {
1043 Out.EmitInstruction(Inst);
1047 // Otherwise, the match failed, try to produce a decent error message.
1049 // If we had multiple suffix matches, then identify this as an ambiguous
1051 if (NumSuccessfulMatches > 1) {
1053 unsigned NumMatches = 0;
1054 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1055 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1056 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1057 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1059 SmallString<126> Msg;
1060 raw_svector_ostream OS(Msg);
1061 OS << "ambiguous instructions require an explicit suffix (could be ";
1062 for (unsigned i = 0; i != NumMatches; ++i) {
1065 if (i + 1 == NumMatches)
1067 OS << "'" << Base << MatchChars[i] << "'";
1070 Error(IDLoc, OS.str());
1074 // Okay, we know that none of the variants matched successfully.
1076 // If all of the instructions reported an invalid mnemonic, then the original
1077 // mnemonic was invalid.
1078 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1079 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1080 if (!WasOriginallyInvalidOperand) {
1081 Error(IDLoc, "invalid instruction mnemonic '" + Base + "'");
1085 // Recover location info for the operand if we know which was the problem.
1086 SMLoc ErrorLoc = IDLoc;
1087 if (OrigErrorInfo != ~0U) {
1088 if (OrigErrorInfo >= Operands.size())
1089 return Error(IDLoc, "too few operands for instruction");
1091 ErrorLoc = ((X86Operand*)Operands[OrigErrorInfo])->getStartLoc();
1092 if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
1095 return Error(ErrorLoc, "invalid operand for instruction");
1098 // If one instruction matched with a missing feature, report this as a
1100 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1101 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1102 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1106 // If one instruction matched with an invalid operand, report this as an
1108 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1109 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1110 Error(IDLoc, "invalid operand for instruction");
1114 // If all of these were an outright failure, report it in a useless way.
1115 // FIXME: We should give nicer diagnostics about the exact failure.
1116 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
1121 bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
1122 StringRef IDVal = DirectiveID.getIdentifier();
1123 if (IDVal == ".word")
1124 return ParseDirectiveWord(2, DirectiveID.getLoc());
1125 else if (IDVal.startswith(".code"))
1126 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1130 /// ParseDirectiveWord
1131 /// ::= .word [ expression (, expression)* ]
1132 bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1133 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1135 const MCExpr *Value;
1136 if (getParser().ParseExpression(Value))
1139 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1141 if (getLexer().is(AsmToken::EndOfStatement))
1144 // FIXME: Improve diagnostic.
1145 if (getLexer().isNot(AsmToken::Comma))
1146 return Error(L, "unexpected token in directive");
1155 /// ParseDirectiveCode
1156 /// ::= .code32 | .code64
1157 bool X86ATTAsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1158 if (IDVal == ".code32") {
1160 if (is64BitMode()) {
1162 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1164 } else if (IDVal == ".code64") {
1166 if (!is64BitMode()) {
1168 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1171 return Error(L, "unexpected directive " + IDVal);
1178 extern "C" void LLVMInitializeX86AsmLexer();
1180 // Force static initialization.
1181 extern "C" void LLVMInitializeX86AsmParser() {
1182 RegisterMCAsmParser<X86ATTAsmParser> X(TheX86_32Target);
1183 RegisterMCAsmParser<X86ATTAsmParser> Y(TheX86_64Target);
1184 LLVMInitializeX86AsmLexer();
1187 #define GET_REGISTER_MATCHER
1188 #define GET_MATCHER_IMPLEMENTATION
1189 #include "X86GenAsmMatcher.inc"