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/OwningPtr.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/Support/SourceMgr.h"
29 #include "llvm/Support/raw_ostream.h"
36 class X86ATTAsmParser : public TargetAsmParser {
41 MCAsmParser &getParser() const { return Parser; }
43 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
45 bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
47 X86Operand *ParseOperand();
48 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
50 bool ParseDirectiveWord(unsigned Size, 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 /// @name Auto-generated Matcher Functions
72 #define GET_ASSEMBLER_HEADER
73 #include "X86GenAsmMatcher.inc"
78 X86ATTAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
79 : TargetAsmParser(), STI(sti), Parser(parser) {
81 // Initialize the set of available features.
82 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
84 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
86 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
87 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
89 virtual bool ParseDirective(AsmToken DirectiveID);
91 } // end anonymous namespace
93 /// @name Auto-generated Match Functions
96 static unsigned MatchRegisterName(StringRef Name);
102 /// X86Operand - Instances of this class represent a parsed X86 machine
104 struct X86Operand : public MCParsedAsmOperand {
112 SMLoc StartLoc, EndLoc;
137 X86Operand(KindTy K, SMLoc Start, SMLoc End)
138 : Kind(K), StartLoc(Start), EndLoc(End) {}
140 /// getStartLoc - Get the location of the first token of this operand.
141 SMLoc getStartLoc() const { return StartLoc; }
142 /// getEndLoc - Get the location of the last token of this operand.
143 SMLoc getEndLoc() const { return EndLoc; }
145 virtual void print(raw_ostream &OS) const {}
147 StringRef getToken() const {
148 assert(Kind == Token && "Invalid access!");
149 return StringRef(Tok.Data, Tok.Length);
151 void setTokenValue(StringRef Value) {
152 assert(Kind == Token && "Invalid access!");
153 Tok.Data = Value.data();
154 Tok.Length = Value.size();
157 unsigned getReg() const {
158 assert(Kind == Register && "Invalid access!");
162 const MCExpr *getImm() const {
163 assert(Kind == Immediate && "Invalid access!");
167 const MCExpr *getMemDisp() const {
168 assert(Kind == Memory && "Invalid access!");
171 unsigned getMemSegReg() const {
172 assert(Kind == Memory && "Invalid access!");
175 unsigned getMemBaseReg() const {
176 assert(Kind == Memory && "Invalid access!");
179 unsigned getMemIndexReg() const {
180 assert(Kind == Memory && "Invalid access!");
183 unsigned getMemScale() const {
184 assert(Kind == Memory && "Invalid access!");
188 bool isToken() const {return Kind == Token; }
190 bool isImm() const { return Kind == Immediate; }
192 bool isImmSExti16i8() const {
196 // If this isn't a constant expr, just assume it fits and let relaxation
198 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
202 // Otherwise, check the value is in a range that makes sense for this
204 uint64_t Value = CE->getValue();
205 return (( Value <= 0x000000000000007FULL)||
206 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
207 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
209 bool isImmSExti32i8() const {
213 // If this isn't a constant expr, just assume it fits and let relaxation
215 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
219 // Otherwise, check the value is in a range that makes sense for this
221 uint64_t Value = CE->getValue();
222 return (( Value <= 0x000000000000007FULL)||
223 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
224 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
226 bool isImmSExti64i8() const {
230 // If this isn't a constant expr, just assume it fits and let relaxation
232 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
236 // Otherwise, check the value is in a range that makes sense for this
238 uint64_t Value = CE->getValue();
239 return (( Value <= 0x000000000000007FULL)||
240 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
242 bool isImmSExti64i32() const {
246 // If this isn't a constant expr, just assume it fits and let relaxation
248 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
252 // Otherwise, check the value is in a range that makes sense for this
254 uint64_t Value = CE->getValue();
255 return (( Value <= 0x000000007FFFFFFFULL)||
256 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
259 bool isMem() const { return Kind == Memory; }
261 bool isAbsMem() const {
262 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
263 !getMemIndexReg() && getMemScale() == 1;
266 bool isReg() const { return Kind == Register; }
268 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
269 // Add as immediates when possible.
270 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
271 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
273 Inst.addOperand(MCOperand::CreateExpr(Expr));
276 void addRegOperands(MCInst &Inst, unsigned N) const {
277 assert(N == 1 && "Invalid number of operands!");
278 Inst.addOperand(MCOperand::CreateReg(getReg()));
281 void addImmOperands(MCInst &Inst, unsigned N) const {
282 assert(N == 1 && "Invalid number of operands!");
283 addExpr(Inst, getImm());
286 void addMemOperands(MCInst &Inst, unsigned N) const {
287 assert((N == 5) && "Invalid number of operands!");
288 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
289 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
290 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
291 addExpr(Inst, getMemDisp());
292 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
295 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
296 assert((N == 1) && "Invalid number of operands!");
297 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
300 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
301 X86Operand *Res = new X86Operand(Token, Loc, Loc);
302 Res->Tok.Data = Str.data();
303 Res->Tok.Length = Str.size();
307 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
308 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
309 Res->Reg.RegNo = RegNo;
313 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
314 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
319 /// Create an absolute memory operand.
320 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
322 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
324 Res->Mem.Disp = Disp;
325 Res->Mem.BaseReg = 0;
326 Res->Mem.IndexReg = 0;
331 /// Create a generalized memory operand.
332 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
333 unsigned BaseReg, unsigned IndexReg,
334 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc) {
335 // We should never just have a displacement, that should be parsed as an
336 // absolute memory operand.
337 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
339 // The scale should always be one of {1,2,4,8}.
340 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
342 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
343 Res->Mem.SegReg = SegReg;
344 Res->Mem.Disp = Disp;
345 Res->Mem.BaseReg = BaseReg;
346 Res->Mem.IndexReg = IndexReg;
347 Res->Mem.Scale = Scale;
352 } // end anonymous namespace.
354 bool X86ATTAsmParser::isSrcOp(X86Operand &Op) {
355 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
357 return (Op.isMem() &&
358 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
359 isa<MCConstantExpr>(Op.Mem.Disp) &&
360 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
361 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
364 bool X86ATTAsmParser::isDstOp(X86Operand &Op) {
365 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
367 return Op.isMem() && Op.Mem.SegReg == X86::ES &&
368 isa<MCConstantExpr>(Op.Mem.Disp) &&
369 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
370 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
373 bool X86ATTAsmParser::ParseRegister(unsigned &RegNo,
374 SMLoc &StartLoc, SMLoc &EndLoc) {
376 const AsmToken &TokPercent = Parser.getTok();
377 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
378 StartLoc = TokPercent.getLoc();
379 Parser.Lex(); // Eat percent token.
381 const AsmToken &Tok = Parser.getTok();
382 if (Tok.isNot(AsmToken::Identifier))
383 return Error(Tok.getLoc(), "invalid register name");
385 // FIXME: Validate register for the current architecture; we have to do
386 // validation later, so maybe there is no need for this here.
387 RegNo = MatchRegisterName(Tok.getString());
389 // If the match failed, try the register name as lowercase.
391 RegNo = MatchRegisterName(LowercaseString(Tok.getString()));
393 // FIXME: This should be done using Requires<In32BitMode> and
394 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions
395 // can be also checked.
396 if (RegNo == X86::RIZ && !is64BitMode())
397 return Error(Tok.getLoc(), "riz register in 64-bit mode only");
399 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
400 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
402 EndLoc = Tok.getLoc();
403 Parser.Lex(); // Eat 'st'
405 // Check to see if we have '(4)' after %st.
406 if (getLexer().isNot(AsmToken::LParen))
411 const AsmToken &IntTok = Parser.getTok();
412 if (IntTok.isNot(AsmToken::Integer))
413 return Error(IntTok.getLoc(), "expected stack index");
414 switch (IntTok.getIntVal()) {
415 case 0: RegNo = X86::ST0; break;
416 case 1: RegNo = X86::ST1; break;
417 case 2: RegNo = X86::ST2; break;
418 case 3: RegNo = X86::ST3; break;
419 case 4: RegNo = X86::ST4; break;
420 case 5: RegNo = X86::ST5; break;
421 case 6: RegNo = X86::ST6; break;
422 case 7: RegNo = X86::ST7; break;
423 default: return Error(IntTok.getLoc(), "invalid stack index");
426 if (getParser().Lex().isNot(AsmToken::RParen))
427 return Error(Parser.getTok().getLoc(), "expected ')'");
429 EndLoc = Tok.getLoc();
430 Parser.Lex(); // Eat ')'
434 // If this is "db[0-7]", match it as an alias
436 if (RegNo == 0 && Tok.getString().size() == 3 &&
437 Tok.getString().startswith("db")) {
438 switch (Tok.getString()[2]) {
439 case '0': RegNo = X86::DR0; break;
440 case '1': RegNo = X86::DR1; break;
441 case '2': RegNo = X86::DR2; break;
442 case '3': RegNo = X86::DR3; break;
443 case '4': RegNo = X86::DR4; break;
444 case '5': RegNo = X86::DR5; break;
445 case '6': RegNo = X86::DR6; break;
446 case '7': RegNo = X86::DR7; break;
450 EndLoc = Tok.getLoc();
451 Parser.Lex(); // Eat it.
457 return Error(Tok.getLoc(), "invalid register name");
459 EndLoc = Tok.getLoc();
460 Parser.Lex(); // Eat identifier token.
464 X86Operand *X86ATTAsmParser::ParseOperand() {
465 switch (getLexer().getKind()) {
467 // Parse a memory operand with no segment register.
468 return ParseMemOperand(0, Parser.getTok().getLoc());
469 case AsmToken::Percent: {
470 // Read the register.
473 if (ParseRegister(RegNo, Start, End)) return 0;
474 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
475 Error(Start, "eiz and riz can only be used as index registers");
479 // If this is a segment register followed by a ':', then this is the start
480 // of a memory reference, otherwise this is a normal register reference.
481 if (getLexer().isNot(AsmToken::Colon))
482 return X86Operand::CreateReg(RegNo, Start, End);
485 getParser().Lex(); // Eat the colon.
486 return ParseMemOperand(RegNo, Start);
488 case AsmToken::Dollar: {
490 SMLoc Start = Parser.getTok().getLoc(), End;
493 if (getParser().ParseExpression(Val, End))
495 return X86Operand::CreateImm(Val, Start, End);
500 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
501 /// has already been parsed if present.
502 X86Operand *X86ATTAsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
504 // We have to disambiguate a parenthesized expression "(4+5)" from the start
505 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
506 // only way to do this without lookahead is to eat the '(' and see what is
508 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
509 if (getLexer().isNot(AsmToken::LParen)) {
511 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
513 // After parsing the base expression we could either have a parenthesized
514 // memory address or not. If not, return now. If so, eat the (.
515 if (getLexer().isNot(AsmToken::LParen)) {
516 // Unless we have a segment register, treat this as an immediate.
518 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
519 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
525 // Okay, we have a '('. We don't know if this is an expression or not, but
526 // so we have to eat the ( to see beyond it.
527 SMLoc LParenLoc = Parser.getTok().getLoc();
528 Parser.Lex(); // Eat the '('.
530 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
531 // Nothing to do here, fall into the code below with the '(' part of the
532 // memory operand consumed.
536 // It must be an parenthesized expression, parse it now.
537 if (getParser().ParseParenExpression(Disp, ExprEnd))
540 // After parsing the base expression we could either have a parenthesized
541 // memory address or not. If not, return now. If so, eat the (.
542 if (getLexer().isNot(AsmToken::LParen)) {
543 // Unless we have a segment register, treat this as an immediate.
545 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
546 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
554 // If we reached here, then we just ate the ( of the memory operand. Process
555 // the rest of the memory operand.
556 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
558 if (getLexer().is(AsmToken::Percent)) {
560 if (ParseRegister(BaseReg, L, L)) return 0;
561 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
562 Error(L, "eiz and riz can only be used as index registers");
567 if (getLexer().is(AsmToken::Comma)) {
568 Parser.Lex(); // Eat the comma.
570 // Following the comma we should have either an index register, or a scale
571 // value. We don't support the later form, but we want to parse it
574 // Not that even though it would be completely consistent to support syntax
575 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
576 if (getLexer().is(AsmToken::Percent)) {
578 if (ParseRegister(IndexReg, L, L)) return 0;
580 if (getLexer().isNot(AsmToken::RParen)) {
581 // Parse the scale amount:
582 // ::= ',' [scale-expression]
583 if (getLexer().isNot(AsmToken::Comma)) {
584 Error(Parser.getTok().getLoc(),
585 "expected comma in scale expression");
588 Parser.Lex(); // Eat the comma.
590 if (getLexer().isNot(AsmToken::RParen)) {
591 SMLoc Loc = Parser.getTok().getLoc();
594 if (getParser().ParseAbsoluteExpression(ScaleVal))
597 // Validate the scale amount.
598 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
599 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
602 Scale = (unsigned)ScaleVal;
605 } else if (getLexer().isNot(AsmToken::RParen)) {
606 // A scale amount without an index is ignored.
608 SMLoc Loc = Parser.getTok().getLoc();
611 if (getParser().ParseAbsoluteExpression(Value))
615 Warning(Loc, "scale factor without index register is ignored");
620 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
621 if (getLexer().isNot(AsmToken::RParen)) {
622 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
625 SMLoc MemEnd = Parser.getTok().getLoc();
626 Parser.Lex(); // Eat the ')'.
628 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
632 bool X86ATTAsmParser::
633 ParseInstruction(StringRef Name, SMLoc NameLoc,
634 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
635 StringRef PatchedName = Name;
637 // FIXME: Hack to recognize setneb as setne.
638 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
639 PatchedName != "setb" && PatchedName != "setnb")
640 PatchedName = PatchedName.substr(0, Name.size()-1);
642 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
643 const MCExpr *ExtraImmOp = 0;
644 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
645 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
646 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
647 bool IsVCMP = PatchedName.startswith("vcmp");
648 unsigned SSECCIdx = IsVCMP ? 4 : 3;
649 unsigned SSEComparisonCode = StringSwitch<unsigned>(
650 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
663 .Case("neq_oq", 0x0C)
670 .Case("unord_s", 0x13)
671 .Case("neq_us", 0x14)
672 .Case("nlt_uq", 0x15)
673 .Case("nle_uq", 0x16)
676 .Case("nge_uq", 0x19)
677 .Case("ngt_uq", 0x1A)
678 .Case("false_os", 0x1B)
679 .Case("neq_os", 0x1C)
682 .Case("true_us", 0x1F)
684 if (SSEComparisonCode != ~0U) {
685 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
686 getParser().getContext());
687 if (PatchedName.endswith("ss")) {
688 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
689 } else if (PatchedName.endswith("sd")) {
690 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
691 } else if (PatchedName.endswith("ps")) {
692 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
694 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
695 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
700 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
703 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
706 // Determine whether this is an instruction prefix.
708 Name == "lock" || Name == "rep" ||
709 Name == "repe" || Name == "repz" ||
710 Name == "repne" || Name == "repnz" ||
711 Name == "rex64" || Name == "data16";
714 // This does the actual operand parsing. Don't parse any more if we have a
715 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
716 // just want to parse the "lock" as the first instruction and the "incl" as
718 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
720 // Parse '*' modifier.
721 if (getLexer().is(AsmToken::Star)) {
722 SMLoc Loc = Parser.getTok().getLoc();
723 Operands.push_back(X86Operand::CreateToken("*", Loc));
724 Parser.Lex(); // Eat the star.
727 // Read the first operand.
728 if (X86Operand *Op = ParseOperand())
729 Operands.push_back(Op);
731 Parser.EatToEndOfStatement();
735 while (getLexer().is(AsmToken::Comma)) {
736 Parser.Lex(); // Eat the comma.
738 // Parse and remember the operand.
739 if (X86Operand *Op = ParseOperand())
740 Operands.push_back(Op);
742 Parser.EatToEndOfStatement();
747 if (getLexer().isNot(AsmToken::EndOfStatement)) {
748 SMLoc Loc = getLexer().getLoc();
749 Parser.EatToEndOfStatement();
750 return Error(Loc, "unexpected token in argument list");
754 if (getLexer().is(AsmToken::EndOfStatement))
755 Parser.Lex(); // Consume the EndOfStatement
756 else if (isPrefix && getLexer().is(AsmToken::Slash))
757 Parser.Lex(); // Consume the prefix separator Slash
759 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
760 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
761 // documented form in various unofficial manuals, so a lot of code uses it.
762 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
763 Operands.size() == 3) {
764 X86Operand &Op = *(X86Operand*)Operands.back();
765 if (Op.isMem() && Op.Mem.SegReg == 0 &&
766 isa<MCConstantExpr>(Op.Mem.Disp) &&
767 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
768 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
769 SMLoc Loc = Op.getEndLoc();
770 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
774 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
775 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
776 Operands.size() == 3) {
777 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
778 if (Op.isMem() && Op.Mem.SegReg == 0 &&
779 isa<MCConstantExpr>(Op.Mem.Disp) &&
780 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
781 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
782 SMLoc Loc = Op.getEndLoc();
783 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
787 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
788 if (Name.startswith("ins") && Operands.size() == 3 &&
789 (Name == "insb" || Name == "insw" || Name == "insl")) {
790 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
791 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
792 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
800 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
801 if (Name.startswith("outs") && Operands.size() == 3 &&
802 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
803 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
804 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
805 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
813 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
814 if (Name.startswith("movs") && Operands.size() == 3 &&
815 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
816 (is64BitMode() && Name == "movsq"))) {
817 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
818 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
819 if (isSrcOp(Op) && isDstOp(Op2)) {
826 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
827 if (Name.startswith("lods") && Operands.size() == 3 &&
828 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
829 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
830 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
831 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
832 if (isSrcOp(*Op1) && Op2->isReg()) {
834 unsigned reg = Op2->getReg();
835 bool isLods = Name == "lods";
836 if (reg == X86::AL && (isLods || Name == "lodsb"))
838 else if (reg == X86::AX && (isLods || Name == "lodsw"))
840 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
842 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
852 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
856 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
857 if (Name.startswith("stos") && Operands.size() == 3 &&
858 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
859 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
860 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
861 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
862 if (isDstOp(*Op2) && Op1->isReg()) {
864 unsigned reg = Op1->getReg();
865 bool isStos = Name == "stos";
866 if (reg == X86::AL && (isStos || Name == "stosb"))
868 else if (reg == X86::AX && (isStos || Name == "stosw"))
870 else if (reg == X86::EAX && (isStos || Name == "stosl"))
872 else if (reg == X86::RAX && (isStos || Name == "stosq"))
882 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
887 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
889 if ((Name.startswith("shr") || Name.startswith("sar") ||
890 Name.startswith("shl") || Name.startswith("sal") ||
891 Name.startswith("rcl") || Name.startswith("rcr") ||
892 Name.startswith("rol") || Name.startswith("ror")) &&
893 Operands.size() == 3) {
894 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
895 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
896 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
898 Operands.erase(Operands.begin() + 1);
902 // Transforms "int $3" into "int3" as a size optimization. We can't write an
903 // instalias with an immediate operand yet.
904 if (Name == "int" && Operands.size() == 2) {
905 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
906 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
907 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
909 Operands.erase(Operands.begin() + 1);
910 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
917 bool X86ATTAsmParser::
918 MatchAndEmitInstruction(SMLoc IDLoc,
919 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
921 assert(!Operands.empty() && "Unexpect empty operand list!");
922 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
923 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
925 // First, handle aliases that expand to multiple instructions.
926 // FIXME: This should be replaced with a real .td file alias mechanism.
927 // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
929 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
930 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
931 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
932 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
934 Inst.setOpcode(X86::WAIT);
935 Out.EmitInstruction(Inst);
938 StringSwitch<const char*>(Op->getToken())
939 .Case("finit", "fninit")
940 .Case("fsave", "fnsave")
941 .Case("fstcw", "fnstcw")
942 .Case("fstcww", "fnstcw")
943 .Case("fstenv", "fnstenv")
944 .Case("fstsw", "fnstsw")
945 .Case("fstsww", "fnstsw")
946 .Case("fclex", "fnclex")
948 assert(Repl && "Unknown wait-prefixed instruction");
950 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
953 bool WasOriginallyInvalidOperand = false;
954 unsigned OrigErrorInfo;
957 // First, try a direct match.
958 switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo)) {
960 Out.EmitInstruction(Inst);
962 case Match_MissingFeature:
963 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
965 case Match_ConversionFail:
966 return Error(IDLoc, "unable to convert operands to instruction");
967 case Match_InvalidOperand:
968 WasOriginallyInvalidOperand = true;
970 case Match_MnemonicFail:
974 // FIXME: Ideally, we would only attempt suffix matches for things which are
975 // valid prefixes, and we could just infer the right unambiguous
976 // type. However, that requires substantially more matcher support than the
979 // Change the operand to point to a temporary token.
980 StringRef Base = Op->getToken();
984 Op->setTokenValue(Tmp.str());
986 // If this instruction starts with an 'f', then it is a floating point stack
987 // instruction. These come in up to three forms for 32-bit, 64-bit, and
988 // 80-bit floating point, which use the suffixes s,l,t respectively.
990 // Otherwise, we assume that this may be an integer instruction, which comes
991 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
992 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
994 // Check for the various suffix matches.
995 Tmp[Base.size()] = Suffixes[0];
996 unsigned ErrorInfoIgnore;
997 MatchResultTy Match1, Match2, Match3, Match4;
999 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1000 Tmp[Base.size()] = Suffixes[1];
1001 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1002 Tmp[Base.size()] = Suffixes[2];
1003 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1004 Tmp[Base.size()] = Suffixes[3];
1005 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1007 // Restore the old token.
1008 Op->setTokenValue(Base);
1010 // If exactly one matched, then we treat that as a successful match (and the
1011 // instruction will already have been filled in correctly, since the failing
1012 // matches won't have modified it).
1013 unsigned NumSuccessfulMatches =
1014 (Match1 == Match_Success) + (Match2 == Match_Success) +
1015 (Match3 == Match_Success) + (Match4 == Match_Success);
1016 if (NumSuccessfulMatches == 1) {
1017 Out.EmitInstruction(Inst);
1021 // Otherwise, the match failed, try to produce a decent error message.
1023 // If we had multiple suffix matches, then identify this as an ambiguous
1025 if (NumSuccessfulMatches > 1) {
1027 unsigned NumMatches = 0;
1028 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1029 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1030 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1031 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1033 SmallString<126> Msg;
1034 raw_svector_ostream OS(Msg);
1035 OS << "ambiguous instructions require an explicit suffix (could be ";
1036 for (unsigned i = 0; i != NumMatches; ++i) {
1039 if (i + 1 == NumMatches)
1041 OS << "'" << Base << MatchChars[i] << "'";
1044 Error(IDLoc, OS.str());
1048 // Okay, we know that none of the variants matched successfully.
1050 // If all of the instructions reported an invalid mnemonic, then the original
1051 // mnemonic was invalid.
1052 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1053 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1054 if (!WasOriginallyInvalidOperand) {
1055 Error(IDLoc, "invalid instruction mnemonic '" + Base + "'");
1059 // Recover location info for the operand if we know which was the problem.
1060 SMLoc ErrorLoc = IDLoc;
1061 if (OrigErrorInfo != ~0U) {
1062 if (OrigErrorInfo >= Operands.size())
1063 return Error(IDLoc, "too few operands for instruction");
1065 ErrorLoc = ((X86Operand*)Operands[OrigErrorInfo])->getStartLoc();
1066 if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
1069 return Error(ErrorLoc, "invalid operand for instruction");
1072 // If one instruction matched with a missing feature, report this as a
1074 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1075 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1076 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1080 // If one instruction matched with an invalid operand, report this as an
1082 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1083 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1084 Error(IDLoc, "invalid operand for instruction");
1088 // If all of these were an outright failure, report it in a useless way.
1089 // FIXME: We should give nicer diagnostics about the exact failure.
1090 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
1095 bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
1096 StringRef IDVal = DirectiveID.getIdentifier();
1097 if (IDVal == ".word")
1098 return ParseDirectiveWord(2, DirectiveID.getLoc());
1102 /// ParseDirectiveWord
1103 /// ::= .word [ expression (, expression)* ]
1104 bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1105 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1107 const MCExpr *Value;
1108 if (getParser().ParseExpression(Value))
1111 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1113 if (getLexer().is(AsmToken::EndOfStatement))
1116 // FIXME: Improve diagnostic.
1117 if (getLexer().isNot(AsmToken::Comma))
1118 return Error(L, "unexpected token in directive");
1130 extern "C" void LLVMInitializeX86AsmLexer();
1132 // Force static initialization.
1133 extern "C" void LLVMInitializeX86AsmParser() {
1134 RegisterAsmParser<X86ATTAsmParser> X(TheX86_32Target);
1135 RegisterAsmParser<X86ATTAsmParser> Y(TheX86_64Target);
1136 LLVMInitializeX86AsmLexer();
1139 #define GET_REGISTER_MATCHER
1140 #define GET_MATCHER_IMPLEMENTATION
1141 #include "X86GenAsmMatcher.inc"