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/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/TargetRegistry.h"
26 #include "llvm/Support/raw_ostream.h"
33 class X86AsmParser : public MCTargetAsmParser {
37 MCAsmParser &getParser() const { return Parser; }
39 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
41 bool Error(SMLoc L, const Twine &Msg,
42 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>(),
43 bool matchingInlineAsm = false) {
44 if (matchingInlineAsm) return true;
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(unsigned SegReg, SMLoc StartLoc);
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,
69 bool MatchInstruction(SMLoc IDLoc,
70 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
71 MCStreamer &Out, unsigned &Kind, unsigned &Opcode,
72 MatchInstMapAndConstraintsImpl &MapAndConstraints,
73 unsigned &OrigErrorInfo, bool matchingInlineAsm = false);
75 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
76 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
77 bool isSrcOp(X86Operand &Op);
79 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
80 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
81 bool isDstOp(X86Operand &Op);
83 bool is64BitMode() const {
84 // FIXME: Can tablegen auto-generate this?
85 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
88 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
89 setAvailableFeatures(FB);
92 /// @name Auto-generated Matcher Functions
95 #define GET_ASSEMBLER_HEADER
96 #include "X86GenAsmMatcher.inc"
101 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
102 : MCTargetAsmParser(), STI(sti), Parser(parser) {
104 // Initialize the set of available features.
105 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
107 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
109 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
110 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
112 virtual bool ParseDirective(AsmToken DirectiveID);
114 bool isParsingIntelSyntax() {
115 return getParser().getAssemblerDialect();
118 } // end anonymous namespace
120 /// @name Auto-generated Match Functions
123 static unsigned MatchRegisterName(StringRef Name);
127 static bool isImmSExti16i8Value(uint64_t Value) {
128 return (( Value <= 0x000000000000007FULL)||
129 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
130 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
133 static bool isImmSExti32i8Value(uint64_t Value) {
134 return (( Value <= 0x000000000000007FULL)||
135 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
136 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
139 static bool isImmZExtu32u8Value(uint64_t Value) {
140 return (Value <= 0x00000000000000FFULL);
143 static bool isImmSExti64i8Value(uint64_t Value) {
144 return (( Value <= 0x000000000000007FULL)||
145 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
148 static bool isImmSExti64i32Value(uint64_t Value) {
149 return (( Value <= 0x000000007FFFFFFFULL)||
150 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
154 /// X86Operand - Instances of this class represent a parsed X86 machine
156 struct X86Operand : public MCParsedAsmOperand {
164 SMLoc StartLoc, EndLoc;
190 X86Operand(KindTy K, SMLoc Start, SMLoc End)
191 : Kind(K), StartLoc(Start), EndLoc(End) {}
193 /// getStartLoc - Get the location of the first token of this operand.
194 SMLoc getStartLoc() const { return StartLoc; }
195 /// getEndLoc - Get the location of the last token of this operand.
196 SMLoc getEndLoc() const { return EndLoc; }
197 /// getLocRange - Get the range between the first and last token of this
199 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
201 virtual void print(raw_ostream &OS) const {}
203 StringRef getToken() const {
204 assert(Kind == Token && "Invalid access!");
205 return StringRef(Tok.Data, Tok.Length);
207 void setTokenValue(StringRef Value) {
208 assert(Kind == Token && "Invalid access!");
209 Tok.Data = Value.data();
210 Tok.Length = Value.size();
213 unsigned getReg() const {
214 assert(Kind == Register && "Invalid access!");
218 const MCExpr *getImm() const {
219 assert(Kind == Immediate && "Invalid access!");
223 const MCExpr *getMemDisp() const {
224 assert(Kind == Memory && "Invalid access!");
227 unsigned getMemSegReg() const {
228 assert(Kind == Memory && "Invalid access!");
231 unsigned getMemBaseReg() const {
232 assert(Kind == Memory && "Invalid access!");
235 unsigned getMemIndexReg() const {
236 assert(Kind == Memory && "Invalid access!");
239 unsigned getMemScale() const {
240 assert(Kind == Memory && "Invalid access!");
244 bool isToken() const {return Kind == Token; }
246 bool isImm() const { return Kind == Immediate; }
248 bool isImmSExti16i8() const {
252 // If this isn't a constant expr, just assume it fits and let relaxation
254 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
258 // Otherwise, check the value is in a range that makes sense for this
260 return isImmSExti16i8Value(CE->getValue());
262 bool isImmSExti32i8() const {
266 // If this isn't a constant expr, just assume it fits and let relaxation
268 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
272 // Otherwise, check the value is in a range that makes sense for this
274 return isImmSExti32i8Value(CE->getValue());
276 bool isImmZExtu32u8() const {
280 // If this isn't a constant expr, just assume it fits and let relaxation
282 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
286 // Otherwise, check the value is in a range that makes sense for this
288 return isImmZExtu32u8Value(CE->getValue());
290 bool isImmSExti64i8() const {
294 // If this isn't a constant expr, just assume it fits and let relaxation
296 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
300 // Otherwise, check the value is in a range that makes sense for this
302 return isImmSExti64i8Value(CE->getValue());
304 bool isImmSExti64i32() const {
308 // If this isn't a constant expr, just assume it fits and let relaxation
310 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
314 // Otherwise, check the value is in a range that makes sense for this
316 return isImmSExti64i32Value(CE->getValue());
319 bool isMem() const { return Kind == Memory; }
320 bool isMem8() const {
321 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
323 bool isMem16() const {
324 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
326 bool isMem32() const {
327 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
329 bool isMem64() const {
330 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
332 bool isMem80() const {
333 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
335 bool isMem128() const {
336 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
338 bool isMem256() const {
339 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
342 bool isMemVX32() const {
343 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
344 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
346 bool isMemVY32() const {
347 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
348 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
350 bool isMemVX64() const {
351 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
352 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
354 bool isMemVY64() const {
355 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
356 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
359 bool isAbsMem() const {
360 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
361 !getMemIndexReg() && getMemScale() == 1;
364 bool isReg() const { return Kind == Register; }
366 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
367 // Add as immediates when possible.
368 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
369 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
371 Inst.addOperand(MCOperand::CreateExpr(Expr));
374 void addRegOperands(MCInst &Inst, unsigned N) const {
375 assert(N == 1 && "Invalid number of operands!");
376 Inst.addOperand(MCOperand::CreateReg(getReg()));
379 void addImmOperands(MCInst &Inst, unsigned N) const {
380 assert(N == 1 && "Invalid number of operands!");
381 addExpr(Inst, getImm());
384 void addMem8Operands(MCInst &Inst, unsigned N) const {
385 addMemOperands(Inst, N);
387 void addMem16Operands(MCInst &Inst, unsigned N) const {
388 addMemOperands(Inst, N);
390 void addMem32Operands(MCInst &Inst, unsigned N) const {
391 addMemOperands(Inst, N);
393 void addMem64Operands(MCInst &Inst, unsigned N) const {
394 addMemOperands(Inst, N);
396 void addMem80Operands(MCInst &Inst, unsigned N) const {
397 addMemOperands(Inst, N);
399 void addMem128Operands(MCInst &Inst, unsigned N) const {
400 addMemOperands(Inst, N);
402 void addMem256Operands(MCInst &Inst, unsigned N) const {
403 addMemOperands(Inst, N);
405 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
406 addMemOperands(Inst, N);
408 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
409 addMemOperands(Inst, N);
411 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
412 addMemOperands(Inst, N);
414 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
415 addMemOperands(Inst, N);
418 void addMemOperands(MCInst &Inst, unsigned N) const {
419 assert((N == 5) && "Invalid number of operands!");
420 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
421 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
422 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
423 addExpr(Inst, getMemDisp());
424 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
427 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
428 assert((N == 1) && "Invalid number of operands!");
429 // Add as immediates when possible.
430 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
431 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
433 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
436 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
437 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
438 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
439 Res->Tok.Data = Str.data();
440 Res->Tok.Length = Str.size();
444 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
445 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
446 Res->Reg.RegNo = RegNo;
450 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
451 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
456 /// Create an absolute memory operand.
457 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
458 SMLoc EndLoc, unsigned Size = 0) {
459 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
461 Res->Mem.Disp = Disp;
462 Res->Mem.BaseReg = 0;
463 Res->Mem.IndexReg = 0;
465 Res->Mem.Size = Size;
469 /// Create a generalized memory operand.
470 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
471 unsigned BaseReg, unsigned IndexReg,
472 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
474 // We should never just have a displacement, that should be parsed as an
475 // absolute memory operand.
476 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
478 // The scale should always be one of {1,2,4,8}.
479 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
481 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
482 Res->Mem.SegReg = SegReg;
483 Res->Mem.Disp = Disp;
484 Res->Mem.BaseReg = BaseReg;
485 Res->Mem.IndexReg = IndexReg;
486 Res->Mem.Scale = Scale;
487 Res->Mem.Size = Size;
492 } // end anonymous namespace.
494 bool X86AsmParser::isSrcOp(X86Operand &Op) {
495 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
497 return (Op.isMem() &&
498 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
499 isa<MCConstantExpr>(Op.Mem.Disp) &&
500 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
501 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
504 bool X86AsmParser::isDstOp(X86Operand &Op) {
505 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
508 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
509 isa<MCConstantExpr>(Op.Mem.Disp) &&
510 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
511 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
514 bool X86AsmParser::ParseRegister(unsigned &RegNo,
515 SMLoc &StartLoc, SMLoc &EndLoc) {
517 const AsmToken &PercentTok = Parser.getTok();
518 StartLoc = PercentTok.getLoc();
520 // If we encounter a %, ignore it. This code handles registers with and
521 // without the prefix, unprefixed registers can occur in cfi directives.
522 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
523 Parser.Lex(); // Eat percent token.
525 const AsmToken &Tok = Parser.getTok();
526 if (Tok.isNot(AsmToken::Identifier)) {
527 if (isParsingIntelSyntax()) return true;
528 return Error(StartLoc, "invalid register name",
529 SMRange(StartLoc, Tok.getEndLoc()));
532 RegNo = MatchRegisterName(Tok.getString());
534 // If the match failed, try the register name as lowercase.
536 RegNo = MatchRegisterName(Tok.getString().lower());
538 if (!is64BitMode()) {
539 // FIXME: This should be done using Requires<In32BitMode> and
540 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
542 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
544 if (RegNo == X86::RIZ ||
545 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
546 X86II::isX86_64NonExtLowByteReg(RegNo) ||
547 X86II::isX86_64ExtendedReg(RegNo))
548 return Error(StartLoc, "register %"
549 + Tok.getString() + " is only available in 64-bit mode",
550 SMRange(StartLoc, Tok.getEndLoc()));
553 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
554 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
556 EndLoc = Tok.getLoc();
557 Parser.Lex(); // Eat 'st'
559 // Check to see if we have '(4)' after %st.
560 if (getLexer().isNot(AsmToken::LParen))
565 const AsmToken &IntTok = Parser.getTok();
566 if (IntTok.isNot(AsmToken::Integer))
567 return Error(IntTok.getLoc(), "expected stack index");
568 switch (IntTok.getIntVal()) {
569 case 0: RegNo = X86::ST0; break;
570 case 1: RegNo = X86::ST1; break;
571 case 2: RegNo = X86::ST2; break;
572 case 3: RegNo = X86::ST3; break;
573 case 4: RegNo = X86::ST4; break;
574 case 5: RegNo = X86::ST5; break;
575 case 6: RegNo = X86::ST6; break;
576 case 7: RegNo = X86::ST7; break;
577 default: return Error(IntTok.getLoc(), "invalid stack index");
580 if (getParser().Lex().isNot(AsmToken::RParen))
581 return Error(Parser.getTok().getLoc(), "expected ')'");
583 EndLoc = Tok.getLoc();
584 Parser.Lex(); // Eat ')'
588 // If this is "db[0-7]", match it as an alias
590 if (RegNo == 0 && Tok.getString().size() == 3 &&
591 Tok.getString().startswith("db")) {
592 switch (Tok.getString()[2]) {
593 case '0': RegNo = X86::DR0; break;
594 case '1': RegNo = X86::DR1; break;
595 case '2': RegNo = X86::DR2; break;
596 case '3': RegNo = X86::DR3; break;
597 case '4': RegNo = X86::DR4; break;
598 case '5': RegNo = X86::DR5; break;
599 case '6': RegNo = X86::DR6; break;
600 case '7': RegNo = X86::DR7; break;
604 EndLoc = Tok.getLoc();
605 Parser.Lex(); // Eat it.
611 if (isParsingIntelSyntax()) return true;
612 return Error(StartLoc, "invalid register name",
613 SMRange(StartLoc, Tok.getEndLoc()));
616 EndLoc = Tok.getEndLoc();
617 Parser.Lex(); // Eat identifier token.
621 X86Operand *X86AsmParser::ParseOperand() {
622 if (isParsingIntelSyntax())
623 return ParseIntelOperand();
624 return ParseATTOperand();
627 /// getIntelMemOperandSize - Return intel memory operand size.
628 static unsigned getIntelMemOperandSize(StringRef OpStr) {
629 unsigned Size = StringSwitch<unsigned>(OpStr)
630 .Cases("BYTE", "byte", 8)
631 .Cases("WORD", "word", 16)
632 .Cases("DWORD", "dword", 32)
633 .Cases("QWORD", "qword", 64)
634 .Cases("XWORD", "xword", 80)
635 .Cases("XMMWORD", "xmmword", 128)
636 .Cases("YMMWORD", "ymmword", 256)
641 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
643 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
644 SMLoc Start = Parser.getTok().getLoc(), End;
646 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
647 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
650 if (getLexer().isNot(AsmToken::LBrac))
651 return ErrorOperand(Start, "Expected '[' token!");
654 if (getLexer().is(AsmToken::Identifier)) {
656 if (ParseRegister(BaseReg, Start, End)) {
657 // Handle '[' 'symbol' ']'
658 if (getParser().ParseExpression(Disp, End)) return 0;
659 if (getLexer().isNot(AsmToken::RBrac))
660 return ErrorOperand(Start, "Expected ']' token!");
662 return X86Operand::CreateMem(Disp, Start, End, Size);
664 } else if (getLexer().is(AsmToken::Integer)) {
665 int64_t Val = Parser.getTok().getIntVal();
667 SMLoc Loc = Parser.getTok().getLoc();
668 if (getLexer().is(AsmToken::RBrac)) {
669 // Handle '[' number ']'
671 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
673 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
675 return X86Operand::CreateMem(Disp, Start, End, Size);
676 } else if (getLexer().is(AsmToken::Star)) {
677 // Handle '[' Scale*IndexReg ']'
679 SMLoc IdxRegLoc = Parser.getTok().getLoc();
680 if (ParseRegister(IndexReg, IdxRegLoc, End))
681 return ErrorOperand(IdxRegLoc, "Expected register");
684 return ErrorOperand(Loc, "Unexpected token");
687 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
688 bool isPlus = getLexer().is(AsmToken::Plus);
690 SMLoc PlusLoc = Parser.getTok().getLoc();
691 if (getLexer().is(AsmToken::Integer)) {
692 int64_t Val = Parser.getTok().getIntVal();
694 if (getLexer().is(AsmToken::Star)) {
696 SMLoc IdxRegLoc = Parser.getTok().getLoc();
697 if (ParseRegister(IndexReg, IdxRegLoc, End))
698 return ErrorOperand(IdxRegLoc, "Expected register");
700 } else if (getLexer().is(AsmToken::RBrac)) {
701 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
702 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
704 return ErrorOperand(PlusLoc, "unexpected token after +");
705 } else if (getLexer().is(AsmToken::Identifier)) {
706 // This could be an index register or a displacement expression.
707 End = Parser.getTok().getLoc();
709 ParseRegister(IndexReg, Start, End);
710 else if (getParser().ParseExpression(Disp, End)) return 0;
714 if (getLexer().isNot(AsmToken::RBrac))
715 if (getParser().ParseExpression(Disp, End)) return 0;
717 End = Parser.getTok().getLoc();
718 if (getLexer().isNot(AsmToken::RBrac))
719 return ErrorOperand(End, "expected ']' token!");
721 End = Parser.getTok().getLoc();
724 if (!BaseReg && !IndexReg)
725 return X86Operand::CreateMem(Disp, Start, End, Size);
727 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
731 /// ParseIntelMemOperand - Parse intel style memory operand.
732 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg, SMLoc Start) {
733 const AsmToken &Tok = Parser.getTok();
736 unsigned Size = getIntelMemOperandSize(Tok.getString());
739 assert ((Tok.getString() == "PTR" || Tok.getString() == "ptr") &&
740 "Unexpected token!");
744 if (getLexer().is(AsmToken::LBrac))
745 return ParseIntelBracExpression(SegReg, Size);
747 if (!ParseRegister(SegReg, Start, End)) {
748 // Handel SegReg : [ ... ]
749 if (getLexer().isNot(AsmToken::Colon))
750 return ErrorOperand(Start, "Expected ':' token!");
751 Parser.Lex(); // Eat :
752 if (getLexer().isNot(AsmToken::LBrac))
753 return ErrorOperand(Start, "Expected '[' token!");
754 return ParseIntelBracExpression(SegReg, Size);
757 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
758 if (getParser().ParseExpression(Disp, End)) return 0;
759 return X86Operand::CreateMem(Disp, Start, End, Size);
762 X86Operand *X86AsmParser::ParseIntelOperand() {
763 SMLoc Start = Parser.getTok().getLoc(), End;
766 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
767 getLexer().is(AsmToken::Minus)) {
769 if (!getParser().ParseExpression(Val, End)) {
770 End = Parser.getTok().getLoc();
771 return X86Operand::CreateImm(Val, Start, End);
777 if (!ParseRegister(RegNo, Start, End)) {
778 // If this is a segment register followed by a ':', then this is the start
779 // of a memory reference, otherwise this is a normal register reference.
780 if (getLexer().isNot(AsmToken::Colon))
781 return X86Operand::CreateReg(RegNo, Start, Parser.getTok().getLoc());
783 getParser().Lex(); // Eat the colon.
784 return ParseIntelMemOperand(RegNo, Start);
788 return ParseIntelMemOperand(0, Start);
791 X86Operand *X86AsmParser::ParseATTOperand() {
792 switch (getLexer().getKind()) {
794 // Parse a memory operand with no segment register.
795 return ParseMemOperand(0, Parser.getTok().getLoc());
796 case AsmToken::Percent: {
797 // Read the register.
800 if (ParseRegister(RegNo, Start, End)) return 0;
801 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
802 Error(Start, "%eiz and %riz can only be used as index registers",
803 SMRange(Start, End));
807 // If this is a segment register followed by a ':', then this is the start
808 // of a memory reference, otherwise this is a normal register reference.
809 if (getLexer().isNot(AsmToken::Colon))
810 return X86Operand::CreateReg(RegNo, Start, End);
813 getParser().Lex(); // Eat the colon.
814 return ParseMemOperand(RegNo, Start);
816 case AsmToken::Dollar: {
818 SMLoc Start = Parser.getTok().getLoc(), End;
821 if (getParser().ParseExpression(Val, End))
823 return X86Operand::CreateImm(Val, Start, End);
828 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
829 /// has already been parsed if present.
830 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
832 // We have to disambiguate a parenthesized expression "(4+5)" from the start
833 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
834 // only way to do this without lookahead is to eat the '(' and see what is
836 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
837 if (getLexer().isNot(AsmToken::LParen)) {
839 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
841 // After parsing the base expression we could either have a parenthesized
842 // memory address or not. If not, return now. If so, eat the (.
843 if (getLexer().isNot(AsmToken::LParen)) {
844 // Unless we have a segment register, treat this as an immediate.
846 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
847 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
853 // Okay, we have a '('. We don't know if this is an expression or not, but
854 // so we have to eat the ( to see beyond it.
855 SMLoc LParenLoc = Parser.getTok().getLoc();
856 Parser.Lex(); // Eat the '('.
858 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
859 // Nothing to do here, fall into the code below with the '(' part of the
860 // memory operand consumed.
864 // It must be an parenthesized expression, parse it now.
865 if (getParser().ParseParenExpression(Disp, ExprEnd))
868 // After parsing the base expression we could either have a parenthesized
869 // memory address or not. If not, return now. If so, eat the (.
870 if (getLexer().isNot(AsmToken::LParen)) {
871 // Unless we have a segment register, treat this as an immediate.
873 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
874 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
882 // If we reached here, then we just ate the ( of the memory operand. Process
883 // the rest of the memory operand.
884 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
887 if (getLexer().is(AsmToken::Percent)) {
888 SMLoc StartLoc, EndLoc;
889 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
890 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
891 Error(StartLoc, "eiz and riz can only be used as index registers",
892 SMRange(StartLoc, EndLoc));
897 if (getLexer().is(AsmToken::Comma)) {
898 Parser.Lex(); // Eat the comma.
899 IndexLoc = Parser.getTok().getLoc();
901 // Following the comma we should have either an index register, or a scale
902 // value. We don't support the later form, but we want to parse it
905 // Not that even though it would be completely consistent to support syntax
906 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
907 if (getLexer().is(AsmToken::Percent)) {
909 if (ParseRegister(IndexReg, L, L)) return 0;
911 if (getLexer().isNot(AsmToken::RParen)) {
912 // Parse the scale amount:
913 // ::= ',' [scale-expression]
914 if (getLexer().isNot(AsmToken::Comma)) {
915 Error(Parser.getTok().getLoc(),
916 "expected comma in scale expression");
919 Parser.Lex(); // Eat the comma.
921 if (getLexer().isNot(AsmToken::RParen)) {
922 SMLoc Loc = Parser.getTok().getLoc();
925 if (getParser().ParseAbsoluteExpression(ScaleVal)){
926 Error(Loc, "expected scale expression");
930 // Validate the scale amount.
931 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
932 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
935 Scale = (unsigned)ScaleVal;
938 } else if (getLexer().isNot(AsmToken::RParen)) {
939 // A scale amount without an index is ignored.
941 SMLoc Loc = Parser.getTok().getLoc();
944 if (getParser().ParseAbsoluteExpression(Value))
948 Warning(Loc, "scale factor without index register is ignored");
953 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
954 if (getLexer().isNot(AsmToken::RParen)) {
955 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
958 SMLoc MemEnd = Parser.getTok().getLoc();
959 Parser.Lex(); // Eat the ')'.
961 // If we have both a base register and an index register make sure they are
962 // both 64-bit or 32-bit registers.
963 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
964 if (BaseReg != 0 && IndexReg != 0) {
965 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
966 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
967 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
968 IndexReg != X86::RIZ) {
969 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
972 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
973 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
974 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
975 IndexReg != X86::EIZ){
976 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
981 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
986 ParseInstruction(StringRef Name, SMLoc NameLoc,
987 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
988 StringRef PatchedName = Name;
990 // FIXME: Hack to recognize setneb as setne.
991 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
992 PatchedName != "setb" && PatchedName != "setnb")
993 PatchedName = PatchedName.substr(0, Name.size()-1);
995 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
996 const MCExpr *ExtraImmOp = 0;
997 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
998 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
999 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1000 bool IsVCMP = PatchedName[0] == 'v';
1001 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1002 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1003 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1007 .Case("unord", 0x03)
1012 /* AVX only from here */
1013 .Case("eq_uq", 0x08)
1016 .Case("false", 0x0B)
1017 .Case("neq_oq", 0x0C)
1021 .Case("eq_os", 0x10)
1022 .Case("lt_oq", 0x11)
1023 .Case("le_oq", 0x12)
1024 .Case("unord_s", 0x13)
1025 .Case("neq_us", 0x14)
1026 .Case("nlt_uq", 0x15)
1027 .Case("nle_uq", 0x16)
1028 .Case("ord_s", 0x17)
1029 .Case("eq_us", 0x18)
1030 .Case("nge_uq", 0x19)
1031 .Case("ngt_uq", 0x1A)
1032 .Case("false_os", 0x1B)
1033 .Case("neq_os", 0x1C)
1034 .Case("ge_oq", 0x1D)
1035 .Case("gt_oq", 0x1E)
1036 .Case("true_us", 0x1F)
1038 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1039 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1040 getParser().getContext());
1041 if (PatchedName.endswith("ss")) {
1042 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1043 } else if (PatchedName.endswith("sd")) {
1044 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1045 } else if (PatchedName.endswith("ps")) {
1046 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1048 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1049 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1054 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1056 if (ExtraImmOp && !isParsingIntelSyntax())
1057 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1059 // Determine whether this is an instruction prefix.
1061 Name == "lock" || Name == "rep" ||
1062 Name == "repe" || Name == "repz" ||
1063 Name == "repne" || Name == "repnz" ||
1064 Name == "rex64" || Name == "data16";
1067 // This does the actual operand parsing. Don't parse any more if we have a
1068 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1069 // just want to parse the "lock" as the first instruction and the "incl" as
1071 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1073 // Parse '*' modifier.
1074 if (getLexer().is(AsmToken::Star)) {
1075 SMLoc Loc = Parser.getTok().getLoc();
1076 Operands.push_back(X86Operand::CreateToken("*", Loc));
1077 Parser.Lex(); // Eat the star.
1080 // Read the first operand.
1081 if (X86Operand *Op = ParseOperand())
1082 Operands.push_back(Op);
1084 Parser.EatToEndOfStatement();
1088 while (getLexer().is(AsmToken::Comma)) {
1089 Parser.Lex(); // Eat the comma.
1091 // Parse and remember the operand.
1092 if (X86Operand *Op = ParseOperand())
1093 Operands.push_back(Op);
1095 Parser.EatToEndOfStatement();
1100 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1101 SMLoc Loc = getLexer().getLoc();
1102 Parser.EatToEndOfStatement();
1103 return Error(Loc, "unexpected token in argument list");
1107 if (getLexer().is(AsmToken::EndOfStatement))
1108 Parser.Lex(); // Consume the EndOfStatement
1109 else if (isPrefix && getLexer().is(AsmToken::Slash))
1110 Parser.Lex(); // Consume the prefix separator Slash
1112 if (ExtraImmOp && isParsingIntelSyntax())
1113 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1115 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1116 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1117 // documented form in various unofficial manuals, so a lot of code uses it.
1118 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1119 Operands.size() == 3) {
1120 X86Operand &Op = *(X86Operand*)Operands.back();
1121 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1122 isa<MCConstantExpr>(Op.Mem.Disp) &&
1123 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1124 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1125 SMLoc Loc = Op.getEndLoc();
1126 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1130 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1131 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1132 Operands.size() == 3) {
1133 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1134 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1135 isa<MCConstantExpr>(Op.Mem.Disp) &&
1136 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1137 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1138 SMLoc Loc = Op.getEndLoc();
1139 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1143 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1144 if (Name.startswith("ins") && Operands.size() == 3 &&
1145 (Name == "insb" || Name == "insw" || Name == "insl")) {
1146 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1147 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1148 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1149 Operands.pop_back();
1150 Operands.pop_back();
1156 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1157 if (Name.startswith("outs") && Operands.size() == 3 &&
1158 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1159 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1160 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1161 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1162 Operands.pop_back();
1163 Operands.pop_back();
1169 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1170 if (Name.startswith("movs") && Operands.size() == 3 &&
1171 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1172 (is64BitMode() && Name == "movsq"))) {
1173 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1174 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1175 if (isSrcOp(Op) && isDstOp(Op2)) {
1176 Operands.pop_back();
1177 Operands.pop_back();
1182 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1183 if (Name.startswith("lods") && Operands.size() == 3 &&
1184 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1185 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1186 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1187 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1188 if (isSrcOp(*Op1) && Op2->isReg()) {
1190 unsigned reg = Op2->getReg();
1191 bool isLods = Name == "lods";
1192 if (reg == X86::AL && (isLods || Name == "lodsb"))
1194 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1196 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1198 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1203 Operands.pop_back();
1204 Operands.pop_back();
1208 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1212 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1213 if (Name.startswith("stos") && Operands.size() == 3 &&
1214 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1215 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1216 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1217 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1218 if (isDstOp(*Op2) && Op1->isReg()) {
1220 unsigned reg = Op1->getReg();
1221 bool isStos = Name == "stos";
1222 if (reg == X86::AL && (isStos || Name == "stosb"))
1224 else if (reg == X86::AX && (isStos || Name == "stosw"))
1226 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1228 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1233 Operands.pop_back();
1234 Operands.pop_back();
1238 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1243 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1245 if ((Name.startswith("shr") || Name.startswith("sar") ||
1246 Name.startswith("shl") || Name.startswith("sal") ||
1247 Name.startswith("rcl") || Name.startswith("rcr") ||
1248 Name.startswith("rol") || Name.startswith("ror")) &&
1249 Operands.size() == 3) {
1250 if (isParsingIntelSyntax()) {
1252 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1253 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1254 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1256 Operands.pop_back();
1259 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1260 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1261 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1263 Operands.erase(Operands.begin() + 1);
1268 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1269 // instalias with an immediate operand yet.
1270 if (Name == "int" && Operands.size() == 2) {
1271 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1272 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1273 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1275 Operands.erase(Operands.begin() + 1);
1276 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1284 processInstruction(MCInst &Inst,
1285 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1286 switch (Inst.getOpcode()) {
1287 default: return false;
1288 case X86::AND16i16: {
1289 if (!Inst.getOperand(0).isImm() ||
1290 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1294 TmpInst.setOpcode(X86::AND16ri8);
1295 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1296 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1297 TmpInst.addOperand(Inst.getOperand(0));
1301 case X86::AND32i32: {
1302 if (!Inst.getOperand(0).isImm() ||
1303 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1307 TmpInst.setOpcode(X86::AND32ri8);
1308 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1309 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1310 TmpInst.addOperand(Inst.getOperand(0));
1314 case X86::AND64i32: {
1315 if (!Inst.getOperand(0).isImm() ||
1316 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1320 TmpInst.setOpcode(X86::AND64ri8);
1321 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1322 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1323 TmpInst.addOperand(Inst.getOperand(0));
1327 case X86::XOR16i16: {
1328 if (!Inst.getOperand(0).isImm() ||
1329 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1333 TmpInst.setOpcode(X86::XOR16ri8);
1334 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1335 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1336 TmpInst.addOperand(Inst.getOperand(0));
1340 case X86::XOR32i32: {
1341 if (!Inst.getOperand(0).isImm() ||
1342 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1346 TmpInst.setOpcode(X86::XOR32ri8);
1347 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1348 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1349 TmpInst.addOperand(Inst.getOperand(0));
1353 case X86::XOR64i32: {
1354 if (!Inst.getOperand(0).isImm() ||
1355 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1359 TmpInst.setOpcode(X86::XOR64ri8);
1360 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1361 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1362 TmpInst.addOperand(Inst.getOperand(0));
1366 case X86::OR16i16: {
1367 if (!Inst.getOperand(0).isImm() ||
1368 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1372 TmpInst.setOpcode(X86::OR16ri8);
1373 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1374 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1375 TmpInst.addOperand(Inst.getOperand(0));
1379 case X86::OR32i32: {
1380 if (!Inst.getOperand(0).isImm() ||
1381 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1385 TmpInst.setOpcode(X86::OR32ri8);
1386 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1387 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1388 TmpInst.addOperand(Inst.getOperand(0));
1392 case X86::OR64i32: {
1393 if (!Inst.getOperand(0).isImm() ||
1394 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1398 TmpInst.setOpcode(X86::OR64ri8);
1399 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1400 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1401 TmpInst.addOperand(Inst.getOperand(0));
1405 case X86::CMP16i16: {
1406 if (!Inst.getOperand(0).isImm() ||
1407 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1411 TmpInst.setOpcode(X86::CMP16ri8);
1412 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1413 TmpInst.addOperand(Inst.getOperand(0));
1417 case X86::CMP32i32: {
1418 if (!Inst.getOperand(0).isImm() ||
1419 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1423 TmpInst.setOpcode(X86::CMP32ri8);
1424 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1425 TmpInst.addOperand(Inst.getOperand(0));
1429 case X86::CMP64i32: {
1430 if (!Inst.getOperand(0).isImm() ||
1431 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1435 TmpInst.setOpcode(X86::CMP64ri8);
1436 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1437 TmpInst.addOperand(Inst.getOperand(0));
1441 case X86::ADD16i16: {
1442 if (!Inst.getOperand(0).isImm() ||
1443 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1447 TmpInst.setOpcode(X86::ADD16ri8);
1448 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1449 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1450 TmpInst.addOperand(Inst.getOperand(0));
1454 case X86::ADD32i32: {
1455 if (!Inst.getOperand(0).isImm() ||
1456 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1460 TmpInst.setOpcode(X86::ADD32ri8);
1461 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1462 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1463 TmpInst.addOperand(Inst.getOperand(0));
1467 case X86::ADD64i32: {
1468 if (!Inst.getOperand(0).isImm() ||
1469 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1473 TmpInst.setOpcode(X86::ADD64ri8);
1474 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1475 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1476 TmpInst.addOperand(Inst.getOperand(0));
1480 case X86::SUB16i16: {
1481 if (!Inst.getOperand(0).isImm() ||
1482 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1486 TmpInst.setOpcode(X86::SUB16ri8);
1487 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1488 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1489 TmpInst.addOperand(Inst.getOperand(0));
1493 case X86::SUB32i32: {
1494 if (!Inst.getOperand(0).isImm() ||
1495 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1499 TmpInst.setOpcode(X86::SUB32ri8);
1500 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1501 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1502 TmpInst.addOperand(Inst.getOperand(0));
1506 case X86::SUB64i32: {
1507 if (!Inst.getOperand(0).isImm() ||
1508 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1512 TmpInst.setOpcode(X86::SUB64ri8);
1513 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1514 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1515 TmpInst.addOperand(Inst.getOperand(0));
1523 MatchAndEmitInstruction(SMLoc IDLoc,
1524 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1529 MatchInstMapAndConstraints MapAndConstraints;
1530 bool Error = MatchInstruction(IDLoc, Operands, Out, Kind, Opcode,
1531 MapAndConstraints, ErrorInfo);
1536 MatchInstruction(SMLoc IDLoc,
1537 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1538 MCStreamer &Out, unsigned &Kind, unsigned &Opcode,
1539 SmallVectorImpl<std::pair< unsigned, std::string > > &MapAndConstraints,
1540 unsigned &OrigErrorInfo, bool matchingInlineAsm) {
1541 assert(!Operands.empty() && "Unexpect empty operand list!");
1542 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1543 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1544 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
1546 // First, handle aliases that expand to multiple instructions.
1547 // FIXME: This should be replaced with a real .td file alias mechanism.
1548 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
1550 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1551 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1552 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1553 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1555 Inst.setOpcode(X86::WAIT);
1557 if (!matchingInlineAsm)
1558 Out.EmitInstruction(Inst);
1561 StringSwitch<const char*>(Op->getToken())
1562 .Case("finit", "fninit")
1563 .Case("fsave", "fnsave")
1564 .Case("fstcw", "fnstcw")
1565 .Case("fstcww", "fnstcw")
1566 .Case("fstenv", "fnstenv")
1567 .Case("fstsw", "fnstsw")
1568 .Case("fstsww", "fnstsw")
1569 .Case("fclex", "fnclex")
1571 assert(Repl && "Unknown wait-prefixed instruction");
1573 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1576 bool WasOriginallyInvalidOperand = false;
1579 // First, try a direct match.
1580 switch (MatchInstructionImpl(Operands, Kind, Inst, MapAndConstraints,
1581 OrigErrorInfo, matchingInlineAsm,
1582 isParsingIntelSyntax())) {
1585 // Some instructions need post-processing to, for example, tweak which
1586 // encoding is selected. Loop on it while changes happen so the
1587 // individual transformations can chain off each other.
1588 if (!matchingInlineAsm)
1589 while (processInstruction(Inst, Operands))
1593 if (!matchingInlineAsm)
1594 Out.EmitInstruction(Inst);
1595 Opcode = Inst.getOpcode();
1597 case Match_MissingFeature:
1598 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1599 EmptyRanges, matchingInlineAsm);
1601 case Match_InvalidOperand:
1602 WasOriginallyInvalidOperand = true;
1604 case Match_MnemonicFail:
1608 // FIXME: Ideally, we would only attempt suffix matches for things which are
1609 // valid prefixes, and we could just infer the right unambiguous
1610 // type. However, that requires substantially more matcher support than the
1613 // Change the operand to point to a temporary token.
1614 StringRef Base = Op->getToken();
1615 SmallString<16> Tmp;
1618 Op->setTokenValue(Tmp.str());
1620 // If this instruction starts with an 'f', then it is a floating point stack
1621 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1622 // 80-bit floating point, which use the suffixes s,l,t respectively.
1624 // Otherwise, we assume that this may be an integer instruction, which comes
1625 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1626 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1628 // Check for the various suffix matches.
1629 Tmp[Base.size()] = Suffixes[0];
1630 unsigned ErrorInfoIgnore;
1631 unsigned Match1, Match2, Match3, Match4;
1634 MatchInstMapAndConstraints tMapAndConstraints[4];
1635 Match1 = MatchInstructionImpl(Operands, tKind, Inst, tMapAndConstraints[0],
1636 ErrorInfoIgnore, isParsingIntelSyntax());
1637 if (Match1 == Match_Success) Kind = tKind;
1638 Tmp[Base.size()] = Suffixes[1];
1639 Match2 = MatchInstructionImpl(Operands, tKind, Inst, tMapAndConstraints[1],
1640 ErrorInfoIgnore, isParsingIntelSyntax());
1641 if (Match2 == Match_Success) Kind = tKind;
1642 Tmp[Base.size()] = Suffixes[2];
1643 Match3 = MatchInstructionImpl(Operands, tKind, Inst, tMapAndConstraints[2],
1644 ErrorInfoIgnore, isParsingIntelSyntax());
1645 if (Match3 == Match_Success) Kind = tKind;
1646 Tmp[Base.size()] = Suffixes[3];
1647 Match4 = MatchInstructionImpl(Operands, tKind, Inst, tMapAndConstraints[3],
1648 ErrorInfoIgnore, isParsingIntelSyntax());
1649 if (Match4 == Match_Success) Kind = tKind;
1651 // Restore the old token.
1652 Op->setTokenValue(Base);
1654 // If exactly one matched, then we treat that as a successful match (and the
1655 // instruction will already have been filled in correctly, since the failing
1656 // matches won't have modified it).
1657 unsigned NumSuccessfulMatches =
1658 (Match1 == Match_Success) + (Match2 == Match_Success) +
1659 (Match3 == Match_Success) + (Match4 == Match_Success);
1660 if (NumSuccessfulMatches == 1) {
1662 if (!matchingInlineAsm)
1663 Out.EmitInstruction(Inst);
1664 Opcode = Inst.getOpcode();
1665 // FIXME: Handle the map and constraints.
1669 // Otherwise, the match failed, try to produce a decent error message.
1671 // If we had multiple suffix matches, then identify this as an ambiguous
1673 if (NumSuccessfulMatches > 1) {
1675 unsigned NumMatches = 0;
1676 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1677 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1678 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1679 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1681 SmallString<126> Msg;
1682 raw_svector_ostream OS(Msg);
1683 OS << "ambiguous instructions require an explicit suffix (could be ";
1684 for (unsigned i = 0; i != NumMatches; ++i) {
1687 if (i + 1 == NumMatches)
1689 OS << "'" << Base << MatchChars[i] << "'";
1692 Error(IDLoc, OS.str(), EmptyRanges, matchingInlineAsm);
1696 // Okay, we know that none of the variants matched successfully.
1698 // If all of the instructions reported an invalid mnemonic, then the original
1699 // mnemonic was invalid.
1700 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1701 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1702 if (!WasOriginallyInvalidOperand) {
1703 ArrayRef<SMRange> Ranges = matchingInlineAsm ? EmptyRanges :
1705 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1706 Ranges, matchingInlineAsm);
1709 // Recover location info for the operand if we know which was the problem.
1710 if (OrigErrorInfo != ~0U) {
1711 if (OrigErrorInfo >= Operands.size())
1712 return Error(IDLoc, "too few operands for instruction",
1713 EmptyRanges, matchingInlineAsm);
1715 X86Operand *Operand = (X86Operand*)Operands[OrigErrorInfo];
1716 if (Operand->getStartLoc().isValid()) {
1717 SMRange OperandRange = Operand->getLocRange();
1718 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1719 OperandRange, matchingInlineAsm);
1723 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1727 // If one instruction matched with a missing feature, report this as a
1729 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1730 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1731 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1732 EmptyRanges, matchingInlineAsm);
1736 // If one instruction matched with an invalid operand, report this as an
1738 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1739 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1740 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1745 // If all of these were an outright failure, report it in a useless way.
1746 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
1747 EmptyRanges, matchingInlineAsm);
1752 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1753 StringRef IDVal = DirectiveID.getIdentifier();
1754 if (IDVal == ".word")
1755 return ParseDirectiveWord(2, DirectiveID.getLoc());
1756 else if (IDVal.startswith(".code"))
1757 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1758 else if (IDVal.startswith(".att_syntax")) {
1759 getParser().setAssemblerDialect(0);
1761 } else if (IDVal.startswith(".intel_syntax")) {
1762 getParser().setAssemblerDialect(1);
1763 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1764 if(Parser.getTok().getString() == "noprefix") {
1765 // FIXME : Handle noprefix
1775 /// ParseDirectiveWord
1776 /// ::= .word [ expression (, expression)* ]
1777 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1778 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1780 const MCExpr *Value;
1781 if (getParser().ParseExpression(Value))
1784 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1786 if (getLexer().is(AsmToken::EndOfStatement))
1789 // FIXME: Improve diagnostic.
1790 if (getLexer().isNot(AsmToken::Comma))
1791 return Error(L, "unexpected token in directive");
1800 /// ParseDirectiveCode
1801 /// ::= .code32 | .code64
1802 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1803 if (IDVal == ".code32") {
1805 if (is64BitMode()) {
1807 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1809 } else if (IDVal == ".code64") {
1811 if (!is64BitMode()) {
1813 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1816 return Error(L, "unexpected directive " + IDVal);
1823 extern "C" void LLVMInitializeX86AsmLexer();
1825 // Force static initialization.
1826 extern "C" void LLVMInitializeX86AsmParser() {
1827 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1828 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1829 LLVMInitializeX86AsmLexer();
1832 #define GET_REGISTER_MATCHER
1833 #define GET_MATCHER_IMPLEMENTATION
1834 #include "X86GenAsmMatcher.inc"