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 "llvm/Target/TargetAsmParser.h"
12 #include "X86Subtarget.h"
13 #include "llvm/Target/TargetRegistry.h"
14 #include "llvm/Target/TargetAsmParser.h"
15 #include "llvm/MC/MCStreamer.h"
16 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCInst.h"
18 #include "llvm/MC/MCSubtargetInfo.h"
19 #include "llvm/MC/MCParser/MCAsmLexer.h"
20 #include "llvm/MC/MCParser/MCAsmParser.h"
21 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "llvm/Support/raw_ostream.h"
30 #define GET_SUBTARGETINFO_ENUM
31 #include "X86GenSubtargetInfo.inc"
38 class X86ATTAsmParser : public TargetAsmParser {
40 const MCSubtargetInfo *STI;
43 MCAsmParser &getParser() const { return Parser; }
45 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
47 bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
49 X86Operand *ParseOperand();
50 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
52 bool ParseDirectiveWord(unsigned Size, SMLoc L);
54 bool MatchAndEmitInstruction(SMLoc IDLoc,
55 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
58 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
59 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
60 bool isSrcOp(X86Operand &Op);
62 /// isDstOp - Returns true if operand is either %es:(%rdi) in 64bit mode
63 /// or %es:(%edi) in 32bit mode.
64 bool isDstOp(X86Operand &Op);
67 // FIXME: Can tablegen auto-generate this?
68 return (STI->getFeatureBits() & X86::Mode64Bit) != 0;
71 /// @name Auto-generated Matcher Functions
74 #define GET_ASSEMBLER_HEADER
75 #include "X86GenAsmMatcher.inc"
80 X86ATTAsmParser(StringRef TT, StringRef CPU, StringRef FS,
82 : TargetAsmParser(), Parser(parser) {
83 STI = X86_MC::createX86MCSubtargetInfo(TT, CPU, FS);
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 dump(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 isImmSExti64i8() 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 <= 0x000000000000007FULL)||
244 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
246 bool isImmSExti64i32() const {
250 // If this isn't a constant expr, just assume it fits and let relaxation
252 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
256 // Otherwise, check the value is in a range that makes sense for this
258 uint64_t Value = CE->getValue();
259 return (( Value <= 0x000000007FFFFFFFULL)||
260 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
263 bool isMem() const { return Kind == Memory; }
265 bool isAbsMem() const {
266 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
267 !getMemIndexReg() && getMemScale() == 1;
270 bool isReg() const { return Kind == Register; }
272 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
273 // Add as immediates when possible.
274 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
275 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
277 Inst.addOperand(MCOperand::CreateExpr(Expr));
280 void addRegOperands(MCInst &Inst, unsigned N) const {
281 assert(N == 1 && "Invalid number of operands!");
282 Inst.addOperand(MCOperand::CreateReg(getReg()));
285 void addImmOperands(MCInst &Inst, unsigned N) const {
286 assert(N == 1 && "Invalid number of operands!");
287 addExpr(Inst, getImm());
290 void addMemOperands(MCInst &Inst, unsigned N) const {
291 assert((N == 5) && "Invalid number of operands!");
292 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
293 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
294 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
295 addExpr(Inst, getMemDisp());
296 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
299 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
300 assert((N == 1) && "Invalid number of operands!");
301 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
304 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
305 X86Operand *Res = new X86Operand(Token, Loc, Loc);
306 Res->Tok.Data = Str.data();
307 Res->Tok.Length = Str.size();
311 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
312 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
313 Res->Reg.RegNo = RegNo;
317 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
318 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
323 /// Create an absolute memory operand.
324 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
326 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
328 Res->Mem.Disp = Disp;
329 Res->Mem.BaseReg = 0;
330 Res->Mem.IndexReg = 0;
335 /// Create a generalized memory operand.
336 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
337 unsigned BaseReg, unsigned IndexReg,
338 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc) {
339 // We should never just have a displacement, that should be parsed as an
340 // absolute memory operand.
341 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
343 // The scale should always be one of {1,2,4,8}.
344 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
346 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
347 Res->Mem.SegReg = SegReg;
348 Res->Mem.Disp = Disp;
349 Res->Mem.BaseReg = BaseReg;
350 Res->Mem.IndexReg = IndexReg;
351 Res->Mem.Scale = Scale;
356 } // end anonymous namespace.
358 bool X86ATTAsmParser::isSrcOp(X86Operand &Op) {
359 unsigned basereg = is64Bit() ? X86::RSI : X86::ESI;
361 return (Op.isMem() &&
362 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
363 isa<MCConstantExpr>(Op.Mem.Disp) &&
364 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
365 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
368 bool X86ATTAsmParser::isDstOp(X86Operand &Op) {
369 unsigned basereg = is64Bit() ? X86::RDI : X86::EDI;
371 return Op.isMem() && Op.Mem.SegReg == X86::ES &&
372 isa<MCConstantExpr>(Op.Mem.Disp) &&
373 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
374 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
377 bool X86ATTAsmParser::ParseRegister(unsigned &RegNo,
378 SMLoc &StartLoc, SMLoc &EndLoc) {
380 const AsmToken &TokPercent = Parser.getTok();
381 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
382 StartLoc = TokPercent.getLoc();
383 Parser.Lex(); // Eat percent token.
385 const AsmToken &Tok = Parser.getTok();
386 if (Tok.isNot(AsmToken::Identifier))
387 return Error(Tok.getLoc(), "invalid register name");
389 // FIXME: Validate register for the current architecture; we have to do
390 // validation later, so maybe there is no need for this here.
391 RegNo = MatchRegisterName(Tok.getString());
393 // If the match failed, try the register name as lowercase.
395 RegNo = MatchRegisterName(LowercaseString(Tok.getString()));
397 // FIXME: This should be done using Requires<In32BitMode> and
398 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions
399 // can be also checked.
400 if (RegNo == X86::RIZ && !is64Bit())
401 return Error(Tok.getLoc(), "riz register in 64-bit mode only");
403 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
404 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
406 EndLoc = Tok.getLoc();
407 Parser.Lex(); // Eat 'st'
409 // Check to see if we have '(4)' after %st.
410 if (getLexer().isNot(AsmToken::LParen))
415 const AsmToken &IntTok = Parser.getTok();
416 if (IntTok.isNot(AsmToken::Integer))
417 return Error(IntTok.getLoc(), "expected stack index");
418 switch (IntTok.getIntVal()) {
419 case 0: RegNo = X86::ST0; break;
420 case 1: RegNo = X86::ST1; break;
421 case 2: RegNo = X86::ST2; break;
422 case 3: RegNo = X86::ST3; break;
423 case 4: RegNo = X86::ST4; break;
424 case 5: RegNo = X86::ST5; break;
425 case 6: RegNo = X86::ST6; break;
426 case 7: RegNo = X86::ST7; break;
427 default: return Error(IntTok.getLoc(), "invalid stack index");
430 if (getParser().Lex().isNot(AsmToken::RParen))
431 return Error(Parser.getTok().getLoc(), "expected ')'");
433 EndLoc = Tok.getLoc();
434 Parser.Lex(); // Eat ')'
438 // If this is "db[0-7]", match it as an alias
440 if (RegNo == 0 && Tok.getString().size() == 3 &&
441 Tok.getString().startswith("db")) {
442 switch (Tok.getString()[2]) {
443 case '0': RegNo = X86::DR0; break;
444 case '1': RegNo = X86::DR1; break;
445 case '2': RegNo = X86::DR2; break;
446 case '3': RegNo = X86::DR3; break;
447 case '4': RegNo = X86::DR4; break;
448 case '5': RegNo = X86::DR5; break;
449 case '6': RegNo = X86::DR6; break;
450 case '7': RegNo = X86::DR7; break;
454 EndLoc = Tok.getLoc();
455 Parser.Lex(); // Eat it.
461 return Error(Tok.getLoc(), "invalid register name");
463 EndLoc = Tok.getLoc();
464 Parser.Lex(); // Eat identifier token.
468 X86Operand *X86ATTAsmParser::ParseOperand() {
469 switch (getLexer().getKind()) {
471 // Parse a memory operand with no segment register.
472 return ParseMemOperand(0, Parser.getTok().getLoc());
473 case AsmToken::Percent: {
474 // Read the register.
477 if (ParseRegister(RegNo, Start, End)) return 0;
478 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
479 Error(Start, "eiz and riz can only be used as index registers");
483 // If this is a segment register followed by a ':', then this is the start
484 // of a memory reference, otherwise this is a normal register reference.
485 if (getLexer().isNot(AsmToken::Colon))
486 return X86Operand::CreateReg(RegNo, Start, End);
489 getParser().Lex(); // Eat the colon.
490 return ParseMemOperand(RegNo, Start);
492 case AsmToken::Dollar: {
494 SMLoc Start = Parser.getTok().getLoc(), End;
497 if (getParser().ParseExpression(Val, End))
499 return X86Operand::CreateImm(Val, Start, End);
504 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
505 /// has already been parsed if present.
506 X86Operand *X86ATTAsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
508 // We have to disambiguate a parenthesized expression "(4+5)" from the start
509 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
510 // only way to do this without lookahead is to eat the '(' and see what is
512 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
513 if (getLexer().isNot(AsmToken::LParen)) {
515 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
517 // After parsing the base expression we could either have a parenthesized
518 // memory address or not. If not, return now. If so, eat the (.
519 if (getLexer().isNot(AsmToken::LParen)) {
520 // Unless we have a segment register, treat this as an immediate.
522 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
523 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
529 // Okay, we have a '('. We don't know if this is an expression or not, but
530 // so we have to eat the ( to see beyond it.
531 SMLoc LParenLoc = Parser.getTok().getLoc();
532 Parser.Lex(); // Eat the '('.
534 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
535 // Nothing to do here, fall into the code below with the '(' part of the
536 // memory operand consumed.
540 // It must be an parenthesized expression, parse it now.
541 if (getParser().ParseParenExpression(Disp, ExprEnd))
544 // After parsing the base expression we could either have a parenthesized
545 // memory address or not. If not, return now. If so, eat the (.
546 if (getLexer().isNot(AsmToken::LParen)) {
547 // Unless we have a segment register, treat this as an immediate.
549 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
550 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
558 // If we reached here, then we just ate the ( of the memory operand. Process
559 // the rest of the memory operand.
560 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
562 if (getLexer().is(AsmToken::Percent)) {
564 if (ParseRegister(BaseReg, L, L)) return 0;
565 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
566 Error(L, "eiz and riz can only be used as index registers");
571 if (getLexer().is(AsmToken::Comma)) {
572 Parser.Lex(); // Eat the comma.
574 // Following the comma we should have either an index register, or a scale
575 // value. We don't support the later form, but we want to parse it
578 // Not that even though it would be completely consistent to support syntax
579 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
580 if (getLexer().is(AsmToken::Percent)) {
582 if (ParseRegister(IndexReg, L, L)) return 0;
584 if (getLexer().isNot(AsmToken::RParen)) {
585 // Parse the scale amount:
586 // ::= ',' [scale-expression]
587 if (getLexer().isNot(AsmToken::Comma)) {
588 Error(Parser.getTok().getLoc(),
589 "expected comma in scale expression");
592 Parser.Lex(); // Eat the comma.
594 if (getLexer().isNot(AsmToken::RParen)) {
595 SMLoc Loc = Parser.getTok().getLoc();
598 if (getParser().ParseAbsoluteExpression(ScaleVal))
601 // Validate the scale amount.
602 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
603 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
606 Scale = (unsigned)ScaleVal;
609 } else if (getLexer().isNot(AsmToken::RParen)) {
610 // A scale amount without an index is ignored.
612 SMLoc Loc = Parser.getTok().getLoc();
615 if (getParser().ParseAbsoluteExpression(Value))
619 Warning(Loc, "scale factor without index register is ignored");
624 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
625 if (getLexer().isNot(AsmToken::RParen)) {
626 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
629 SMLoc MemEnd = Parser.getTok().getLoc();
630 Parser.Lex(); // Eat the ')'.
632 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
636 bool X86ATTAsmParser::
637 ParseInstruction(StringRef Name, SMLoc NameLoc,
638 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
639 StringRef PatchedName = Name;
641 // FIXME: Hack to recognize setneb as setne.
642 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
643 PatchedName != "setb" && PatchedName != "setnb")
644 PatchedName = PatchedName.substr(0, Name.size()-1);
646 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
647 const MCExpr *ExtraImmOp = 0;
648 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
649 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
650 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
651 bool IsVCMP = PatchedName.startswith("vcmp");
652 unsigned SSECCIdx = IsVCMP ? 4 : 3;
653 unsigned SSEComparisonCode = StringSwitch<unsigned>(
654 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
667 .Case("neq_oq", 0x0C)
674 .Case("unord_s", 0x13)
675 .Case("neq_us", 0x14)
676 .Case("nlt_uq", 0x15)
677 .Case("nle_uq", 0x16)
680 .Case("nge_uq", 0x19)
681 .Case("ngt_uq", 0x1A)
682 .Case("false_os", 0x1B)
683 .Case("neq_os", 0x1C)
686 .Case("true_us", 0x1F)
688 if (SSEComparisonCode != ~0U) {
689 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
690 getParser().getContext());
691 if (PatchedName.endswith("ss")) {
692 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
693 } else if (PatchedName.endswith("sd")) {
694 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
695 } else if (PatchedName.endswith("ps")) {
696 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
698 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
699 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
704 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
707 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
710 // Determine whether this is an instruction prefix.
712 Name == "lock" || Name == "rep" ||
713 Name == "repe" || Name == "repz" ||
714 Name == "repne" || Name == "repnz" ||
715 Name == "rex64" || Name == "data16";
718 // This does the actual operand parsing. Don't parse any more if we have a
719 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
720 // just want to parse the "lock" as the first instruction and the "incl" as
722 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
724 // Parse '*' modifier.
725 if (getLexer().is(AsmToken::Star)) {
726 SMLoc Loc = Parser.getTok().getLoc();
727 Operands.push_back(X86Operand::CreateToken("*", Loc));
728 Parser.Lex(); // Eat the star.
731 // Read the first operand.
732 if (X86Operand *Op = ParseOperand())
733 Operands.push_back(Op);
735 Parser.EatToEndOfStatement();
739 while (getLexer().is(AsmToken::Comma)) {
740 Parser.Lex(); // Eat the comma.
742 // Parse and remember the operand.
743 if (X86Operand *Op = ParseOperand())
744 Operands.push_back(Op);
746 Parser.EatToEndOfStatement();
751 if (getLexer().isNot(AsmToken::EndOfStatement)) {
752 SMLoc Loc = getLexer().getLoc();
753 Parser.EatToEndOfStatement();
754 return Error(Loc, "unexpected token in argument list");
758 if (getLexer().is(AsmToken::EndOfStatement))
759 Parser.Lex(); // Consume the EndOfStatement
760 else if (isPrefix && getLexer().is(AsmToken::Slash))
761 Parser.Lex(); // Consume the prefix separator Slash
763 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
764 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
765 // documented form in various unofficial manuals, so a lot of code uses it.
766 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
767 Operands.size() == 3) {
768 X86Operand &Op = *(X86Operand*)Operands.back();
769 if (Op.isMem() && Op.Mem.SegReg == 0 &&
770 isa<MCConstantExpr>(Op.Mem.Disp) &&
771 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
772 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
773 SMLoc Loc = Op.getEndLoc();
774 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
778 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
779 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
780 Operands.size() == 3) {
781 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
782 if (Op.isMem() && Op.Mem.SegReg == 0 &&
783 isa<MCConstantExpr>(Op.Mem.Disp) &&
784 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
785 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
786 SMLoc Loc = Op.getEndLoc();
787 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
791 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
792 if (Name.startswith("ins") && Operands.size() == 3 &&
793 (Name == "insb" || Name == "insw" || Name == "insl")) {
794 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
795 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
796 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
804 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
805 if (Name.startswith("outs") && Operands.size() == 3 &&
806 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
807 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
808 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
809 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
817 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
818 if (Name.startswith("movs") && Operands.size() == 3 &&
819 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
820 (is64Bit() && Name == "movsq"))) {
821 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
822 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
823 if (isSrcOp(Op) && isDstOp(Op2)) {
830 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
831 if (Name.startswith("lods") && Operands.size() == 3 &&
832 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
833 Name == "lodsl" || (is64Bit() && Name == "lodsq"))) {
834 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
835 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
836 if (isSrcOp(*Op1) && Op2->isReg()) {
838 unsigned reg = Op2->getReg();
839 bool isLods = Name == "lods";
840 if (reg == X86::AL && (isLods || Name == "lodsb"))
842 else if (reg == X86::AX && (isLods || Name == "lodsw"))
844 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
846 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
856 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
860 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
861 if (Name.startswith("stos") && Operands.size() == 3 &&
862 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
863 Name == "stosl" || (is64Bit() && Name == "stosq"))) {
864 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
865 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
866 if (isDstOp(*Op2) && Op1->isReg()) {
868 unsigned reg = Op1->getReg();
869 bool isStos = Name == "stos";
870 if (reg == X86::AL && (isStos || Name == "stosb"))
872 else if (reg == X86::AX && (isStos || Name == "stosw"))
874 else if (reg == X86::EAX && (isStos || Name == "stosl"))
876 else if (reg == X86::RAX && (isStos || Name == "stosq"))
886 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
891 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
893 if ((Name.startswith("shr") || Name.startswith("sar") ||
894 Name.startswith("shl") || Name.startswith("sal") ||
895 Name.startswith("rcl") || Name.startswith("rcr") ||
896 Name.startswith("rol") || Name.startswith("ror")) &&
897 Operands.size() == 3) {
898 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
899 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
900 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
902 Operands.erase(Operands.begin() + 1);
906 // Transforms "int $3" into "int3" as a size optimization. We can't write an
907 // instalias with an immediate operand yet.
908 if (Name == "int" && Operands.size() == 2) {
909 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
910 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
911 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
913 Operands.erase(Operands.begin() + 1);
914 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
921 bool X86ATTAsmParser::
922 MatchAndEmitInstruction(SMLoc IDLoc,
923 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
925 assert(!Operands.empty() && "Unexpect empty operand list!");
926 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
927 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
929 // First, handle aliases that expand to multiple instructions.
930 // FIXME: This should be replaced with a real .td file alias mechanism.
931 // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
933 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
934 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
935 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
936 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
938 Inst.setOpcode(X86::WAIT);
939 Out.EmitInstruction(Inst);
942 StringSwitch<const char*>(Op->getToken())
943 .Case("finit", "fninit")
944 .Case("fsave", "fnsave")
945 .Case("fstcw", "fnstcw")
946 .Case("fstcww", "fnstcw")
947 .Case("fstenv", "fnstenv")
948 .Case("fstsw", "fnstsw")
949 .Case("fstsww", "fnstsw")
950 .Case("fclex", "fnclex")
952 assert(Repl && "Unknown wait-prefixed instruction");
954 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
957 bool WasOriginallyInvalidOperand = false;
958 unsigned OrigErrorInfo;
961 // First, try a direct match.
962 switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo)) {
964 Out.EmitInstruction(Inst);
966 case Match_MissingFeature:
967 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
969 case Match_ConversionFail:
970 return Error(IDLoc, "unable to convert operands to instruction");
971 case Match_InvalidOperand:
972 WasOriginallyInvalidOperand = true;
974 case Match_MnemonicFail:
978 // FIXME: Ideally, we would only attempt suffix matches for things which are
979 // valid prefixes, and we could just infer the right unambiguous
980 // type. However, that requires substantially more matcher support than the
983 // Change the operand to point to a temporary token.
984 StringRef Base = Op->getToken();
988 Op->setTokenValue(Tmp.str());
990 // If this instruction starts with an 'f', then it is a floating point stack
991 // instruction. These come in up to three forms for 32-bit, 64-bit, and
992 // 80-bit floating point, which use the suffixes s,l,t respectively.
994 // Otherwise, we assume that this may be an integer instruction, which comes
995 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
996 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
998 // Check for the various suffix matches.
999 Tmp[Base.size()] = Suffixes[0];
1000 unsigned ErrorInfoIgnore;
1001 MatchResultTy Match1, Match2, Match3, Match4;
1003 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1004 Tmp[Base.size()] = Suffixes[1];
1005 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1006 Tmp[Base.size()] = Suffixes[2];
1007 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1008 Tmp[Base.size()] = Suffixes[3];
1009 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1011 // Restore the old token.
1012 Op->setTokenValue(Base);
1014 // If exactly one matched, then we treat that as a successful match (and the
1015 // instruction will already have been filled in correctly, since the failing
1016 // matches won't have modified it).
1017 unsigned NumSuccessfulMatches =
1018 (Match1 == Match_Success) + (Match2 == Match_Success) +
1019 (Match3 == Match_Success) + (Match4 == Match_Success);
1020 if (NumSuccessfulMatches == 1) {
1021 Out.EmitInstruction(Inst);
1025 // Otherwise, the match failed, try to produce a decent error message.
1027 // If we had multiple suffix matches, then identify this as an ambiguous
1029 if (NumSuccessfulMatches > 1) {
1031 unsigned NumMatches = 0;
1032 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1033 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1034 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1035 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1037 SmallString<126> Msg;
1038 raw_svector_ostream OS(Msg);
1039 OS << "ambiguous instructions require an explicit suffix (could be ";
1040 for (unsigned i = 0; i != NumMatches; ++i) {
1043 if (i + 1 == NumMatches)
1045 OS << "'" << Base << MatchChars[i] << "'";
1048 Error(IDLoc, OS.str());
1052 // Okay, we know that none of the variants matched successfully.
1054 // If all of the instructions reported an invalid mnemonic, then the original
1055 // mnemonic was invalid.
1056 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1057 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1058 if (!WasOriginallyInvalidOperand) {
1059 Error(IDLoc, "invalid instruction mnemonic '" + Base + "'");
1063 // Recover location info for the operand if we know which was the problem.
1064 SMLoc ErrorLoc = IDLoc;
1065 if (OrigErrorInfo != ~0U) {
1066 if (OrigErrorInfo >= Operands.size())
1067 return Error(IDLoc, "too few operands for instruction");
1069 ErrorLoc = ((X86Operand*)Operands[OrigErrorInfo])->getStartLoc();
1070 if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
1073 return Error(ErrorLoc, "invalid operand for instruction");
1076 // If one instruction matched with a missing feature, report this as a
1078 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1079 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1080 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1084 // If one instruction matched with an invalid operand, report this as an
1086 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1087 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1088 Error(IDLoc, "invalid operand for instruction");
1092 // If all of these were an outright failure, report it in a useless way.
1093 // FIXME: We should give nicer diagnostics about the exact failure.
1094 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
1099 bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
1100 StringRef IDVal = DirectiveID.getIdentifier();
1101 if (IDVal == ".word")
1102 return ParseDirectiveWord(2, DirectiveID.getLoc());
1106 /// ParseDirectiveWord
1107 /// ::= .word [ expression (, expression)* ]
1108 bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1109 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1111 const MCExpr *Value;
1112 if (getParser().ParseExpression(Value))
1115 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1117 if (getLexer().is(AsmToken::EndOfStatement))
1120 // FIXME: Improve diagnostic.
1121 if (getLexer().isNot(AsmToken::Comma))
1122 return Error(L, "unexpected token in directive");
1134 extern "C" void LLVMInitializeX86AsmLexer();
1136 // Force static initialization.
1137 extern "C" void LLVMInitializeX86AsmParser() {
1138 RegisterAsmParser<X86ATTAsmParser> X(TheX86_32Target);
1139 RegisterAsmParser<X86ATTAsmParser> Y(TheX86_64Target);
1140 LLVMInitializeX86AsmLexer();
1143 #define GET_REGISTER_MATCHER
1144 #define GET_MATCHER_IMPLEMENTATION
1145 #include "X86GenAsmMatcher.inc"