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/MC/TargetAsmParser.h"
12 #include "X86Subtarget.h"
13 #include "llvm/Target/TargetRegistry.h"
14 #include "llvm/MC/MCStreamer.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCInst.h"
17 #include "llvm/MC/MCSubtargetInfo.h"
18 #include "llvm/MC/MCParser/MCAsmLexer.h"
19 #include "llvm/MC/MCParser/MCAsmParser.h"
20 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
21 #include "llvm/ADT/OwningPtr.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"
35 class X86ATTAsmParser : public TargetAsmParser {
40 MCAsmParser &getParser() const { return Parser; }
42 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
44 bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
46 X86Operand *ParseOperand();
47 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
49 bool ParseDirectiveWord(unsigned Size, SMLoc L);
51 bool MatchAndEmitInstruction(SMLoc IDLoc,
52 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
55 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
56 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
57 bool isSrcOp(X86Operand &Op);
59 /// isDstOp - Returns true if operand is either %es:(%rdi) in 64bit mode
60 /// or %es:(%edi) in 32bit mode.
61 bool isDstOp(X86Operand &Op);
63 bool is64BitMode() const {
64 // FIXME: Can tablegen auto-generate this?
65 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
68 /// @name Auto-generated Matcher Functions
71 #define GET_ASSEMBLER_HEADER
72 #include "X86GenAsmMatcher.inc"
77 X86ATTAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
78 : TargetAsmParser(), STI(sti), Parser(parser) {
80 // Initialize the set of available features.
81 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
83 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
85 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
86 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
88 virtual bool ParseDirective(AsmToken DirectiveID);
90 } // end anonymous namespace
92 /// @name Auto-generated Match Functions
95 static unsigned MatchRegisterName(StringRef Name);
101 /// X86Operand - Instances of this class represent a parsed X86 machine
103 struct X86Operand : public MCParsedAsmOperand {
111 SMLoc StartLoc, EndLoc;
136 X86Operand(KindTy K, SMLoc Start, SMLoc End)
137 : Kind(K), StartLoc(Start), EndLoc(End) {}
139 /// getStartLoc - Get the location of the first token of this operand.
140 SMLoc getStartLoc() const { return StartLoc; }
141 /// getEndLoc - Get the location of the last token of this operand.
142 SMLoc getEndLoc() const { return EndLoc; }
144 virtual void print(raw_ostream &OS) const {}
146 StringRef getToken() const {
147 assert(Kind == Token && "Invalid access!");
148 return StringRef(Tok.Data, Tok.Length);
150 void setTokenValue(StringRef Value) {
151 assert(Kind == Token && "Invalid access!");
152 Tok.Data = Value.data();
153 Tok.Length = Value.size();
156 unsigned getReg() const {
157 assert(Kind == Register && "Invalid access!");
161 const MCExpr *getImm() const {
162 assert(Kind == Immediate && "Invalid access!");
166 const MCExpr *getMemDisp() const {
167 assert(Kind == Memory && "Invalid access!");
170 unsigned getMemSegReg() const {
171 assert(Kind == Memory && "Invalid access!");
174 unsigned getMemBaseReg() const {
175 assert(Kind == Memory && "Invalid access!");
178 unsigned getMemIndexReg() const {
179 assert(Kind == Memory && "Invalid access!");
182 unsigned getMemScale() const {
183 assert(Kind == Memory && "Invalid access!");
187 bool isToken() const {return Kind == Token; }
189 bool isImm() const { return Kind == Immediate; }
191 bool isImmSExti16i8() const {
195 // If this isn't a constant expr, just assume it fits and let relaxation
197 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
201 // Otherwise, check the value is in a range that makes sense for this
203 uint64_t Value = CE->getValue();
204 return (( Value <= 0x000000000000007FULL)||
205 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
206 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
208 bool isImmSExti32i8() const {
212 // If this isn't a constant expr, just assume it fits and let relaxation
214 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
218 // Otherwise, check the value is in a range that makes sense for this
220 uint64_t Value = CE->getValue();
221 return (( Value <= 0x000000000000007FULL)||
222 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
223 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
225 bool isImmSExti64i8() const {
229 // If this isn't a constant expr, just assume it fits and let relaxation
231 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
235 // Otherwise, check the value is in a range that makes sense for this
237 uint64_t Value = CE->getValue();
238 return (( Value <= 0x000000000000007FULL)||
239 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
241 bool isImmSExti64i32() const {
245 // If this isn't a constant expr, just assume it fits and let relaxation
247 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
251 // Otherwise, check the value is in a range that makes sense for this
253 uint64_t Value = CE->getValue();
254 return (( Value <= 0x000000007FFFFFFFULL)||
255 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
258 bool isMem() const { return Kind == Memory; }
260 bool isAbsMem() const {
261 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
262 !getMemIndexReg() && getMemScale() == 1;
265 bool isReg() const { return Kind == Register; }
267 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
268 // Add as immediates when possible.
269 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
270 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
272 Inst.addOperand(MCOperand::CreateExpr(Expr));
275 void addRegOperands(MCInst &Inst, unsigned N) const {
276 assert(N == 1 && "Invalid number of operands!");
277 Inst.addOperand(MCOperand::CreateReg(getReg()));
280 void addImmOperands(MCInst &Inst, unsigned N) const {
281 assert(N == 1 && "Invalid number of operands!");
282 addExpr(Inst, getImm());
285 void addMemOperands(MCInst &Inst, unsigned N) const {
286 assert((N == 5) && "Invalid number of operands!");
287 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
288 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
289 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
290 addExpr(Inst, getMemDisp());
291 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
294 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
295 assert((N == 1) && "Invalid number of operands!");
296 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
299 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
300 X86Operand *Res = new X86Operand(Token, Loc, Loc);
301 Res->Tok.Data = Str.data();
302 Res->Tok.Length = Str.size();
306 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
307 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
308 Res->Reg.RegNo = RegNo;
312 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
313 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
318 /// Create an absolute memory operand.
319 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
321 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
323 Res->Mem.Disp = Disp;
324 Res->Mem.BaseReg = 0;
325 Res->Mem.IndexReg = 0;
330 /// Create a generalized memory operand.
331 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
332 unsigned BaseReg, unsigned IndexReg,
333 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc) {
334 // We should never just have a displacement, that should be parsed as an
335 // absolute memory operand.
336 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
338 // The scale should always be one of {1,2,4,8}.
339 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
341 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
342 Res->Mem.SegReg = SegReg;
343 Res->Mem.Disp = Disp;
344 Res->Mem.BaseReg = BaseReg;
345 Res->Mem.IndexReg = IndexReg;
346 Res->Mem.Scale = Scale;
351 } // end anonymous namespace.
353 bool X86ATTAsmParser::isSrcOp(X86Operand &Op) {
354 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
356 return (Op.isMem() &&
357 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
358 isa<MCConstantExpr>(Op.Mem.Disp) &&
359 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
360 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
363 bool X86ATTAsmParser::isDstOp(X86Operand &Op) {
364 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
366 return Op.isMem() && Op.Mem.SegReg == X86::ES &&
367 isa<MCConstantExpr>(Op.Mem.Disp) &&
368 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
369 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
372 bool X86ATTAsmParser::ParseRegister(unsigned &RegNo,
373 SMLoc &StartLoc, SMLoc &EndLoc) {
375 const AsmToken &TokPercent = Parser.getTok();
376 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
377 StartLoc = TokPercent.getLoc();
378 Parser.Lex(); // Eat percent token.
380 const AsmToken &Tok = Parser.getTok();
381 if (Tok.isNot(AsmToken::Identifier))
382 return Error(Tok.getLoc(), "invalid register name");
384 // FIXME: Validate register for the current architecture; we have to do
385 // validation later, so maybe there is no need for this here.
386 RegNo = MatchRegisterName(Tok.getString());
388 // If the match failed, try the register name as lowercase.
390 RegNo = MatchRegisterName(LowercaseString(Tok.getString()));
392 // FIXME: This should be done using Requires<In32BitMode> and
393 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions
394 // can be also checked.
395 if (RegNo == X86::RIZ && !is64BitMode())
396 return Error(Tok.getLoc(), "riz register in 64-bit mode only");
398 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
399 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
401 EndLoc = Tok.getLoc();
402 Parser.Lex(); // Eat 'st'
404 // Check to see if we have '(4)' after %st.
405 if (getLexer().isNot(AsmToken::LParen))
410 const AsmToken &IntTok = Parser.getTok();
411 if (IntTok.isNot(AsmToken::Integer))
412 return Error(IntTok.getLoc(), "expected stack index");
413 switch (IntTok.getIntVal()) {
414 case 0: RegNo = X86::ST0; break;
415 case 1: RegNo = X86::ST1; break;
416 case 2: RegNo = X86::ST2; break;
417 case 3: RegNo = X86::ST3; break;
418 case 4: RegNo = X86::ST4; break;
419 case 5: RegNo = X86::ST5; break;
420 case 6: RegNo = X86::ST6; break;
421 case 7: RegNo = X86::ST7; break;
422 default: return Error(IntTok.getLoc(), "invalid stack index");
425 if (getParser().Lex().isNot(AsmToken::RParen))
426 return Error(Parser.getTok().getLoc(), "expected ')'");
428 EndLoc = Tok.getLoc();
429 Parser.Lex(); // Eat ')'
433 // If this is "db[0-7]", match it as an alias
435 if (RegNo == 0 && Tok.getString().size() == 3 &&
436 Tok.getString().startswith("db")) {
437 switch (Tok.getString()[2]) {
438 case '0': RegNo = X86::DR0; break;
439 case '1': RegNo = X86::DR1; break;
440 case '2': RegNo = X86::DR2; break;
441 case '3': RegNo = X86::DR3; break;
442 case '4': RegNo = X86::DR4; break;
443 case '5': RegNo = X86::DR5; break;
444 case '6': RegNo = X86::DR6; break;
445 case '7': RegNo = X86::DR7; break;
449 EndLoc = Tok.getLoc();
450 Parser.Lex(); // Eat it.
456 return Error(Tok.getLoc(), "invalid register name");
458 EndLoc = Tok.getLoc();
459 Parser.Lex(); // Eat identifier token.
463 X86Operand *X86ATTAsmParser::ParseOperand() {
464 switch (getLexer().getKind()) {
466 // Parse a memory operand with no segment register.
467 return ParseMemOperand(0, Parser.getTok().getLoc());
468 case AsmToken::Percent: {
469 // Read the register.
472 if (ParseRegister(RegNo, Start, End)) return 0;
473 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
474 Error(Start, "eiz and riz can only be used as index registers");
478 // If this is a segment register followed by a ':', then this is the start
479 // of a memory reference, otherwise this is a normal register reference.
480 if (getLexer().isNot(AsmToken::Colon))
481 return X86Operand::CreateReg(RegNo, Start, End);
484 getParser().Lex(); // Eat the colon.
485 return ParseMemOperand(RegNo, Start);
487 case AsmToken::Dollar: {
489 SMLoc Start = Parser.getTok().getLoc(), End;
492 if (getParser().ParseExpression(Val, End))
494 return X86Operand::CreateImm(Val, Start, End);
499 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
500 /// has already been parsed if present.
501 X86Operand *X86ATTAsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
503 // We have to disambiguate a parenthesized expression "(4+5)" from the start
504 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
505 // only way to do this without lookahead is to eat the '(' and see what is
507 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
508 if (getLexer().isNot(AsmToken::LParen)) {
510 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
512 // After parsing the base expression we could either have a parenthesized
513 // memory address or not. If not, return now. If so, eat the (.
514 if (getLexer().isNot(AsmToken::LParen)) {
515 // Unless we have a segment register, treat this as an immediate.
517 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
518 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
524 // Okay, we have a '('. We don't know if this is an expression or not, but
525 // so we have to eat the ( to see beyond it.
526 SMLoc LParenLoc = Parser.getTok().getLoc();
527 Parser.Lex(); // Eat the '('.
529 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
530 // Nothing to do here, fall into the code below with the '(' part of the
531 // memory operand consumed.
535 // It must be an parenthesized expression, parse it now.
536 if (getParser().ParseParenExpression(Disp, ExprEnd))
539 // After parsing the base expression we could either have a parenthesized
540 // memory address or not. If not, return now. If so, eat the (.
541 if (getLexer().isNot(AsmToken::LParen)) {
542 // Unless we have a segment register, treat this as an immediate.
544 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
545 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
553 // If we reached here, then we just ate the ( of the memory operand. Process
554 // the rest of the memory operand.
555 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
557 if (getLexer().is(AsmToken::Percent)) {
559 if (ParseRegister(BaseReg, L, L)) return 0;
560 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
561 Error(L, "eiz and riz can only be used as index registers");
566 if (getLexer().is(AsmToken::Comma)) {
567 Parser.Lex(); // Eat the comma.
569 // Following the comma we should have either an index register, or a scale
570 // value. We don't support the later form, but we want to parse it
573 // Not that even though it would be completely consistent to support syntax
574 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
575 if (getLexer().is(AsmToken::Percent)) {
577 if (ParseRegister(IndexReg, L, L)) return 0;
579 if (getLexer().isNot(AsmToken::RParen)) {
580 // Parse the scale amount:
581 // ::= ',' [scale-expression]
582 if (getLexer().isNot(AsmToken::Comma)) {
583 Error(Parser.getTok().getLoc(),
584 "expected comma in scale expression");
587 Parser.Lex(); // Eat the comma.
589 if (getLexer().isNot(AsmToken::RParen)) {
590 SMLoc Loc = Parser.getTok().getLoc();
593 if (getParser().ParseAbsoluteExpression(ScaleVal))
596 // Validate the scale amount.
597 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
598 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
601 Scale = (unsigned)ScaleVal;
604 } else if (getLexer().isNot(AsmToken::RParen)) {
605 // A scale amount without an index is ignored.
607 SMLoc Loc = Parser.getTok().getLoc();
610 if (getParser().ParseAbsoluteExpression(Value))
614 Warning(Loc, "scale factor without index register is ignored");
619 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
620 if (getLexer().isNot(AsmToken::RParen)) {
621 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
624 SMLoc MemEnd = Parser.getTok().getLoc();
625 Parser.Lex(); // Eat the ')'.
627 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
631 bool X86ATTAsmParser::
632 ParseInstruction(StringRef Name, SMLoc NameLoc,
633 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
634 StringRef PatchedName = Name;
636 // FIXME: Hack to recognize setneb as setne.
637 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
638 PatchedName != "setb" && PatchedName != "setnb")
639 PatchedName = PatchedName.substr(0, Name.size()-1);
641 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
642 const MCExpr *ExtraImmOp = 0;
643 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
644 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
645 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
646 bool IsVCMP = PatchedName.startswith("vcmp");
647 unsigned SSECCIdx = IsVCMP ? 4 : 3;
648 unsigned SSEComparisonCode = StringSwitch<unsigned>(
649 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
662 .Case("neq_oq", 0x0C)
669 .Case("unord_s", 0x13)
670 .Case("neq_us", 0x14)
671 .Case("nlt_uq", 0x15)
672 .Case("nle_uq", 0x16)
675 .Case("nge_uq", 0x19)
676 .Case("ngt_uq", 0x1A)
677 .Case("false_os", 0x1B)
678 .Case("neq_os", 0x1C)
681 .Case("true_us", 0x1F)
683 if (SSEComparisonCode != ~0U) {
684 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
685 getParser().getContext());
686 if (PatchedName.endswith("ss")) {
687 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
688 } else if (PatchedName.endswith("sd")) {
689 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
690 } else if (PatchedName.endswith("ps")) {
691 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
693 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
694 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
699 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
702 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
705 // Determine whether this is an instruction prefix.
707 Name == "lock" || Name == "rep" ||
708 Name == "repe" || Name == "repz" ||
709 Name == "repne" || Name == "repnz" ||
710 Name == "rex64" || Name == "data16";
713 // This does the actual operand parsing. Don't parse any more if we have a
714 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
715 // just want to parse the "lock" as the first instruction and the "incl" as
717 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
719 // Parse '*' modifier.
720 if (getLexer().is(AsmToken::Star)) {
721 SMLoc Loc = Parser.getTok().getLoc();
722 Operands.push_back(X86Operand::CreateToken("*", Loc));
723 Parser.Lex(); // Eat the star.
726 // Read the first operand.
727 if (X86Operand *Op = ParseOperand())
728 Operands.push_back(Op);
730 Parser.EatToEndOfStatement();
734 while (getLexer().is(AsmToken::Comma)) {
735 Parser.Lex(); // Eat the comma.
737 // Parse and remember the operand.
738 if (X86Operand *Op = ParseOperand())
739 Operands.push_back(Op);
741 Parser.EatToEndOfStatement();
746 if (getLexer().isNot(AsmToken::EndOfStatement)) {
747 SMLoc Loc = getLexer().getLoc();
748 Parser.EatToEndOfStatement();
749 return Error(Loc, "unexpected token in argument list");
753 if (getLexer().is(AsmToken::EndOfStatement))
754 Parser.Lex(); // Consume the EndOfStatement
755 else if (isPrefix && getLexer().is(AsmToken::Slash))
756 Parser.Lex(); // Consume the prefix separator Slash
758 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
759 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
760 // documented form in various unofficial manuals, so a lot of code uses it.
761 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
762 Operands.size() == 3) {
763 X86Operand &Op = *(X86Operand*)Operands.back();
764 if (Op.isMem() && Op.Mem.SegReg == 0 &&
765 isa<MCConstantExpr>(Op.Mem.Disp) &&
766 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
767 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
768 SMLoc Loc = Op.getEndLoc();
769 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
773 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
774 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
775 Operands.size() == 3) {
776 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
777 if (Op.isMem() && Op.Mem.SegReg == 0 &&
778 isa<MCConstantExpr>(Op.Mem.Disp) &&
779 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
780 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
781 SMLoc Loc = Op.getEndLoc();
782 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
786 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
787 if (Name.startswith("ins") && Operands.size() == 3 &&
788 (Name == "insb" || Name == "insw" || Name == "insl")) {
789 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
790 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
791 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
799 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
800 if (Name.startswith("outs") && Operands.size() == 3 &&
801 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
802 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
803 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
804 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
812 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
813 if (Name.startswith("movs") && Operands.size() == 3 &&
814 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
815 (is64BitMode() && Name == "movsq"))) {
816 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
817 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
818 if (isSrcOp(Op) && isDstOp(Op2)) {
825 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
826 if (Name.startswith("lods") && Operands.size() == 3 &&
827 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
828 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
829 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
830 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
831 if (isSrcOp(*Op1) && Op2->isReg()) {
833 unsigned reg = Op2->getReg();
834 bool isLods = Name == "lods";
835 if (reg == X86::AL && (isLods || Name == "lodsb"))
837 else if (reg == X86::AX && (isLods || Name == "lodsw"))
839 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
841 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
851 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
855 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
856 if (Name.startswith("stos") && Operands.size() == 3 &&
857 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
858 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
859 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
860 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
861 if (isDstOp(*Op2) && Op1->isReg()) {
863 unsigned reg = Op1->getReg();
864 bool isStos = Name == "stos";
865 if (reg == X86::AL && (isStos || Name == "stosb"))
867 else if (reg == X86::AX && (isStos || Name == "stosw"))
869 else if (reg == X86::EAX && (isStos || Name == "stosl"))
871 else if (reg == X86::RAX && (isStos || Name == "stosq"))
881 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
886 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
888 if ((Name.startswith("shr") || Name.startswith("sar") ||
889 Name.startswith("shl") || Name.startswith("sal") ||
890 Name.startswith("rcl") || Name.startswith("rcr") ||
891 Name.startswith("rol") || Name.startswith("ror")) &&
892 Operands.size() == 3) {
893 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
894 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
895 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
897 Operands.erase(Operands.begin() + 1);
901 // Transforms "int $3" into "int3" as a size optimization. We can't write an
902 // instalias with an immediate operand yet.
903 if (Name == "int" && Operands.size() == 2) {
904 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
905 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
906 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
908 Operands.erase(Operands.begin() + 1);
909 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
916 bool X86ATTAsmParser::
917 MatchAndEmitInstruction(SMLoc IDLoc,
918 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
920 assert(!Operands.empty() && "Unexpect empty operand list!");
921 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
922 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
924 // First, handle aliases that expand to multiple instructions.
925 // FIXME: This should be replaced with a real .td file alias mechanism.
926 // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
928 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
929 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
930 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
931 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
933 Inst.setOpcode(X86::WAIT);
934 Out.EmitInstruction(Inst);
937 StringSwitch<const char*>(Op->getToken())
938 .Case("finit", "fninit")
939 .Case("fsave", "fnsave")
940 .Case("fstcw", "fnstcw")
941 .Case("fstcww", "fnstcw")
942 .Case("fstenv", "fnstenv")
943 .Case("fstsw", "fnstsw")
944 .Case("fstsww", "fnstsw")
945 .Case("fclex", "fnclex")
947 assert(Repl && "Unknown wait-prefixed instruction");
949 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
952 bool WasOriginallyInvalidOperand = false;
953 unsigned OrigErrorInfo;
956 // First, try a direct match.
957 switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo)) {
959 Out.EmitInstruction(Inst);
961 case Match_MissingFeature:
962 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
964 case Match_ConversionFail:
965 return Error(IDLoc, "unable to convert operands to instruction");
966 case Match_InvalidOperand:
967 WasOriginallyInvalidOperand = true;
969 case Match_MnemonicFail:
973 // FIXME: Ideally, we would only attempt suffix matches for things which are
974 // valid prefixes, and we could just infer the right unambiguous
975 // type. However, that requires substantially more matcher support than the
978 // Change the operand to point to a temporary token.
979 StringRef Base = Op->getToken();
983 Op->setTokenValue(Tmp.str());
985 // If this instruction starts with an 'f', then it is a floating point stack
986 // instruction. These come in up to three forms for 32-bit, 64-bit, and
987 // 80-bit floating point, which use the suffixes s,l,t respectively.
989 // Otherwise, we assume that this may be an integer instruction, which comes
990 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
991 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
993 // Check for the various suffix matches.
994 Tmp[Base.size()] = Suffixes[0];
995 unsigned ErrorInfoIgnore;
996 MatchResultTy Match1, Match2, Match3, Match4;
998 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
999 Tmp[Base.size()] = Suffixes[1];
1000 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1001 Tmp[Base.size()] = Suffixes[2];
1002 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1003 Tmp[Base.size()] = Suffixes[3];
1004 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1006 // Restore the old token.
1007 Op->setTokenValue(Base);
1009 // If exactly one matched, then we treat that as a successful match (and the
1010 // instruction will already have been filled in correctly, since the failing
1011 // matches won't have modified it).
1012 unsigned NumSuccessfulMatches =
1013 (Match1 == Match_Success) + (Match2 == Match_Success) +
1014 (Match3 == Match_Success) + (Match4 == Match_Success);
1015 if (NumSuccessfulMatches == 1) {
1016 Out.EmitInstruction(Inst);
1020 // Otherwise, the match failed, try to produce a decent error message.
1022 // If we had multiple suffix matches, then identify this as an ambiguous
1024 if (NumSuccessfulMatches > 1) {
1026 unsigned NumMatches = 0;
1027 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1028 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1029 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1030 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1032 SmallString<126> Msg;
1033 raw_svector_ostream OS(Msg);
1034 OS << "ambiguous instructions require an explicit suffix (could be ";
1035 for (unsigned i = 0; i != NumMatches; ++i) {
1038 if (i + 1 == NumMatches)
1040 OS << "'" << Base << MatchChars[i] << "'";
1043 Error(IDLoc, OS.str());
1047 // Okay, we know that none of the variants matched successfully.
1049 // If all of the instructions reported an invalid mnemonic, then the original
1050 // mnemonic was invalid.
1051 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1052 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1053 if (!WasOriginallyInvalidOperand) {
1054 Error(IDLoc, "invalid instruction mnemonic '" + Base + "'");
1058 // Recover location info for the operand if we know which was the problem.
1059 SMLoc ErrorLoc = IDLoc;
1060 if (OrigErrorInfo != ~0U) {
1061 if (OrigErrorInfo >= Operands.size())
1062 return Error(IDLoc, "too few operands for instruction");
1064 ErrorLoc = ((X86Operand*)Operands[OrigErrorInfo])->getStartLoc();
1065 if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
1068 return Error(ErrorLoc, "invalid operand for instruction");
1071 // If one instruction matched with a missing feature, report this as a
1073 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1074 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1075 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1079 // If one instruction matched with an invalid operand, report this as an
1081 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1082 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1083 Error(IDLoc, "invalid operand for instruction");
1087 // If all of these were an outright failure, report it in a useless way.
1088 // FIXME: We should give nicer diagnostics about the exact failure.
1089 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
1094 bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
1095 StringRef IDVal = DirectiveID.getIdentifier();
1096 if (IDVal == ".word")
1097 return ParseDirectiveWord(2, DirectiveID.getLoc());
1101 /// ParseDirectiveWord
1102 /// ::= .word [ expression (, expression)* ]
1103 bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1104 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1106 const MCExpr *Value;
1107 if (getParser().ParseExpression(Value))
1110 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1112 if (getLexer().is(AsmToken::EndOfStatement))
1115 // FIXME: Improve diagnostic.
1116 if (getLexer().isNot(AsmToken::Comma))
1117 return Error(L, "unexpected token in directive");
1129 extern "C" void LLVMInitializeX86AsmLexer();
1131 // Force static initialization.
1132 extern "C" void LLVMInitializeX86AsmParser() {
1133 RegisterAsmParser<X86ATTAsmParser> X(TheX86_32Target);
1134 RegisterAsmParser<X86ATTAsmParser> Y(TheX86_64Target);
1135 LLVMInitializeX86AsmLexer();
1138 #define GET_REGISTER_MATCHER
1139 #define GET_MATCHER_IMPLEMENTATION
1140 #include "X86GenAsmMatcher.inc"