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/Target/TargetRegistry.h"
13 #include "llvm/MC/MCStreamer.h"
14 #include "llvm/MC/MCExpr.h"
15 #include "llvm/MC/MCInst.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/raw_ostream.h"
34 class X86ATTAsmParser : public MCTargetAsmParser {
39 MCAsmParser &getParser() const { return Parser; }
41 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
43 bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
45 X86Operand *ParseOperand();
46 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
48 bool ParseDirectiveWord(unsigned Size, SMLoc L);
50 bool MatchAndEmitInstruction(SMLoc IDLoc,
51 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
54 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
55 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
56 bool isSrcOp(X86Operand &Op);
58 /// isDstOp - Returns true if operand is either %es:(%rdi) in 64bit mode
59 /// or %es:(%edi) in 32bit mode.
60 bool isDstOp(X86Operand &Op);
62 bool is64BitMode() const {
63 // FIXME: Can tablegen auto-generate this?
64 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
67 /// @name Auto-generated Matcher Functions
70 #define GET_ASSEMBLER_HEADER
71 #include "X86GenAsmMatcher.inc"
76 X86ATTAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
77 : MCTargetAsmParser(), STI(sti), Parser(parser) {
79 // Initialize the set of available features.
80 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
82 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
84 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
85 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
87 virtual bool ParseDirective(AsmToken DirectiveID);
89 } // end anonymous namespace
91 /// @name Auto-generated Match Functions
94 static unsigned MatchRegisterName(StringRef Name);
100 /// X86Operand - Instances of this class represent a parsed X86 machine
102 struct X86Operand : public MCParsedAsmOperand {
110 SMLoc StartLoc, EndLoc;
135 X86Operand(KindTy K, SMLoc Start, SMLoc End)
136 : Kind(K), StartLoc(Start), EndLoc(End) {}
138 /// getStartLoc - Get the location of the first token of this operand.
139 SMLoc getStartLoc() const { return StartLoc; }
140 /// getEndLoc - Get the location of the last token of this operand.
141 SMLoc getEndLoc() const { return EndLoc; }
143 virtual void print(raw_ostream &OS) const {}
145 StringRef getToken() const {
146 assert(Kind == Token && "Invalid access!");
147 return StringRef(Tok.Data, Tok.Length);
149 void setTokenValue(StringRef Value) {
150 assert(Kind == Token && "Invalid access!");
151 Tok.Data = Value.data();
152 Tok.Length = Value.size();
155 unsigned getReg() const {
156 assert(Kind == Register && "Invalid access!");
160 const MCExpr *getImm() const {
161 assert(Kind == Immediate && "Invalid access!");
165 const MCExpr *getMemDisp() const {
166 assert(Kind == Memory && "Invalid access!");
169 unsigned getMemSegReg() const {
170 assert(Kind == Memory && "Invalid access!");
173 unsigned getMemBaseReg() const {
174 assert(Kind == Memory && "Invalid access!");
177 unsigned getMemIndexReg() const {
178 assert(Kind == Memory && "Invalid access!");
181 unsigned getMemScale() const {
182 assert(Kind == Memory && "Invalid access!");
186 bool isToken() const {return Kind == Token; }
188 bool isImm() const { return Kind == Immediate; }
190 bool isImmSExti16i8() const {
194 // If this isn't a constant expr, just assume it fits and let relaxation
196 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
200 // Otherwise, check the value is in a range that makes sense for this
202 uint64_t Value = CE->getValue();
203 return (( Value <= 0x000000000000007FULL)||
204 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
205 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
207 bool isImmSExti32i8() const {
211 // If this isn't a constant expr, just assume it fits and let relaxation
213 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
217 // Otherwise, check the value is in a range that makes sense for this
219 uint64_t Value = CE->getValue();
220 return (( Value <= 0x000000000000007FULL)||
221 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
222 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
224 bool isImmSExti64i8() const {
228 // If this isn't a constant expr, just assume it fits and let relaxation
230 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
234 // Otherwise, check the value is in a range that makes sense for this
236 uint64_t Value = CE->getValue();
237 return (( Value <= 0x000000000000007FULL)||
238 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
240 bool isImmSExti64i32() const {
244 // If this isn't a constant expr, just assume it fits and let relaxation
246 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
250 // Otherwise, check the value is in a range that makes sense for this
252 uint64_t Value = CE->getValue();
253 return (( Value <= 0x000000007FFFFFFFULL)||
254 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
257 bool isMem() const { return Kind == Memory; }
259 bool isAbsMem() const {
260 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
261 !getMemIndexReg() && getMemScale() == 1;
264 bool isReg() const { return Kind == Register; }
266 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
267 // Add as immediates when possible.
268 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
269 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
271 Inst.addOperand(MCOperand::CreateExpr(Expr));
274 void addRegOperands(MCInst &Inst, unsigned N) const {
275 assert(N == 1 && "Invalid number of operands!");
276 Inst.addOperand(MCOperand::CreateReg(getReg()));
279 void addImmOperands(MCInst &Inst, unsigned N) const {
280 assert(N == 1 && "Invalid number of operands!");
281 addExpr(Inst, getImm());
284 void addMemOperands(MCInst &Inst, unsigned N) const {
285 assert((N == 5) && "Invalid number of operands!");
286 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
287 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
288 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
289 addExpr(Inst, getMemDisp());
290 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
293 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
294 assert((N == 1) && "Invalid number of operands!");
295 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
298 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
299 X86Operand *Res = new X86Operand(Token, Loc, Loc);
300 Res->Tok.Data = Str.data();
301 Res->Tok.Length = Str.size();
305 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
306 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
307 Res->Reg.RegNo = RegNo;
311 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
312 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
317 /// Create an absolute memory operand.
318 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
320 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
322 Res->Mem.Disp = Disp;
323 Res->Mem.BaseReg = 0;
324 Res->Mem.IndexReg = 0;
329 /// Create a generalized memory operand.
330 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
331 unsigned BaseReg, unsigned IndexReg,
332 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc) {
333 // We should never just have a displacement, that should be parsed as an
334 // absolute memory operand.
335 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
337 // The scale should always be one of {1,2,4,8}.
338 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
340 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
341 Res->Mem.SegReg = SegReg;
342 Res->Mem.Disp = Disp;
343 Res->Mem.BaseReg = BaseReg;
344 Res->Mem.IndexReg = IndexReg;
345 Res->Mem.Scale = Scale;
350 } // end anonymous namespace.
352 bool X86ATTAsmParser::isSrcOp(X86Operand &Op) {
353 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
355 return (Op.isMem() &&
356 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
357 isa<MCConstantExpr>(Op.Mem.Disp) &&
358 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
359 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
362 bool X86ATTAsmParser::isDstOp(X86Operand &Op) {
363 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
365 return Op.isMem() && Op.Mem.SegReg == X86::ES &&
366 isa<MCConstantExpr>(Op.Mem.Disp) &&
367 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
368 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
371 bool X86ATTAsmParser::ParseRegister(unsigned &RegNo,
372 SMLoc &StartLoc, SMLoc &EndLoc) {
374 const AsmToken &TokPercent = Parser.getTok();
375 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
376 StartLoc = TokPercent.getLoc();
377 Parser.Lex(); // Eat percent token.
379 const AsmToken &Tok = Parser.getTok();
380 if (Tok.isNot(AsmToken::Identifier))
381 return Error(Tok.getLoc(), "invalid register name");
383 // FIXME: Validate register for the current architecture; we have to do
384 // validation later, so maybe there is no need for this here.
385 RegNo = MatchRegisterName(Tok.getString());
387 // If the match failed, try the register name as lowercase.
389 RegNo = MatchRegisterName(LowercaseString(Tok.getString()));
391 // FIXME: This should be done using Requires<In32BitMode> and
392 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions
393 // can be also checked.
394 if (RegNo == X86::RIZ && !is64BitMode())
395 return Error(Tok.getLoc(), "riz register in 64-bit mode only");
397 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
398 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
400 EndLoc = Tok.getLoc();
401 Parser.Lex(); // Eat 'st'
403 // Check to see if we have '(4)' after %st.
404 if (getLexer().isNot(AsmToken::LParen))
409 const AsmToken &IntTok = Parser.getTok();
410 if (IntTok.isNot(AsmToken::Integer))
411 return Error(IntTok.getLoc(), "expected stack index");
412 switch (IntTok.getIntVal()) {
413 case 0: RegNo = X86::ST0; break;
414 case 1: RegNo = X86::ST1; break;
415 case 2: RegNo = X86::ST2; break;
416 case 3: RegNo = X86::ST3; break;
417 case 4: RegNo = X86::ST4; break;
418 case 5: RegNo = X86::ST5; break;
419 case 6: RegNo = X86::ST6; break;
420 case 7: RegNo = X86::ST7; break;
421 default: return Error(IntTok.getLoc(), "invalid stack index");
424 if (getParser().Lex().isNot(AsmToken::RParen))
425 return Error(Parser.getTok().getLoc(), "expected ')'");
427 EndLoc = Tok.getLoc();
428 Parser.Lex(); // Eat ')'
432 // If this is "db[0-7]", match it as an alias
434 if (RegNo == 0 && Tok.getString().size() == 3 &&
435 Tok.getString().startswith("db")) {
436 switch (Tok.getString()[2]) {
437 case '0': RegNo = X86::DR0; break;
438 case '1': RegNo = X86::DR1; break;
439 case '2': RegNo = X86::DR2; break;
440 case '3': RegNo = X86::DR3; break;
441 case '4': RegNo = X86::DR4; break;
442 case '5': RegNo = X86::DR5; break;
443 case '6': RegNo = X86::DR6; break;
444 case '7': RegNo = X86::DR7; break;
448 EndLoc = Tok.getLoc();
449 Parser.Lex(); // Eat it.
455 return Error(Tok.getLoc(), "invalid register name");
457 EndLoc = Tok.getLoc();
458 Parser.Lex(); // Eat identifier token.
462 X86Operand *X86ATTAsmParser::ParseOperand() {
463 switch (getLexer().getKind()) {
465 // Parse a memory operand with no segment register.
466 return ParseMemOperand(0, Parser.getTok().getLoc());
467 case AsmToken::Percent: {
468 // Read the register.
471 if (ParseRegister(RegNo, Start, End)) return 0;
472 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
473 Error(Start, "eiz and riz can only be used as index registers");
477 // If this is a segment register followed by a ':', then this is the start
478 // of a memory reference, otherwise this is a normal register reference.
479 if (getLexer().isNot(AsmToken::Colon))
480 return X86Operand::CreateReg(RegNo, Start, End);
483 getParser().Lex(); // Eat the colon.
484 return ParseMemOperand(RegNo, Start);
486 case AsmToken::Dollar: {
488 SMLoc Start = Parser.getTok().getLoc(), End;
491 if (getParser().ParseExpression(Val, End))
493 return X86Operand::CreateImm(Val, Start, End);
498 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
499 /// has already been parsed if present.
500 X86Operand *X86ATTAsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
502 // We have to disambiguate a parenthesized expression "(4+5)" from the start
503 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
504 // only way to do this without lookahead is to eat the '(' and see what is
506 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
507 if (getLexer().isNot(AsmToken::LParen)) {
509 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
511 // After parsing the base expression we could either have a parenthesized
512 // memory address or not. If not, return now. If so, eat the (.
513 if (getLexer().isNot(AsmToken::LParen)) {
514 // Unless we have a segment register, treat this as an immediate.
516 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
517 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
523 // Okay, we have a '('. We don't know if this is an expression or not, but
524 // so we have to eat the ( to see beyond it.
525 SMLoc LParenLoc = Parser.getTok().getLoc();
526 Parser.Lex(); // Eat the '('.
528 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
529 // Nothing to do here, fall into the code below with the '(' part of the
530 // memory operand consumed.
534 // It must be an parenthesized expression, parse it now.
535 if (getParser().ParseParenExpression(Disp, ExprEnd))
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, LParenLoc, ExprEnd);
544 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
552 // If we reached here, then we just ate the ( of the memory operand. Process
553 // the rest of the memory operand.
554 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
556 if (getLexer().is(AsmToken::Percent)) {
558 if (ParseRegister(BaseReg, L, L)) return 0;
559 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
560 Error(L, "eiz and riz can only be used as index registers");
565 if (getLexer().is(AsmToken::Comma)) {
566 Parser.Lex(); // Eat the comma.
568 // Following the comma we should have either an index register, or a scale
569 // value. We don't support the later form, but we want to parse it
572 // Not that even though it would be completely consistent to support syntax
573 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
574 if (getLexer().is(AsmToken::Percent)) {
576 if (ParseRegister(IndexReg, L, L)) return 0;
578 if (getLexer().isNot(AsmToken::RParen)) {
579 // Parse the scale amount:
580 // ::= ',' [scale-expression]
581 if (getLexer().isNot(AsmToken::Comma)) {
582 Error(Parser.getTok().getLoc(),
583 "expected comma in scale expression");
586 Parser.Lex(); // Eat the comma.
588 if (getLexer().isNot(AsmToken::RParen)) {
589 SMLoc Loc = Parser.getTok().getLoc();
592 if (getParser().ParseAbsoluteExpression(ScaleVal))
595 // Validate the scale amount.
596 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
597 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
600 Scale = (unsigned)ScaleVal;
603 } else if (getLexer().isNot(AsmToken::RParen)) {
604 // A scale amount without an index is ignored.
606 SMLoc Loc = Parser.getTok().getLoc();
609 if (getParser().ParseAbsoluteExpression(Value))
613 Warning(Loc, "scale factor without index register is ignored");
618 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
619 if (getLexer().isNot(AsmToken::RParen)) {
620 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
623 SMLoc MemEnd = Parser.getTok().getLoc();
624 Parser.Lex(); // Eat the ')'.
626 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
630 bool X86ATTAsmParser::
631 ParseInstruction(StringRef Name, SMLoc NameLoc,
632 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
633 StringRef PatchedName = Name;
635 // FIXME: Hack to recognize setneb as setne.
636 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
637 PatchedName != "setb" && PatchedName != "setnb")
638 PatchedName = PatchedName.substr(0, Name.size()-1);
640 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
641 const MCExpr *ExtraImmOp = 0;
642 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
643 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
644 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
645 bool IsVCMP = PatchedName.startswith("vcmp");
646 unsigned SSECCIdx = IsVCMP ? 4 : 3;
647 unsigned SSEComparisonCode = StringSwitch<unsigned>(
648 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
661 .Case("neq_oq", 0x0C)
668 .Case("unord_s", 0x13)
669 .Case("neq_us", 0x14)
670 .Case("nlt_uq", 0x15)
671 .Case("nle_uq", 0x16)
674 .Case("nge_uq", 0x19)
675 .Case("ngt_uq", 0x1A)
676 .Case("false_os", 0x1B)
677 .Case("neq_os", 0x1C)
680 .Case("true_us", 0x1F)
682 if (SSEComparisonCode != ~0U) {
683 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
684 getParser().getContext());
685 if (PatchedName.endswith("ss")) {
686 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
687 } else if (PatchedName.endswith("sd")) {
688 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
689 } else if (PatchedName.endswith("ps")) {
690 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
692 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
693 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
698 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
701 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
704 // Determine whether this is an instruction prefix.
706 Name == "lock" || Name == "rep" ||
707 Name == "repe" || Name == "repz" ||
708 Name == "repne" || Name == "repnz" ||
709 Name == "rex64" || Name == "data16";
712 // This does the actual operand parsing. Don't parse any more if we have a
713 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
714 // just want to parse the "lock" as the first instruction and the "incl" as
716 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
718 // Parse '*' modifier.
719 if (getLexer().is(AsmToken::Star)) {
720 SMLoc Loc = Parser.getTok().getLoc();
721 Operands.push_back(X86Operand::CreateToken("*", Loc));
722 Parser.Lex(); // Eat the star.
725 // Read the first operand.
726 if (X86Operand *Op = ParseOperand())
727 Operands.push_back(Op);
729 Parser.EatToEndOfStatement();
733 while (getLexer().is(AsmToken::Comma)) {
734 Parser.Lex(); // Eat the comma.
736 // Parse and remember the operand.
737 if (X86Operand *Op = ParseOperand())
738 Operands.push_back(Op);
740 Parser.EatToEndOfStatement();
745 if (getLexer().isNot(AsmToken::EndOfStatement)) {
746 SMLoc Loc = getLexer().getLoc();
747 Parser.EatToEndOfStatement();
748 return Error(Loc, "unexpected token in argument list");
752 if (getLexer().is(AsmToken::EndOfStatement))
753 Parser.Lex(); // Consume the EndOfStatement
754 else if (isPrefix && getLexer().is(AsmToken::Slash))
755 Parser.Lex(); // Consume the prefix separator Slash
757 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
758 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
759 // documented form in various unofficial manuals, so a lot of code uses it.
760 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
761 Operands.size() == 3) {
762 X86Operand &Op = *(X86Operand*)Operands.back();
763 if (Op.isMem() && Op.Mem.SegReg == 0 &&
764 isa<MCConstantExpr>(Op.Mem.Disp) &&
765 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
766 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
767 SMLoc Loc = Op.getEndLoc();
768 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
772 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
773 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
774 Operands.size() == 3) {
775 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
776 if (Op.isMem() && Op.Mem.SegReg == 0 &&
777 isa<MCConstantExpr>(Op.Mem.Disp) &&
778 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
779 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
780 SMLoc Loc = Op.getEndLoc();
781 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
785 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
786 if (Name.startswith("ins") && Operands.size() == 3 &&
787 (Name == "insb" || Name == "insw" || Name == "insl")) {
788 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
789 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
790 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
798 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
799 if (Name.startswith("outs") && Operands.size() == 3 &&
800 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
801 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
802 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
803 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
811 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
812 if (Name.startswith("movs") && Operands.size() == 3 &&
813 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
814 (is64BitMode() && Name == "movsq"))) {
815 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
816 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
817 if (isSrcOp(Op) && isDstOp(Op2)) {
824 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
825 if (Name.startswith("lods") && Operands.size() == 3 &&
826 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
827 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
828 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
829 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
830 if (isSrcOp(*Op1) && Op2->isReg()) {
832 unsigned reg = Op2->getReg();
833 bool isLods = Name == "lods";
834 if (reg == X86::AL && (isLods || Name == "lodsb"))
836 else if (reg == X86::AX && (isLods || Name == "lodsw"))
838 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
840 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
850 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
854 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
855 if (Name.startswith("stos") && Operands.size() == 3 &&
856 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
857 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
858 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
859 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
860 if (isDstOp(*Op2) && Op1->isReg()) {
862 unsigned reg = Op1->getReg();
863 bool isStos = Name == "stos";
864 if (reg == X86::AL && (isStos || Name == "stosb"))
866 else if (reg == X86::AX && (isStos || Name == "stosw"))
868 else if (reg == X86::EAX && (isStos || Name == "stosl"))
870 else if (reg == X86::RAX && (isStos || Name == "stosq"))
880 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
885 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
887 if ((Name.startswith("shr") || Name.startswith("sar") ||
888 Name.startswith("shl") || Name.startswith("sal") ||
889 Name.startswith("rcl") || Name.startswith("rcr") ||
890 Name.startswith("rol") || Name.startswith("ror")) &&
891 Operands.size() == 3) {
892 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
893 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
894 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
896 Operands.erase(Operands.begin() + 1);
900 // Transforms "int $3" into "int3" as a size optimization. We can't write an
901 // instalias with an immediate operand yet.
902 if (Name == "int" && Operands.size() == 2) {
903 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
904 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
905 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
907 Operands.erase(Operands.begin() + 1);
908 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
915 bool X86ATTAsmParser::
916 MatchAndEmitInstruction(SMLoc IDLoc,
917 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
919 assert(!Operands.empty() && "Unexpect empty operand list!");
920 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
921 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
923 // First, handle aliases that expand to multiple instructions.
924 // FIXME: This should be replaced with a real .td file alias mechanism.
925 // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
927 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
928 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
929 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
930 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
932 Inst.setOpcode(X86::WAIT);
933 Out.EmitInstruction(Inst);
936 StringSwitch<const char*>(Op->getToken())
937 .Case("finit", "fninit")
938 .Case("fsave", "fnsave")
939 .Case("fstcw", "fnstcw")
940 .Case("fstcww", "fnstcw")
941 .Case("fstenv", "fnstenv")
942 .Case("fstsw", "fnstsw")
943 .Case("fstsww", "fnstsw")
944 .Case("fclex", "fnclex")
946 assert(Repl && "Unknown wait-prefixed instruction");
948 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
951 bool WasOriginallyInvalidOperand = false;
952 unsigned OrigErrorInfo;
955 // First, try a direct match.
956 switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo)) {
958 Out.EmitInstruction(Inst);
960 case Match_MissingFeature:
961 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
963 case Match_ConversionFail:
964 return Error(IDLoc, "unable to convert operands to instruction");
965 case Match_InvalidOperand:
966 WasOriginallyInvalidOperand = true;
968 case Match_MnemonicFail:
972 // FIXME: Ideally, we would only attempt suffix matches for things which are
973 // valid prefixes, and we could just infer the right unambiguous
974 // type. However, that requires substantially more matcher support than the
977 // Change the operand to point to a temporary token.
978 StringRef Base = Op->getToken();
982 Op->setTokenValue(Tmp.str());
984 // If this instruction starts with an 'f', then it is a floating point stack
985 // instruction. These come in up to three forms for 32-bit, 64-bit, and
986 // 80-bit floating point, which use the suffixes s,l,t respectively.
988 // Otherwise, we assume that this may be an integer instruction, which comes
989 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
990 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
992 // Check for the various suffix matches.
993 Tmp[Base.size()] = Suffixes[0];
994 unsigned ErrorInfoIgnore;
995 MatchResultTy Match1, Match2, Match3, Match4;
997 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
998 Tmp[Base.size()] = Suffixes[1];
999 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1000 Tmp[Base.size()] = Suffixes[2];
1001 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1002 Tmp[Base.size()] = Suffixes[3];
1003 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1005 // Restore the old token.
1006 Op->setTokenValue(Base);
1008 // If exactly one matched, then we treat that as a successful match (and the
1009 // instruction will already have been filled in correctly, since the failing
1010 // matches won't have modified it).
1011 unsigned NumSuccessfulMatches =
1012 (Match1 == Match_Success) + (Match2 == Match_Success) +
1013 (Match3 == Match_Success) + (Match4 == Match_Success);
1014 if (NumSuccessfulMatches == 1) {
1015 Out.EmitInstruction(Inst);
1019 // Otherwise, the match failed, try to produce a decent error message.
1021 // If we had multiple suffix matches, then identify this as an ambiguous
1023 if (NumSuccessfulMatches > 1) {
1025 unsigned NumMatches = 0;
1026 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1027 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1028 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1029 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1031 SmallString<126> Msg;
1032 raw_svector_ostream OS(Msg);
1033 OS << "ambiguous instructions require an explicit suffix (could be ";
1034 for (unsigned i = 0; i != NumMatches; ++i) {
1037 if (i + 1 == NumMatches)
1039 OS << "'" << Base << MatchChars[i] << "'";
1042 Error(IDLoc, OS.str());
1046 // Okay, we know that none of the variants matched successfully.
1048 // If all of the instructions reported an invalid mnemonic, then the original
1049 // mnemonic was invalid.
1050 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1051 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1052 if (!WasOriginallyInvalidOperand) {
1053 Error(IDLoc, "invalid instruction mnemonic '" + Base + "'");
1057 // Recover location info for the operand if we know which was the problem.
1058 SMLoc ErrorLoc = IDLoc;
1059 if (OrigErrorInfo != ~0U) {
1060 if (OrigErrorInfo >= Operands.size())
1061 return Error(IDLoc, "too few operands for instruction");
1063 ErrorLoc = ((X86Operand*)Operands[OrigErrorInfo])->getStartLoc();
1064 if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
1067 return Error(ErrorLoc, "invalid operand for instruction");
1070 // If one instruction matched with a missing feature, report this as a
1072 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1073 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1074 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1078 // If one instruction matched with an invalid operand, report this as an
1080 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1081 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1082 Error(IDLoc, "invalid operand for instruction");
1086 // If all of these were an outright failure, report it in a useless way.
1087 // FIXME: We should give nicer diagnostics about the exact failure.
1088 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
1093 bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
1094 StringRef IDVal = DirectiveID.getIdentifier();
1095 if (IDVal == ".word")
1096 return ParseDirectiveWord(2, DirectiveID.getLoc());
1100 /// ParseDirectiveWord
1101 /// ::= .word [ expression (, expression)* ]
1102 bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1103 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1105 const MCExpr *Value;
1106 if (getParser().ParseExpression(Value))
1109 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1111 if (getLexer().is(AsmToken::EndOfStatement))
1114 // FIXME: Improve diagnostic.
1115 if (getLexer().isNot(AsmToken::Comma))
1116 return Error(L, "unexpected token in directive");
1128 extern "C" void LLVMInitializeX86AsmLexer();
1130 // Force static initialization.
1131 extern "C" void LLVMInitializeX86AsmParser() {
1132 RegisterMCAsmParser<X86ATTAsmParser> X(TheX86_32Target);
1133 RegisterMCAsmParser<X86ATTAsmParser> Y(TheX86_64Target);
1134 LLVMInitializeX86AsmLexer();
1137 #define GET_REGISTER_MATCHER
1138 #define GET_MATCHER_IMPLEMENTATION
1139 #include "X86GenAsmMatcher.inc"