1 //===-- X86AsmParser.cpp - Parse X86 assembly to MCInst instructions ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MCTargetDesc/X86BaseInfo.h"
11 #include "llvm/MC/MCTargetAsmParser.h"
12 #include "llvm/MC/MCStreamer.h"
13 #include "llvm/MC/MCExpr.h"
14 #include "llvm/MC/MCInst.h"
15 #include "llvm/MC/MCRegisterInfo.h"
16 #include "llvm/MC/MCSubtargetInfo.h"
17 #include "llvm/MC/MCParser/MCAsmLexer.h"
18 #include "llvm/MC/MCParser/MCAsmParser.h"
19 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/TargetRegistry.h"
27 #include "llvm/Support/raw_ostream.h"
34 class X86AsmParser : public MCTargetAsmParser {
39 MCAsmParser &getParser() const { return Parser; }
41 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
43 bool Error(SMLoc L, const Twine &Msg,
44 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) {
45 return Parser.Error(L, Msg, Ranges);
48 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
53 X86Operand *ParseOperand();
54 X86Operand *ParseATTOperand();
55 X86Operand *ParseIntelOperand();
56 X86Operand *ParseIntelMemOperand();
57 X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
58 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
60 bool ParseDirectiveWord(unsigned Size, SMLoc L);
61 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
63 bool processInstruction(MCInst &Inst,
64 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
66 bool MatchAndEmitInstruction(SMLoc IDLoc,
67 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
70 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
71 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
72 bool isSrcOp(X86Operand &Op);
74 /// isDstOp - Returns true if operand is either %es:(%rdi) in 64bit mode
75 /// or %es:(%edi) in 32bit mode.
76 bool isDstOp(X86Operand &Op);
78 bool is64BitMode() const {
79 // FIXME: Can tablegen auto-generate this?
80 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
83 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
84 setAvailableFeatures(FB);
87 /// @name Auto-generated Matcher Functions
90 #define GET_ASSEMBLER_HEADER
91 #include "X86GenAsmMatcher.inc"
96 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
97 : MCTargetAsmParser(), STI(sti), Parser(parser) {
99 // Initialize the set of available features.
100 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
102 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
104 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
105 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
107 virtual bool ParseDirective(AsmToken DirectiveID);
109 } // end anonymous namespace
111 /// @name Auto-generated Match Functions
114 static unsigned MatchRegisterName(StringRef Name);
118 static bool isImmSExti16i8Value(uint64_t Value) {
119 return (( Value <= 0x000000000000007FULL)||
120 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
121 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
124 static bool isImmSExti32i8Value(uint64_t Value) {
125 return (( Value <= 0x000000000000007FULL)||
126 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
127 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
130 static bool isImmZExtu32u8Value(uint64_t Value) {
131 return (Value <= 0x00000000000000FFULL);
134 static bool isImmSExti64i8Value(uint64_t Value) {
135 return (( Value <= 0x000000000000007FULL)||
136 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
139 static bool isImmSExti64i32Value(uint64_t Value) {
140 return (( Value <= 0x000000007FFFFFFFULL)||
141 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
145 /// X86Operand - Instances of this class represent a parsed X86 machine
147 struct X86Operand : public MCParsedAsmOperand {
155 SMLoc StartLoc, EndLoc;
181 X86Operand(KindTy K, SMLoc Start, SMLoc End)
182 : Kind(K), StartLoc(Start), EndLoc(End) {}
184 /// getStartLoc - Get the location of the first token of this operand.
185 SMLoc getStartLoc() const { return StartLoc; }
186 /// getEndLoc - Get the location of the last token of this operand.
187 SMLoc getEndLoc() const { return EndLoc; }
189 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
191 virtual void print(raw_ostream &OS) const {}
193 StringRef getToken() const {
194 assert(Kind == Token && "Invalid access!");
195 return StringRef(Tok.Data, Tok.Length);
197 void setTokenValue(StringRef Value) {
198 assert(Kind == Token && "Invalid access!");
199 Tok.Data = Value.data();
200 Tok.Length = Value.size();
203 unsigned getReg() const {
204 assert(Kind == Register && "Invalid access!");
208 const MCExpr *getImm() const {
209 assert(Kind == Immediate && "Invalid access!");
213 const MCExpr *getMemDisp() const {
214 assert(Kind == Memory && "Invalid access!");
217 unsigned getMemSegReg() const {
218 assert(Kind == Memory && "Invalid access!");
221 unsigned getMemBaseReg() const {
222 assert(Kind == Memory && "Invalid access!");
225 unsigned getMemIndexReg() const {
226 assert(Kind == Memory && "Invalid access!");
229 unsigned getMemScale() const {
230 assert(Kind == Memory && "Invalid access!");
234 bool isToken() const {return Kind == Token; }
236 bool isImm() const { return Kind == Immediate; }
238 bool isImmSExti16i8() const {
242 // If this isn't a constant expr, just assume it fits and let relaxation
244 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
248 // Otherwise, check the value is in a range that makes sense for this
250 return isImmSExti16i8Value(CE->getValue());
252 bool isImmSExti32i8() const {
256 // If this isn't a constant expr, just assume it fits and let relaxation
258 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
262 // Otherwise, check the value is in a range that makes sense for this
264 return isImmSExti32i8Value(CE->getValue());
266 bool isImmZExtu32u8() const {
270 // If this isn't a constant expr, just assume it fits and let relaxation
272 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
276 // Otherwise, check the value is in a range that makes sense for this
278 return isImmZExtu32u8Value(CE->getValue());
280 bool isImmSExti64i8() const {
284 // If this isn't a constant expr, just assume it fits and let relaxation
286 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
290 // Otherwise, check the value is in a range that makes sense for this
292 return isImmSExti64i8Value(CE->getValue());
294 bool isImmSExti64i32() const {
298 // If this isn't a constant expr, just assume it fits and let relaxation
300 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
304 // Otherwise, check the value is in a range that makes sense for this
306 return isImmSExti64i32Value(CE->getValue());
309 bool isMem() const { return Kind == Memory; }
310 bool isMem8() const {
311 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
313 bool isMem16() const {
314 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
316 bool isMem32() const {
317 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
319 bool isMem64() const {
320 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
322 bool isMem80() const {
323 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
325 bool isMem128() const {
326 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
328 bool isMem256() const {
329 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
332 bool isAbsMem() const {
333 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
334 !getMemIndexReg() && getMemScale() == 1;
337 bool isReg() const { return Kind == Register; }
339 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
340 // Add as immediates when possible.
341 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
342 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
344 Inst.addOperand(MCOperand::CreateExpr(Expr));
347 void addRegOperands(MCInst &Inst, unsigned N) const {
348 assert(N == 1 && "Invalid number of operands!");
349 Inst.addOperand(MCOperand::CreateReg(getReg()));
352 void addImmOperands(MCInst &Inst, unsigned N) const {
353 assert(N == 1 && "Invalid number of operands!");
354 addExpr(Inst, getImm());
357 void addMem8Operands(MCInst &Inst, unsigned N) const {
358 addMemOperands(Inst, N);
360 void addMem16Operands(MCInst &Inst, unsigned N) const {
361 addMemOperands(Inst, N);
363 void addMem32Operands(MCInst &Inst, unsigned N) const {
364 addMemOperands(Inst, N);
366 void addMem64Operands(MCInst &Inst, unsigned N) const {
367 addMemOperands(Inst, N);
369 void addMem80Operands(MCInst &Inst, unsigned N) const {
370 addMemOperands(Inst, N);
372 void addMem128Operands(MCInst &Inst, unsigned N) const {
373 addMemOperands(Inst, N);
375 void addMem256Operands(MCInst &Inst, unsigned N) const {
376 addMemOperands(Inst, N);
379 void addMemOperands(MCInst &Inst, unsigned N) const {
380 assert((N == 5) && "Invalid number of operands!");
381 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
382 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
383 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
384 addExpr(Inst, getMemDisp());
385 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
388 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
389 assert((N == 1) && "Invalid number of operands!");
390 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
393 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
394 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
395 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
396 Res->Tok.Data = Str.data();
397 Res->Tok.Length = Str.size();
401 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
402 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
403 Res->Reg.RegNo = RegNo;
407 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
408 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
413 /// Create an absolute memory operand.
414 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
415 SMLoc EndLoc, unsigned Size = 0) {
416 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
418 Res->Mem.Disp = Disp;
419 Res->Mem.BaseReg = 0;
420 Res->Mem.IndexReg = 0;
422 Res->Mem.Size = Size;
426 /// Create a generalized memory operand.
427 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
428 unsigned BaseReg, unsigned IndexReg,
429 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
431 // We should never just have a displacement, that should be parsed as an
432 // absolute memory operand.
433 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
435 // The scale should always be one of {1,2,4,8}.
436 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
438 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
439 Res->Mem.SegReg = SegReg;
440 Res->Mem.Disp = Disp;
441 Res->Mem.BaseReg = BaseReg;
442 Res->Mem.IndexReg = IndexReg;
443 Res->Mem.Scale = Scale;
444 Res->Mem.Size = Size;
449 } // end anonymous namespace.
451 bool X86AsmParser::isSrcOp(X86Operand &Op) {
452 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
454 return (Op.isMem() &&
455 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
456 isa<MCConstantExpr>(Op.Mem.Disp) &&
457 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
458 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
461 bool X86AsmParser::isDstOp(X86Operand &Op) {
462 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
464 return Op.isMem() && Op.Mem.SegReg == X86::ES &&
465 isa<MCConstantExpr>(Op.Mem.Disp) &&
466 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
467 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
470 bool X86AsmParser::ParseRegister(unsigned &RegNo,
471 SMLoc &StartLoc, SMLoc &EndLoc) {
473 bool IntelSyntax = getParser().getAssemblerDialect();
475 const AsmToken &TokPercent = Parser.getTok();
476 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
477 StartLoc = TokPercent.getLoc();
478 Parser.Lex(); // Eat percent token.
481 const AsmToken &Tok = Parser.getTok();
482 if (Tok.isNot(AsmToken::Identifier)) {
483 if (IntelSyntax) return true;
484 return Error(StartLoc, "invalid register name",
485 SMRange(StartLoc, Tok.getEndLoc()));
488 RegNo = MatchRegisterName(Tok.getString());
490 // If the match failed, try the register name as lowercase.
492 RegNo = MatchRegisterName(Tok.getString().lower());
494 if (!is64BitMode()) {
495 // FIXME: This should be done using Requires<In32BitMode> and
496 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
498 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
500 if (RegNo == X86::RIZ ||
501 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
502 X86II::isX86_64NonExtLowByteReg(RegNo) ||
503 X86II::isX86_64ExtendedReg(RegNo))
504 return Error(StartLoc, "register %"
505 + Tok.getString() + " is only available in 64-bit mode",
506 SMRange(StartLoc, Tok.getEndLoc()));
509 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
510 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
512 EndLoc = Tok.getLoc();
513 Parser.Lex(); // Eat 'st'
515 // Check to see if we have '(4)' after %st.
516 if (getLexer().isNot(AsmToken::LParen))
521 const AsmToken &IntTok = Parser.getTok();
522 if (IntTok.isNot(AsmToken::Integer))
523 return Error(IntTok.getLoc(), "expected stack index");
524 switch (IntTok.getIntVal()) {
525 case 0: RegNo = X86::ST0; break;
526 case 1: RegNo = X86::ST1; break;
527 case 2: RegNo = X86::ST2; break;
528 case 3: RegNo = X86::ST3; break;
529 case 4: RegNo = X86::ST4; break;
530 case 5: RegNo = X86::ST5; break;
531 case 6: RegNo = X86::ST6; break;
532 case 7: RegNo = X86::ST7; break;
533 default: return Error(IntTok.getLoc(), "invalid stack index");
536 if (getParser().Lex().isNot(AsmToken::RParen))
537 return Error(Parser.getTok().getLoc(), "expected ')'");
539 EndLoc = Tok.getLoc();
540 Parser.Lex(); // Eat ')'
544 // If this is "db[0-7]", match it as an alias
546 if (RegNo == 0 && Tok.getString().size() == 3 &&
547 Tok.getString().startswith("db")) {
548 switch (Tok.getString()[2]) {
549 case '0': RegNo = X86::DR0; break;
550 case '1': RegNo = X86::DR1; break;
551 case '2': RegNo = X86::DR2; break;
552 case '3': RegNo = X86::DR3; break;
553 case '4': RegNo = X86::DR4; break;
554 case '5': RegNo = X86::DR5; break;
555 case '6': RegNo = X86::DR6; break;
556 case '7': RegNo = X86::DR7; break;
560 EndLoc = Tok.getLoc();
561 Parser.Lex(); // Eat it.
567 if (IntelSyntax) return true;
568 return Error(StartLoc, "invalid register name",
569 SMRange(StartLoc, Tok.getEndLoc()));
572 EndLoc = Tok.getEndLoc();
573 Parser.Lex(); // Eat identifier token.
577 X86Operand *X86AsmParser::ParseOperand() {
578 if (getParser().getAssemblerDialect())
579 return ParseIntelOperand();
580 return ParseATTOperand();
583 /// getIntelMemOperandSize - Return intel memory operand size.
584 static unsigned getIntelMemOperandSize(StringRef OpStr) {
586 if (OpStr == "BYTE") Size = 8;
587 if (OpStr == "WORD") Size = 16;
588 if (OpStr == "DWORD") Size = 32;
589 if (OpStr == "QWORD") Size = 64;
590 if (OpStr == "XWORD") Size = 80;
591 if (OpStr == "XMMWORD") Size = 128;
592 if (OpStr == "YMMWORD") Size = 256;
596 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
598 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
599 SMLoc Start = Parser.getTok().getLoc(), End;
601 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
602 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
605 if (getLexer().isNot(AsmToken::LBrac))
606 return ErrorOperand(Start, "Expected '[' token!");
609 if (getLexer().is(AsmToken::Identifier)) {
611 if (ParseRegister(BaseReg, Start, End)) {
612 // Handle '[' 'symbol' ']'
613 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
614 if (getParser().ParseExpression(Disp, End)) return 0;
615 if (getLexer().isNot(AsmToken::RBrac))
616 return ErrorOperand(Start, "Expected ']' token!");
618 return X86Operand::CreateMem(Disp, Start, End, Size);
620 } else if (getLexer().is(AsmToken::Integer)) {
621 int64_t Val = Parser.getTok().getIntVal();
623 SMLoc Loc = Parser.getTok().getLoc();
624 if (getLexer().is(AsmToken::RBrac)) {
625 // Handle '[' number ']'
627 return X86Operand::CreateMem(MCConstantExpr::Create(Val, getContext()),
629 } else if (getLexer().is(AsmToken::Star)) {
630 // Handle '[' Scale*IndexReg ']'
632 SMLoc IdxRegLoc = Parser.getTok().getLoc();
633 if (ParseRegister(IndexReg, IdxRegLoc, End))
634 return ErrorOperand(IdxRegLoc, "Expected register");
637 return ErrorOperand(Loc, "Unepxeted token");
640 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
641 bool isPlus = getLexer().is(AsmToken::Plus);
643 SMLoc PlusLoc = Parser.getTok().getLoc();
644 if (getLexer().is(AsmToken::Integer)) {
645 int64_t Val = Parser.getTok().getIntVal();
647 if (getLexer().is(AsmToken::Star)) {
649 SMLoc IdxRegLoc = Parser.getTok().getLoc();
650 if (ParseRegister(IndexReg, IdxRegLoc, End))
651 return ErrorOperand(IdxRegLoc, "Expected register");
653 } else if (getLexer().is(AsmToken::RBrac)) {
654 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
655 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
657 return ErrorOperand(PlusLoc, "unexpected token after +");
658 } else if (getLexer().is(AsmToken::Identifier)) {
659 // This could be an index register or a displacement expression.
660 End = Parser.getTok().getLoc();
662 ParseRegister(IndexReg, Start, End);
663 else if (getParser().ParseExpression(Disp, End)) return 0;
667 if (getLexer().isNot(AsmToken::RBrac))
668 if (getParser().ParseExpression(Disp, End)) return 0;
670 End = Parser.getTok().getLoc();
671 if (getLexer().isNot(AsmToken::RBrac))
672 return ErrorOperand(End, "expected ']' token!");
674 End = Parser.getTok().getLoc();
677 if (!BaseReg && !IndexReg)
678 return X86Operand::CreateMem(Disp, Start, End, Size);
680 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
684 /// ParseIntelMemOperand - Parse intel style memory operand.
685 X86Operand *X86AsmParser::ParseIntelMemOperand() {
686 const AsmToken &Tok = Parser.getTok();
687 SMLoc Start = Parser.getTok().getLoc(), End;
690 unsigned Size = getIntelMemOperandSize(Tok.getString());
693 assert (Tok.getString() == "PTR" && "Unexpected token!");
697 if (getLexer().is(AsmToken::LBrac))
698 return ParseIntelBracExpression(SegReg, Size);
700 if (!ParseRegister(SegReg, Start, End)) {
701 // Handel SegReg : [ ... ]
702 if (getLexer().isNot(AsmToken::Colon))
703 return ErrorOperand(Start, "Expected ':' token!");
704 Parser.Lex(); // Eat :
705 if (getLexer().isNot(AsmToken::LBrac))
706 return ErrorOperand(Start, "Expected '[' token!");
707 return ParseIntelBracExpression(SegReg, Size);
710 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
711 if (getParser().ParseExpression(Disp, End)) return 0;
712 return X86Operand::CreateMem(Disp, Start, End, Size);
715 X86Operand *X86AsmParser::ParseIntelOperand() {
716 SMLoc Start = Parser.getTok().getLoc(), End;
719 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
720 getLexer().is(AsmToken::Minus)) {
722 if (!getParser().ParseExpression(Val, End)) {
723 End = Parser.getTok().getLoc();
724 return X86Operand::CreateImm(Val, Start, End);
730 if (!ParseRegister(RegNo, Start, End)) {
731 End = Parser.getTok().getLoc();
732 return X86Operand::CreateReg(RegNo, Start, End);
736 return ParseIntelMemOperand();
739 X86Operand *X86AsmParser::ParseATTOperand() {
740 switch (getLexer().getKind()) {
742 // Parse a memory operand with no segment register.
743 return ParseMemOperand(0, Parser.getTok().getLoc());
744 case AsmToken::Percent: {
745 // Read the register.
748 if (ParseRegister(RegNo, Start, End)) return 0;
749 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
750 Error(Start, "%eiz and %riz can only be used as index registers",
751 SMRange(Start, End));
755 // If this is a segment register followed by a ':', then this is the start
756 // of a memory reference, otherwise this is a normal register reference.
757 if (getLexer().isNot(AsmToken::Colon))
758 return X86Operand::CreateReg(RegNo, Start, End);
761 getParser().Lex(); // Eat the colon.
762 return ParseMemOperand(RegNo, Start);
764 case AsmToken::Dollar: {
766 SMLoc Start = Parser.getTok().getLoc(), End;
769 if (getParser().ParseExpression(Val, End))
771 return X86Operand::CreateImm(Val, Start, End);
776 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
777 /// has already been parsed if present.
778 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
780 // We have to disambiguate a parenthesized expression "(4+5)" from the start
781 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
782 // only way to do this without lookahead is to eat the '(' and see what is
784 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
785 if (getLexer().isNot(AsmToken::LParen)) {
787 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
789 // After parsing the base expression we could either have a parenthesized
790 // memory address or not. If not, return now. If so, eat the (.
791 if (getLexer().isNot(AsmToken::LParen)) {
792 // Unless we have a segment register, treat this as an immediate.
794 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
795 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
801 // Okay, we have a '('. We don't know if this is an expression or not, but
802 // so we have to eat the ( to see beyond it.
803 SMLoc LParenLoc = Parser.getTok().getLoc();
804 Parser.Lex(); // Eat the '('.
806 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
807 // Nothing to do here, fall into the code below with the '(' part of the
808 // memory operand consumed.
812 // It must be an parenthesized expression, parse it now.
813 if (getParser().ParseParenExpression(Disp, ExprEnd))
816 // After parsing the base expression we could either have a parenthesized
817 // memory address or not. If not, return now. If so, eat the (.
818 if (getLexer().isNot(AsmToken::LParen)) {
819 // Unless we have a segment register, treat this as an immediate.
821 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
822 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
830 // If we reached here, then we just ate the ( of the memory operand. Process
831 // the rest of the memory operand.
832 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
834 if (getLexer().is(AsmToken::Percent)) {
835 SMLoc StartLoc, EndLoc;
836 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
837 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
838 Error(StartLoc, "eiz and riz can only be used as index registers",
839 SMRange(StartLoc, EndLoc));
844 if (getLexer().is(AsmToken::Comma)) {
845 Parser.Lex(); // Eat the comma.
847 // Following the comma we should have either an index register, or a scale
848 // value. We don't support the later form, but we want to parse it
851 // Not that even though it would be completely consistent to support syntax
852 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
853 if (getLexer().is(AsmToken::Percent)) {
855 if (ParseRegister(IndexReg, L, L)) return 0;
857 if (getLexer().isNot(AsmToken::RParen)) {
858 // Parse the scale amount:
859 // ::= ',' [scale-expression]
860 if (getLexer().isNot(AsmToken::Comma)) {
861 Error(Parser.getTok().getLoc(),
862 "expected comma in scale expression");
865 Parser.Lex(); // Eat the comma.
867 if (getLexer().isNot(AsmToken::RParen)) {
868 SMLoc Loc = Parser.getTok().getLoc();
871 if (getParser().ParseAbsoluteExpression(ScaleVal))
874 // Validate the scale amount.
875 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
876 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
879 Scale = (unsigned)ScaleVal;
882 } else if (getLexer().isNot(AsmToken::RParen)) {
883 // A scale amount without an index is ignored.
885 SMLoc Loc = Parser.getTok().getLoc();
888 if (getParser().ParseAbsoluteExpression(Value))
892 Warning(Loc, "scale factor without index register is ignored");
897 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
898 if (getLexer().isNot(AsmToken::RParen)) {
899 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
902 SMLoc MemEnd = Parser.getTok().getLoc();
903 Parser.Lex(); // Eat the ')'.
905 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
910 ParseInstruction(StringRef Name, SMLoc NameLoc,
911 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
912 StringRef PatchedName = Name;
914 // FIXME: Hack to recognize setneb as setne.
915 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
916 PatchedName != "setb" && PatchedName != "setnb")
917 PatchedName = PatchedName.substr(0, Name.size()-1);
919 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
920 const MCExpr *ExtraImmOp = 0;
921 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
922 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
923 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
924 bool IsVCMP = PatchedName.startswith("vcmp");
925 unsigned SSECCIdx = IsVCMP ? 4 : 3;
926 unsigned SSEComparisonCode = StringSwitch<unsigned>(
927 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
940 .Case("neq_oq", 0x0C)
947 .Case("unord_s", 0x13)
948 .Case("neq_us", 0x14)
949 .Case("nlt_uq", 0x15)
950 .Case("nle_uq", 0x16)
953 .Case("nge_uq", 0x19)
954 .Case("ngt_uq", 0x1A)
955 .Case("false_os", 0x1B)
956 .Case("neq_os", 0x1C)
959 .Case("true_us", 0x1F)
961 if (SSEComparisonCode != ~0U) {
962 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
963 getParser().getContext());
964 if (PatchedName.endswith("ss")) {
965 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
966 } else if (PatchedName.endswith("sd")) {
967 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
968 } else if (PatchedName.endswith("ps")) {
969 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
971 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
972 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
977 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
980 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
983 // Determine whether this is an instruction prefix.
985 Name == "lock" || Name == "rep" ||
986 Name == "repe" || Name == "repz" ||
987 Name == "repne" || Name == "repnz" ||
988 Name == "rex64" || Name == "data16";
991 // This does the actual operand parsing. Don't parse any more if we have a
992 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
993 // just want to parse the "lock" as the first instruction and the "incl" as
995 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
997 // Parse '*' modifier.
998 if (getLexer().is(AsmToken::Star)) {
999 SMLoc Loc = Parser.getTok().getLoc();
1000 Operands.push_back(X86Operand::CreateToken("*", Loc));
1001 Parser.Lex(); // Eat the star.
1004 // Read the first operand.
1005 if (X86Operand *Op = ParseOperand())
1006 Operands.push_back(Op);
1008 Parser.EatToEndOfStatement();
1012 while (getLexer().is(AsmToken::Comma)) {
1013 Parser.Lex(); // Eat the comma.
1015 // Parse and remember the operand.
1016 if (X86Operand *Op = ParseOperand())
1017 Operands.push_back(Op);
1019 Parser.EatToEndOfStatement();
1024 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1025 SMLoc Loc = getLexer().getLoc();
1026 Parser.EatToEndOfStatement();
1027 return Error(Loc, "unexpected token in argument list");
1031 if (getLexer().is(AsmToken::EndOfStatement))
1032 Parser.Lex(); // Consume the EndOfStatement
1033 else if (isPrefix && getLexer().is(AsmToken::Slash))
1034 Parser.Lex(); // Consume the prefix separator Slash
1036 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1037 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1038 // documented form in various unofficial manuals, so a lot of code uses it.
1039 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1040 Operands.size() == 3) {
1041 X86Operand &Op = *(X86Operand*)Operands.back();
1042 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1043 isa<MCConstantExpr>(Op.Mem.Disp) &&
1044 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1045 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1046 SMLoc Loc = Op.getEndLoc();
1047 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1051 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1052 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1053 Operands.size() == 3) {
1054 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1055 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1056 isa<MCConstantExpr>(Op.Mem.Disp) &&
1057 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1058 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1059 SMLoc Loc = Op.getEndLoc();
1060 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1064 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1065 if (Name.startswith("ins") && Operands.size() == 3 &&
1066 (Name == "insb" || Name == "insw" || Name == "insl")) {
1067 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1068 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1069 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1070 Operands.pop_back();
1071 Operands.pop_back();
1077 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1078 if (Name.startswith("outs") && Operands.size() == 3 &&
1079 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1080 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1081 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1082 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1083 Operands.pop_back();
1084 Operands.pop_back();
1090 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1091 if (Name.startswith("movs") && Operands.size() == 3 &&
1092 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1093 (is64BitMode() && Name == "movsq"))) {
1094 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1095 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1096 if (isSrcOp(Op) && isDstOp(Op2)) {
1097 Operands.pop_back();
1098 Operands.pop_back();
1103 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1104 if (Name.startswith("lods") && Operands.size() == 3 &&
1105 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1106 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1107 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1108 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1109 if (isSrcOp(*Op1) && Op2->isReg()) {
1111 unsigned reg = Op2->getReg();
1112 bool isLods = Name == "lods";
1113 if (reg == X86::AL && (isLods || Name == "lodsb"))
1115 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1117 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1119 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1124 Operands.pop_back();
1125 Operands.pop_back();
1129 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1133 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1134 if (Name.startswith("stos") && Operands.size() == 3 &&
1135 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1136 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1137 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1138 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1139 if (isDstOp(*Op2) && Op1->isReg()) {
1141 unsigned reg = Op1->getReg();
1142 bool isStos = Name == "stos";
1143 if (reg == X86::AL && (isStos || Name == "stosb"))
1145 else if (reg == X86::AX && (isStos || Name == "stosw"))
1147 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1149 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1154 Operands.pop_back();
1155 Operands.pop_back();
1159 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1164 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1166 if ((Name.startswith("shr") || Name.startswith("sar") ||
1167 Name.startswith("shl") || Name.startswith("sal") ||
1168 Name.startswith("rcl") || Name.startswith("rcr") ||
1169 Name.startswith("rol") || Name.startswith("ror")) &&
1170 Operands.size() == 3) {
1171 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1172 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1173 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1175 Operands.erase(Operands.begin() + 1);
1179 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1180 // instalias with an immediate operand yet.
1181 if (Name == "int" && Operands.size() == 2) {
1182 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1183 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1184 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1186 Operands.erase(Operands.begin() + 1);
1187 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1195 processInstruction(MCInst &Inst,
1196 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1197 switch (Inst.getOpcode()) {
1198 default: return false;
1199 case X86::AND16i16: {
1200 if (!Inst.getOperand(0).isImm() ||
1201 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1205 TmpInst.setOpcode(X86::AND16ri8);
1206 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1207 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1208 TmpInst.addOperand(Inst.getOperand(0));
1212 case X86::AND32i32: {
1213 if (!Inst.getOperand(0).isImm() ||
1214 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1218 TmpInst.setOpcode(X86::AND32ri8);
1219 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1220 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1221 TmpInst.addOperand(Inst.getOperand(0));
1225 case X86::AND64i32: {
1226 if (!Inst.getOperand(0).isImm() ||
1227 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1231 TmpInst.setOpcode(X86::AND64ri8);
1232 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1233 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1234 TmpInst.addOperand(Inst.getOperand(0));
1238 case X86::XOR16i16: {
1239 if (!Inst.getOperand(0).isImm() ||
1240 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1244 TmpInst.setOpcode(X86::XOR16ri8);
1245 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1246 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1247 TmpInst.addOperand(Inst.getOperand(0));
1251 case X86::XOR32i32: {
1252 if (!Inst.getOperand(0).isImm() ||
1253 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1257 TmpInst.setOpcode(X86::XOR32ri8);
1258 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1259 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1260 TmpInst.addOperand(Inst.getOperand(0));
1264 case X86::XOR64i32: {
1265 if (!Inst.getOperand(0).isImm() ||
1266 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1270 TmpInst.setOpcode(X86::XOR64ri8);
1271 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1272 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1273 TmpInst.addOperand(Inst.getOperand(0));
1277 case X86::OR16i16: {
1278 if (!Inst.getOperand(0).isImm() ||
1279 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1283 TmpInst.setOpcode(X86::OR16ri8);
1284 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1285 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1286 TmpInst.addOperand(Inst.getOperand(0));
1290 case X86::OR32i32: {
1291 if (!Inst.getOperand(0).isImm() ||
1292 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1296 TmpInst.setOpcode(X86::OR32ri8);
1297 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1298 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1299 TmpInst.addOperand(Inst.getOperand(0));
1303 case X86::OR64i32: {
1304 if (!Inst.getOperand(0).isImm() ||
1305 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1309 TmpInst.setOpcode(X86::OR64ri8);
1310 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1311 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1312 TmpInst.addOperand(Inst.getOperand(0));
1316 case X86::CMP16i16: {
1317 if (!Inst.getOperand(0).isImm() ||
1318 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1322 TmpInst.setOpcode(X86::CMP16ri8);
1323 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1324 TmpInst.addOperand(Inst.getOperand(0));
1328 case X86::CMP32i32: {
1329 if (!Inst.getOperand(0).isImm() ||
1330 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1334 TmpInst.setOpcode(X86::CMP32ri8);
1335 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1336 TmpInst.addOperand(Inst.getOperand(0));
1340 case X86::CMP64i32: {
1341 if (!Inst.getOperand(0).isImm() ||
1342 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1346 TmpInst.setOpcode(X86::CMP64ri8);
1347 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1348 TmpInst.addOperand(Inst.getOperand(0));
1352 case X86::ADD16i16: {
1353 if (!Inst.getOperand(0).isImm() ||
1354 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1358 TmpInst.setOpcode(X86::ADD16ri8);
1359 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1360 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1361 TmpInst.addOperand(Inst.getOperand(0));
1365 case X86::ADD32i32: {
1366 if (!Inst.getOperand(0).isImm() ||
1367 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1371 TmpInst.setOpcode(X86::ADD32ri8);
1372 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1373 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1374 TmpInst.addOperand(Inst.getOperand(0));
1378 case X86::ADD64i32: {
1379 if (!Inst.getOperand(0).isImm() ||
1380 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1384 TmpInst.setOpcode(X86::ADD64ri8);
1385 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1386 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1387 TmpInst.addOperand(Inst.getOperand(0));
1391 case X86::SUB16i16: {
1392 if (!Inst.getOperand(0).isImm() ||
1393 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1397 TmpInst.setOpcode(X86::SUB16ri8);
1398 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1399 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1400 TmpInst.addOperand(Inst.getOperand(0));
1404 case X86::SUB32i32: {
1405 if (!Inst.getOperand(0).isImm() ||
1406 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1410 TmpInst.setOpcode(X86::SUB32ri8);
1411 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1412 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1413 TmpInst.addOperand(Inst.getOperand(0));
1417 case X86::SUB64i32: {
1418 if (!Inst.getOperand(0).isImm() ||
1419 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1423 TmpInst.setOpcode(X86::SUB64ri8);
1424 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1425 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1426 TmpInst.addOperand(Inst.getOperand(0));
1435 MatchAndEmitInstruction(SMLoc IDLoc,
1436 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1438 assert(!Operands.empty() && "Unexpect empty operand list!");
1439 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1440 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1442 // First, handle aliases that expand to multiple instructions.
1443 // FIXME: This should be replaced with a real .td file alias mechanism.
1444 // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
1446 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1447 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1448 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1449 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1451 Inst.setOpcode(X86::WAIT);
1452 Out.EmitInstruction(Inst);
1455 StringSwitch<const char*>(Op->getToken())
1456 .Case("finit", "fninit")
1457 .Case("fsave", "fnsave")
1458 .Case("fstcw", "fnstcw")
1459 .Case("fstcww", "fnstcw")
1460 .Case("fstenv", "fnstenv")
1461 .Case("fstsw", "fnstsw")
1462 .Case("fstsww", "fnstsw")
1463 .Case("fclex", "fnclex")
1465 assert(Repl && "Unknown wait-prefixed instruction");
1467 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1470 bool WasOriginallyInvalidOperand = false;
1471 unsigned OrigErrorInfo;
1474 // First, try a direct match.
1475 switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo,
1476 getParser().getAssemblerDialect())) {
1479 // Some instructions need post-processing to, for example, tweak which
1480 // encoding is selected. Loop on it while changes happen so the
1481 // individual transformations can chain off each other.
1482 while (processInstruction(Inst, Operands))
1485 Out.EmitInstruction(Inst);
1487 case Match_MissingFeature:
1488 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1490 case Match_ConversionFail:
1491 return Error(IDLoc, "unable to convert operands to instruction");
1492 case Match_InvalidOperand:
1493 WasOriginallyInvalidOperand = true;
1495 case Match_MnemonicFail:
1499 // FIXME: Ideally, we would only attempt suffix matches for things which are
1500 // valid prefixes, and we could just infer the right unambiguous
1501 // type. However, that requires substantially more matcher support than the
1504 // Change the operand to point to a temporary token.
1505 StringRef Base = Op->getToken();
1506 SmallString<16> Tmp;
1509 Op->setTokenValue(Tmp.str());
1511 // If this instruction starts with an 'f', then it is a floating point stack
1512 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1513 // 80-bit floating point, which use the suffixes s,l,t respectively.
1515 // Otherwise, we assume that this may be an integer instruction, which comes
1516 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1517 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1519 // Check for the various suffix matches.
1520 Tmp[Base.size()] = Suffixes[0];
1521 unsigned ErrorInfoIgnore;
1522 unsigned Match1, Match2, Match3, Match4;
1524 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1525 Tmp[Base.size()] = Suffixes[1];
1526 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1527 Tmp[Base.size()] = Suffixes[2];
1528 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1529 Tmp[Base.size()] = Suffixes[3];
1530 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1532 // Restore the old token.
1533 Op->setTokenValue(Base);
1535 // If exactly one matched, then we treat that as a successful match (and the
1536 // instruction will already have been filled in correctly, since the failing
1537 // matches won't have modified it).
1538 unsigned NumSuccessfulMatches =
1539 (Match1 == Match_Success) + (Match2 == Match_Success) +
1540 (Match3 == Match_Success) + (Match4 == Match_Success);
1541 if (NumSuccessfulMatches == 1) {
1542 Out.EmitInstruction(Inst);
1546 // Otherwise, the match failed, try to produce a decent error message.
1548 // If we had multiple suffix matches, then identify this as an ambiguous
1550 if (NumSuccessfulMatches > 1) {
1552 unsigned NumMatches = 0;
1553 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1554 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1555 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1556 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1558 SmallString<126> Msg;
1559 raw_svector_ostream OS(Msg);
1560 OS << "ambiguous instructions require an explicit suffix (could be ";
1561 for (unsigned i = 0; i != NumMatches; ++i) {
1564 if (i + 1 == NumMatches)
1566 OS << "'" << Base << MatchChars[i] << "'";
1569 Error(IDLoc, OS.str());
1573 // Okay, we know that none of the variants matched successfully.
1575 // If all of the instructions reported an invalid mnemonic, then the original
1576 // mnemonic was invalid.
1577 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1578 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1579 if (!WasOriginallyInvalidOperand) {
1580 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1584 // Recover location info for the operand if we know which was the problem.
1585 if (OrigErrorInfo != ~0U) {
1586 if (OrigErrorInfo >= Operands.size())
1587 return Error(IDLoc, "too few operands for instruction");
1589 X86Operand *Operand = (X86Operand*)Operands[OrigErrorInfo];
1590 if (Operand->getStartLoc().isValid()) {
1591 SMRange OperandRange = Operand->getLocRange();
1592 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1597 return Error(IDLoc, "invalid operand for instruction");
1600 // If one instruction matched with a missing feature, report this as a
1602 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1603 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1604 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1608 // If one instruction matched with an invalid operand, report this as an
1610 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1611 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1612 Error(IDLoc, "invalid operand for instruction");
1616 // If all of these were an outright failure, report it in a useless way.
1617 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
1622 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1623 StringRef IDVal = DirectiveID.getIdentifier();
1624 if (IDVal == ".word")
1625 return ParseDirectiveWord(2, DirectiveID.getLoc());
1626 else if (IDVal.startswith(".code"))
1627 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1631 /// ParseDirectiveWord
1632 /// ::= .word [ expression (, expression)* ]
1633 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1634 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1636 const MCExpr *Value;
1637 if (getParser().ParseExpression(Value))
1640 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1642 if (getLexer().is(AsmToken::EndOfStatement))
1645 // FIXME: Improve diagnostic.
1646 if (getLexer().isNot(AsmToken::Comma))
1647 return Error(L, "unexpected token in directive");
1656 /// ParseDirectiveCode
1657 /// ::= .code32 | .code64
1658 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1659 if (IDVal == ".code32") {
1661 if (is64BitMode()) {
1663 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1665 } else if (IDVal == ".code64") {
1667 if (!is64BitMode()) {
1669 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1672 return Error(L, "unexpected directive " + IDVal);
1679 extern "C" void LLVMInitializeX86AsmLexer();
1681 // Force static initialization.
1682 extern "C" void LLVMInitializeX86AsmParser() {
1683 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1684 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1685 LLVMInitializeX86AsmLexer();
1688 #define GET_REGISTER_MATCHER
1689 #define GET_MATCHER_IMPLEMENTATION
1690 #include "X86GenAsmMatcher.inc"