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/MCSymbol.h"
15 #include "llvm/MC/MCInst.h"
16 #include "llvm/MC/MCRegisterInfo.h"
17 #include "llvm/MC/MCSubtargetInfo.h"
18 #include "llvm/MC/MCParser/MCAsmLexer.h"
19 #include "llvm/MC/MCParser/MCAsmParser.h"
20 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
21 #include "llvm/ADT/APFloat.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/TargetRegistry.h"
28 #include "llvm/Support/raw_ostream.h"
35 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 bool MatchingInlineAsm = false) {
46 if (MatchingInlineAsm) return true;
47 return Parser.Error(L, Msg, Ranges);
50 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
55 X86Operand *ParseOperand();
56 X86Operand *ParseATTOperand();
57 X86Operand *ParseIntelOperand();
58 X86Operand *ParseIntelOffsetOfOperator(SMLoc StartLoc);
59 X86Operand *ParseIntelMemOperand(unsigned SegReg, SMLoc StartLoc);
60 X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
61 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
63 bool ParseIntelDotOperator(const MCExpr *Disp, const MCExpr **NewDisp,
64 SmallString<64> &Err);
66 bool ParseDirectiveWord(unsigned Size, SMLoc L);
67 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
69 bool processInstruction(MCInst &Inst,
70 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
72 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
73 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
74 MCStreamer &Out, unsigned &ErrorInfo,
75 bool MatchingInlineAsm);
77 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
78 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
79 bool isSrcOp(X86Operand &Op);
81 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
82 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
83 bool isDstOp(X86Operand &Op);
85 bool is64BitMode() const {
86 // FIXME: Can tablegen auto-generate this?
87 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
90 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
91 setAvailableFeatures(FB);
94 /// @name Auto-generated Matcher Functions
97 #define GET_ASSEMBLER_HEADER
98 #include "X86GenAsmMatcher.inc"
103 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
104 : MCTargetAsmParser(), STI(sti), Parser(parser) {
106 // Initialize the set of available features.
107 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
109 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
111 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
112 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
114 virtual bool ParseDirective(AsmToken DirectiveID);
116 bool isParsingIntelSyntax() {
117 return getParser().getAssemblerDialect();
120 } // end anonymous namespace
122 /// @name Auto-generated Match Functions
125 static unsigned MatchRegisterName(StringRef Name);
129 static bool isImmSExti16i8Value(uint64_t Value) {
130 return (( Value <= 0x000000000000007FULL)||
131 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
132 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
135 static bool isImmSExti32i8Value(uint64_t Value) {
136 return (( Value <= 0x000000000000007FULL)||
137 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
138 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
141 static bool isImmZExtu32u8Value(uint64_t Value) {
142 return (Value <= 0x00000000000000FFULL);
145 static bool isImmSExti64i8Value(uint64_t Value) {
146 return (( Value <= 0x000000000000007FULL)||
147 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
150 static bool isImmSExti64i32Value(uint64_t Value) {
151 return (( Value <= 0x000000007FFFFFFFULL)||
152 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
156 /// X86Operand - Instances of this class represent a parsed X86 machine
158 struct X86Operand : public MCParsedAsmOperand {
166 SMLoc StartLoc, EndLoc;
194 X86Operand(KindTy K, SMLoc Start, SMLoc End)
195 : Kind(K), StartLoc(Start), EndLoc(End) {}
197 /// getStartLoc - Get the location of the first token of this operand.
198 SMLoc getStartLoc() const { return StartLoc; }
199 /// getEndLoc - Get the location of the last token of this operand.
200 SMLoc getEndLoc() const { return EndLoc; }
201 /// getLocRange - Get the range between the first and last token of this
203 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
204 /// getOffsetOfLoc - Get the location of the offset operator.
205 SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
207 virtual void print(raw_ostream &OS) const {}
209 StringRef getToken() const {
210 assert(Kind == Token && "Invalid access!");
211 return StringRef(Tok.Data, Tok.Length);
213 void setTokenValue(StringRef Value) {
214 assert(Kind == Token && "Invalid access!");
215 Tok.Data = Value.data();
216 Tok.Length = Value.size();
219 unsigned getReg() const {
220 assert(Kind == Register && "Invalid access!");
224 const MCExpr *getImm() const {
225 assert(Kind == Immediate && "Invalid access!");
229 const MCExpr *getMemDisp() const {
230 assert(Kind == Memory && "Invalid access!");
233 unsigned getMemSegReg() const {
234 assert(Kind == Memory && "Invalid access!");
237 unsigned getMemBaseReg() const {
238 assert(Kind == Memory && "Invalid access!");
241 unsigned getMemIndexReg() const {
242 assert(Kind == Memory && "Invalid access!");
245 unsigned getMemScale() const {
246 assert(Kind == Memory && "Invalid access!");
250 bool isToken() const {return Kind == Token; }
252 bool isImm() const { return Kind == Immediate; }
254 bool isImmSExti16i8() const {
258 // If this isn't a constant expr, just assume it fits and let relaxation
260 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
264 // Otherwise, check the value is in a range that makes sense for this
266 return isImmSExti16i8Value(CE->getValue());
268 bool isImmSExti32i8() const {
272 // If this isn't a constant expr, just assume it fits and let relaxation
274 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
278 // Otherwise, check the value is in a range that makes sense for this
280 return isImmSExti32i8Value(CE->getValue());
282 bool isImmZExtu32u8() const {
286 // If this isn't a constant expr, just assume it fits and let relaxation
288 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
292 // Otherwise, check the value is in a range that makes sense for this
294 return isImmZExtu32u8Value(CE->getValue());
296 bool isImmSExti64i8() const {
300 // If this isn't a constant expr, just assume it fits and let relaxation
302 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
306 // Otherwise, check the value is in a range that makes sense for this
308 return isImmSExti64i8Value(CE->getValue());
310 bool isImmSExti64i32() const {
314 // If this isn't a constant expr, just assume it fits and let relaxation
316 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
320 // Otherwise, check the value is in a range that makes sense for this
322 return isImmSExti64i32Value(CE->getValue());
325 unsigned getMemSize() const {
326 assert(Kind == Memory && "Invalid access!");
330 bool isOffsetOf() const {
331 return OffsetOfLoc.getPointer();
334 bool needSizeDirective() const {
335 assert(Kind == Memory && "Invalid access!");
336 return Mem.NeedSizeDir;
339 bool isMem() const { return Kind == Memory; }
340 bool isMem8() const {
341 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
343 bool isMem16() const {
344 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
346 bool isMem32() const {
347 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
349 bool isMem64() const {
350 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
352 bool isMem80() const {
353 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
355 bool isMem128() const {
356 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
358 bool isMem256() const {
359 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
362 bool isMemVX32() const {
363 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
364 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
366 bool isMemVY32() const {
367 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
368 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
370 bool isMemVX64() const {
371 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
372 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
374 bool isMemVY64() const {
375 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
376 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
379 bool isAbsMem() const {
380 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
381 !getMemIndexReg() && getMemScale() == 1;
384 bool isReg() const { return Kind == Register; }
386 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
387 // Add as immediates when possible.
388 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
389 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
391 Inst.addOperand(MCOperand::CreateExpr(Expr));
394 void addRegOperands(MCInst &Inst, unsigned N) const {
395 assert(N == 1 && "Invalid number of operands!");
396 Inst.addOperand(MCOperand::CreateReg(getReg()));
399 void addImmOperands(MCInst &Inst, unsigned N) const {
400 assert(N == 1 && "Invalid number of operands!");
401 addExpr(Inst, getImm());
404 void addMem8Operands(MCInst &Inst, unsigned N) const {
405 addMemOperands(Inst, N);
407 void addMem16Operands(MCInst &Inst, unsigned N) const {
408 addMemOperands(Inst, N);
410 void addMem32Operands(MCInst &Inst, unsigned N) const {
411 addMemOperands(Inst, N);
413 void addMem64Operands(MCInst &Inst, unsigned N) const {
414 addMemOperands(Inst, N);
416 void addMem80Operands(MCInst &Inst, unsigned N) const {
417 addMemOperands(Inst, N);
419 void addMem128Operands(MCInst &Inst, unsigned N) const {
420 addMemOperands(Inst, N);
422 void addMem256Operands(MCInst &Inst, unsigned N) const {
423 addMemOperands(Inst, N);
425 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
426 addMemOperands(Inst, N);
428 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
429 addMemOperands(Inst, N);
431 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
432 addMemOperands(Inst, N);
434 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
435 addMemOperands(Inst, N);
438 void addMemOperands(MCInst &Inst, unsigned N) const {
439 assert((N == 5) && "Invalid number of operands!");
440 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
441 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
442 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
443 addExpr(Inst, getMemDisp());
444 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
447 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
448 assert((N == 1) && "Invalid number of operands!");
449 // Add as immediates when possible.
450 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
451 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
453 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
456 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
457 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
458 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
459 Res->Tok.Data = Str.data();
460 Res->Tok.Length = Str.size();
464 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
465 SMLoc OffsetOfLoc = SMLoc()) {
466 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
467 Res->Reg.RegNo = RegNo;
468 Res->OffsetOfLoc = OffsetOfLoc;
472 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
473 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
478 /// Create an absolute memory operand.
479 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc,
480 unsigned Size = 0, bool NeedSizeDir = false){
481 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
483 Res->Mem.Disp = Disp;
484 Res->Mem.BaseReg = 0;
485 Res->Mem.IndexReg = 0;
487 Res->Mem.Size = Size;
488 Res->Mem.NeedSizeDir = NeedSizeDir;
492 /// Create a generalized memory operand.
493 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
494 unsigned BaseReg, unsigned IndexReg,
495 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
496 unsigned Size = 0, bool NeedSizeDir = false) {
497 // We should never just have a displacement, that should be parsed as an
498 // absolute memory operand.
499 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
501 // The scale should always be one of {1,2,4,8}.
502 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
504 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
505 Res->Mem.SegReg = SegReg;
506 Res->Mem.Disp = Disp;
507 Res->Mem.BaseReg = BaseReg;
508 Res->Mem.IndexReg = IndexReg;
509 Res->Mem.Scale = Scale;
510 Res->Mem.Size = Size;
511 Res->Mem.NeedSizeDir = NeedSizeDir;
516 } // end anonymous namespace.
518 bool X86AsmParser::isSrcOp(X86Operand &Op) {
519 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
521 return (Op.isMem() &&
522 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
523 isa<MCConstantExpr>(Op.Mem.Disp) &&
524 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
525 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
528 bool X86AsmParser::isDstOp(X86Operand &Op) {
529 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
532 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
533 isa<MCConstantExpr>(Op.Mem.Disp) &&
534 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
535 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
538 bool X86AsmParser::ParseRegister(unsigned &RegNo,
539 SMLoc &StartLoc, SMLoc &EndLoc) {
541 const AsmToken &PercentTok = Parser.getTok();
542 StartLoc = PercentTok.getLoc();
544 // If we encounter a %, ignore it. This code handles registers with and
545 // without the prefix, unprefixed registers can occur in cfi directives.
546 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
547 Parser.Lex(); // Eat percent token.
549 const AsmToken &Tok = Parser.getTok();
550 if (Tok.isNot(AsmToken::Identifier)) {
551 if (isParsingIntelSyntax()) return true;
552 return Error(StartLoc, "invalid register name",
553 SMRange(StartLoc, Tok.getEndLoc()));
556 RegNo = MatchRegisterName(Tok.getString());
558 // If the match failed, try the register name as lowercase.
560 RegNo = MatchRegisterName(Tok.getString().lower());
562 if (!is64BitMode()) {
563 // FIXME: This should be done using Requires<In32BitMode> and
564 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
566 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
568 if (RegNo == X86::RIZ ||
569 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
570 X86II::isX86_64NonExtLowByteReg(RegNo) ||
571 X86II::isX86_64ExtendedReg(RegNo))
572 return Error(StartLoc, "register %"
573 + Tok.getString() + " is only available in 64-bit mode",
574 SMRange(StartLoc, Tok.getEndLoc()));
577 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
578 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
580 EndLoc = Tok.getLoc();
581 Parser.Lex(); // Eat 'st'
583 // Check to see if we have '(4)' after %st.
584 if (getLexer().isNot(AsmToken::LParen))
589 const AsmToken &IntTok = Parser.getTok();
590 if (IntTok.isNot(AsmToken::Integer))
591 return Error(IntTok.getLoc(), "expected stack index");
592 switch (IntTok.getIntVal()) {
593 case 0: RegNo = X86::ST0; break;
594 case 1: RegNo = X86::ST1; break;
595 case 2: RegNo = X86::ST2; break;
596 case 3: RegNo = X86::ST3; break;
597 case 4: RegNo = X86::ST4; break;
598 case 5: RegNo = X86::ST5; break;
599 case 6: RegNo = X86::ST6; break;
600 case 7: RegNo = X86::ST7; break;
601 default: return Error(IntTok.getLoc(), "invalid stack index");
604 if (getParser().Lex().isNot(AsmToken::RParen))
605 return Error(Parser.getTok().getLoc(), "expected ')'");
607 EndLoc = Tok.getLoc();
608 Parser.Lex(); // Eat ')'
612 // If this is "db[0-7]", match it as an alias
614 if (RegNo == 0 && Tok.getString().size() == 3 &&
615 Tok.getString().startswith("db")) {
616 switch (Tok.getString()[2]) {
617 case '0': RegNo = X86::DR0; break;
618 case '1': RegNo = X86::DR1; break;
619 case '2': RegNo = X86::DR2; break;
620 case '3': RegNo = X86::DR3; break;
621 case '4': RegNo = X86::DR4; break;
622 case '5': RegNo = X86::DR5; break;
623 case '6': RegNo = X86::DR6; break;
624 case '7': RegNo = X86::DR7; break;
628 EndLoc = Tok.getLoc();
629 Parser.Lex(); // Eat it.
635 if (isParsingIntelSyntax()) return true;
636 return Error(StartLoc, "invalid register name",
637 SMRange(StartLoc, Tok.getEndLoc()));
640 EndLoc = Tok.getEndLoc();
641 Parser.Lex(); // Eat identifier token.
645 X86Operand *X86AsmParser::ParseOperand() {
646 if (isParsingIntelSyntax())
647 return ParseIntelOperand();
648 return ParseATTOperand();
651 /// getIntelMemOperandSize - Return intel memory operand size.
652 static unsigned getIntelMemOperandSize(StringRef OpStr) {
653 unsigned Size = StringSwitch<unsigned>(OpStr)
654 .Cases("BYTE", "byte", 8)
655 .Cases("WORD", "word", 16)
656 .Cases("DWORD", "dword", 32)
657 .Cases("QWORD", "qword", 64)
658 .Cases("XWORD", "xword", 80)
659 .Cases("XMMWORD", "xmmword", 128)
660 .Cases("YMMWORD", "ymmword", 256)
665 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
667 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
668 const AsmToken &Tok = Parser.getTok();
669 SMLoc Start = Tok.getLoc(), End;
671 const MCExpr *Disp = MCConstantExpr::Create(0, getContext());
672 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
675 if (getLexer().isNot(AsmToken::LBrac))
676 return ErrorOperand(Start, "Expected '[' token!");
679 if (getLexer().is(AsmToken::Identifier)) {
681 if (ParseRegister(BaseReg, Start, End)) {
682 // Handle '[' 'symbol' ']'
683 if (getParser().ParseExpression(Disp, End)) return 0;
684 if (getLexer().isNot(AsmToken::RBrac))
685 return ErrorOperand(Start, "Expected ']' token!");
687 return X86Operand::CreateMem(Disp, Start, End, Size);
689 } else if (getLexer().is(AsmToken::Integer)) {
690 int64_t Val = Tok.getIntVal();
692 SMLoc Loc = Tok.getLoc();
693 if (getLexer().is(AsmToken::RBrac)) {
694 // Handle '[' number ']'
696 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
698 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
700 return X86Operand::CreateMem(Disp, Start, End, Size);
701 } else if (getLexer().is(AsmToken::Star)) {
702 // Handle '[' Scale*IndexReg ']'
704 SMLoc IdxRegLoc = Tok.getLoc();
705 if (ParseRegister(IndexReg, IdxRegLoc, End))
706 return ErrorOperand(IdxRegLoc, "Expected register");
709 return ErrorOperand(Loc, "Unexpected token");
712 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
713 bool isPlus = getLexer().is(AsmToken::Plus);
715 SMLoc PlusLoc = Tok.getLoc();
716 if (getLexer().is(AsmToken::Integer)) {
717 int64_t Val = Tok.getIntVal();
719 if (getLexer().is(AsmToken::Star)) {
721 SMLoc IdxRegLoc = Tok.getLoc();
722 if (ParseRegister(IndexReg, IdxRegLoc, End))
723 return ErrorOperand(IdxRegLoc, "Expected register");
725 } else if (getLexer().is(AsmToken::RBrac)) {
726 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
727 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
729 return ErrorOperand(PlusLoc, "unexpected token after +");
730 } else if (getLexer().is(AsmToken::Identifier)) {
731 // This could be an index register or a displacement expression.
734 ParseRegister(IndexReg, Start, End);
735 else if (getParser().ParseExpression(Disp, End)) return 0;
739 if (getLexer().isNot(AsmToken::RBrac))
740 if (getParser().ParseExpression(Disp, End)) return 0;
743 if (getLexer().isNot(AsmToken::RBrac))
744 return ErrorOperand(End, "expected ']' token!");
748 if (Tok.getString().startswith(".")) {
750 const MCExpr *NewDisp;
751 if (ParseIntelDotOperator(Disp, &NewDisp, Err))
752 return ErrorOperand(Tok.getLoc(), Err);
754 Parser.Lex(); // Eat the field.
761 if (!BaseReg && !IndexReg)
762 return X86Operand::CreateMem(Disp, Start, End, Size);
764 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
768 /// ParseIntelMemOperand - Parse intel style memory operand.
769 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg, SMLoc Start) {
770 const AsmToken &Tok = Parser.getTok();
773 unsigned Size = getIntelMemOperandSize(Tok.getString());
776 assert ((Tok.getString() == "PTR" || Tok.getString() == "ptr") &&
777 "Unexpected token!");
781 if (getLexer().is(AsmToken::LBrac))
782 return ParseIntelBracExpression(SegReg, Size);
784 if (!ParseRegister(SegReg, Start, End)) {
785 // Handel SegReg : [ ... ]
786 if (getLexer().isNot(AsmToken::Colon))
787 return ErrorOperand(Start, "Expected ':' token!");
788 Parser.Lex(); // Eat :
789 if (getLexer().isNot(AsmToken::LBrac))
790 return ErrorOperand(Start, "Expected '[' token!");
791 return ParseIntelBracExpression(SegReg, Size);
794 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
795 if (getParser().ParseExpression(Disp, End)) return 0;
796 End = Parser.getTok().getLoc();
798 bool NeedSizeDir = false;
799 if (!Size && isParsingInlineAsm()) {
800 if (const MCSymbolRefExpr *SymRef = dyn_cast<MCSymbolRefExpr>(Disp)) {
801 const MCSymbol &Sym = SymRef->getSymbol();
802 // FIXME: The SemaLookup will fail if the name is anything other then an
804 // FIXME: Pass a valid SMLoc.
805 SemaCallback->LookupInlineAsmIdentifier(Sym.getName(), NULL, Size);
806 NeedSizeDir = Size > 0;
809 if (!isParsingInlineAsm())
810 return X86Operand::CreateMem(Disp, Start, End, Size);
812 // When parsing inline assembly we set the base register to a non-zero value
813 // as we don't know the actual value at this time. This is necessary to
814 // get the matching correct in some cases.
815 return X86Operand::CreateMem(/*SegReg*/0, Disp, /*BaseReg*/1, /*IndexReg*/0,
816 /*Scale*/1, Start, End, Size, NeedSizeDir);
819 /// Parse the '.' operator.
820 bool X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp,
821 const MCExpr **NewDisp,
822 SmallString<64> &Err) {
823 AsmToken Tok = *&Parser.getTok();
824 uint64_t OrigDispVal, DotDispVal;
826 // FIXME: Handle non-constant expressions.
827 if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp)) {
828 OrigDispVal = OrigDisp->getValue();
830 Err = "Non-constant offsets are not supported!";
835 StringRef DotDispStr = Tok.getString().drop_front(1);
837 // .Imm gets lexed as a real.
838 if (Tok.is(AsmToken::Real)) {
840 DotDispStr.getAsInteger(10, DotDisp);
841 DotDispVal = DotDisp.getZExtValue();
843 Err = "Unexpected token type!";
847 // Special case zero dot displacement.
853 *NewDisp = MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext());
857 /// Parse the 'offset' operator. This operator is used to specify the
858 /// location rather then the content of a variable.
859 X86Operand *X86AsmParser::ParseIntelOffsetOfOperator(SMLoc Start) {
860 SMLoc OffsetOfLoc = Start;
861 Parser.Lex(); // Eat offset.
862 Start = Parser.getTok().getLoc();
863 assert (Parser.getTok().is(AsmToken::Identifier) && "Expected an identifier");
867 if (getParser().ParseExpression(Val, End))
870 End = Parser.getTok().getLoc();
872 // The offset operator will have an 'r' constraint, thus we need to create
873 // register operand to ensure proper matching. Just pick a GPR based on
874 // the size of a pointer.
875 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
876 return X86Operand::CreateReg(RegNo, Start, End, OffsetOfLoc);
879 X86Operand *X86AsmParser::ParseIntelOperand() {
880 SMLoc Start = Parser.getTok().getLoc(), End;
883 const AsmToken &Tok = Parser.getTok();
884 if ((Tok.getString() == "offset" || Tok.getString() == "OFFSET") &&
885 isParsingInlineAsm())
886 return ParseIntelOffsetOfOperator(Start);
889 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
890 getLexer().is(AsmToken::Minus)) {
892 if (!getParser().ParseExpression(Val, End)) {
893 End = Parser.getTok().getLoc();
894 return X86Operand::CreateImm(Val, Start, End);
900 if (!ParseRegister(RegNo, Start, End)) {
901 // If this is a segment register followed by a ':', then this is the start
902 // of a memory reference, otherwise this is a normal register reference.
903 if (getLexer().isNot(AsmToken::Colon))
904 return X86Operand::CreateReg(RegNo, Start, Parser.getTok().getLoc());
906 getParser().Lex(); // Eat the colon.
907 return ParseIntelMemOperand(RegNo, Start);
911 return ParseIntelMemOperand(0, Start);
914 X86Operand *X86AsmParser::ParseATTOperand() {
915 switch (getLexer().getKind()) {
917 // Parse a memory operand with no segment register.
918 return ParseMemOperand(0, Parser.getTok().getLoc());
919 case AsmToken::Percent: {
920 // Read the register.
923 if (ParseRegister(RegNo, Start, End)) return 0;
924 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
925 Error(Start, "%eiz and %riz can only be used as index registers",
926 SMRange(Start, End));
930 // If this is a segment register followed by a ':', then this is the start
931 // of a memory reference, otherwise this is a normal register reference.
932 if (getLexer().isNot(AsmToken::Colon))
933 return X86Operand::CreateReg(RegNo, Start, End);
936 getParser().Lex(); // Eat the colon.
937 return ParseMemOperand(RegNo, Start);
939 case AsmToken::Dollar: {
941 SMLoc Start = Parser.getTok().getLoc(), End;
944 if (getParser().ParseExpression(Val, End))
946 return X86Operand::CreateImm(Val, Start, End);
951 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
952 /// has already been parsed if present.
953 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
955 // We have to disambiguate a parenthesized expression "(4+5)" from the start
956 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
957 // only way to do this without lookahead is to eat the '(' and see what is
959 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
960 if (getLexer().isNot(AsmToken::LParen)) {
962 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
964 // After parsing the base expression we could either have a parenthesized
965 // memory address or not. If not, return now. If so, eat the (.
966 if (getLexer().isNot(AsmToken::LParen)) {
967 // Unless we have a segment register, treat this as an immediate.
969 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
970 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
976 // Okay, we have a '('. We don't know if this is an expression or not, but
977 // so we have to eat the ( to see beyond it.
978 SMLoc LParenLoc = Parser.getTok().getLoc();
979 Parser.Lex(); // Eat the '('.
981 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
982 // Nothing to do here, fall into the code below with the '(' part of the
983 // memory operand consumed.
987 // It must be an parenthesized expression, parse it now.
988 if (getParser().ParseParenExpression(Disp, ExprEnd))
991 // After parsing the base expression we could either have a parenthesized
992 // memory address or not. If not, return now. If so, eat the (.
993 if (getLexer().isNot(AsmToken::LParen)) {
994 // Unless we have a segment register, treat this as an immediate.
996 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
997 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1005 // If we reached here, then we just ate the ( of the memory operand. Process
1006 // the rest of the memory operand.
1007 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
1010 if (getLexer().is(AsmToken::Percent)) {
1011 SMLoc StartLoc, EndLoc;
1012 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
1013 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
1014 Error(StartLoc, "eiz and riz can only be used as index registers",
1015 SMRange(StartLoc, EndLoc));
1020 if (getLexer().is(AsmToken::Comma)) {
1021 Parser.Lex(); // Eat the comma.
1022 IndexLoc = Parser.getTok().getLoc();
1024 // Following the comma we should have either an index register, or a scale
1025 // value. We don't support the later form, but we want to parse it
1028 // Not that even though it would be completely consistent to support syntax
1029 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
1030 if (getLexer().is(AsmToken::Percent)) {
1032 if (ParseRegister(IndexReg, L, L)) return 0;
1034 if (getLexer().isNot(AsmToken::RParen)) {
1035 // Parse the scale amount:
1036 // ::= ',' [scale-expression]
1037 if (getLexer().isNot(AsmToken::Comma)) {
1038 Error(Parser.getTok().getLoc(),
1039 "expected comma in scale expression");
1042 Parser.Lex(); // Eat the comma.
1044 if (getLexer().isNot(AsmToken::RParen)) {
1045 SMLoc Loc = Parser.getTok().getLoc();
1048 if (getParser().ParseAbsoluteExpression(ScaleVal)){
1049 Error(Loc, "expected scale expression");
1053 // Validate the scale amount.
1054 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
1055 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
1058 Scale = (unsigned)ScaleVal;
1061 } else if (getLexer().isNot(AsmToken::RParen)) {
1062 // A scale amount without an index is ignored.
1064 SMLoc Loc = Parser.getTok().getLoc();
1067 if (getParser().ParseAbsoluteExpression(Value))
1071 Warning(Loc, "scale factor without index register is ignored");
1076 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1077 if (getLexer().isNot(AsmToken::RParen)) {
1078 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1081 SMLoc MemEnd = Parser.getTok().getLoc();
1082 Parser.Lex(); // Eat the ')'.
1084 // If we have both a base register and an index register make sure they are
1085 // both 64-bit or 32-bit registers.
1086 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1087 if (BaseReg != 0 && IndexReg != 0) {
1088 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1089 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1090 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1091 IndexReg != X86::RIZ) {
1092 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1095 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1096 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1097 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1098 IndexReg != X86::EIZ){
1099 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1104 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1109 ParseInstruction(StringRef Name, SMLoc NameLoc,
1110 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1111 StringRef PatchedName = Name;
1113 // FIXME: Hack to recognize setneb as setne.
1114 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1115 PatchedName != "setb" && PatchedName != "setnb")
1116 PatchedName = PatchedName.substr(0, Name.size()-1);
1118 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1119 const MCExpr *ExtraImmOp = 0;
1120 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1121 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1122 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1123 bool IsVCMP = PatchedName[0] == 'v';
1124 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1125 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1126 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1130 .Case("unord", 0x03)
1135 /* AVX only from here */
1136 .Case("eq_uq", 0x08)
1139 .Case("false", 0x0B)
1140 .Case("neq_oq", 0x0C)
1144 .Case("eq_os", 0x10)
1145 .Case("lt_oq", 0x11)
1146 .Case("le_oq", 0x12)
1147 .Case("unord_s", 0x13)
1148 .Case("neq_us", 0x14)
1149 .Case("nlt_uq", 0x15)
1150 .Case("nle_uq", 0x16)
1151 .Case("ord_s", 0x17)
1152 .Case("eq_us", 0x18)
1153 .Case("nge_uq", 0x19)
1154 .Case("ngt_uq", 0x1A)
1155 .Case("false_os", 0x1B)
1156 .Case("neq_os", 0x1C)
1157 .Case("ge_oq", 0x1D)
1158 .Case("gt_oq", 0x1E)
1159 .Case("true_us", 0x1F)
1161 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1162 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1163 getParser().getContext());
1164 if (PatchedName.endswith("ss")) {
1165 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1166 } else if (PatchedName.endswith("sd")) {
1167 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1168 } else if (PatchedName.endswith("ps")) {
1169 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1171 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1172 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1177 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1179 if (ExtraImmOp && !isParsingIntelSyntax())
1180 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1182 // Determine whether this is an instruction prefix.
1184 Name == "lock" || Name == "rep" ||
1185 Name == "repe" || Name == "repz" ||
1186 Name == "repne" || Name == "repnz" ||
1187 Name == "rex64" || Name == "data16";
1190 // This does the actual operand parsing. Don't parse any more if we have a
1191 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1192 // just want to parse the "lock" as the first instruction and the "incl" as
1194 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1196 // Parse '*' modifier.
1197 if (getLexer().is(AsmToken::Star)) {
1198 SMLoc Loc = Parser.getTok().getLoc();
1199 Operands.push_back(X86Operand::CreateToken("*", Loc));
1200 Parser.Lex(); // Eat the star.
1203 // Read the first operand.
1204 if (X86Operand *Op = ParseOperand())
1205 Operands.push_back(Op);
1207 Parser.EatToEndOfStatement();
1211 while (getLexer().is(AsmToken::Comma)) {
1212 Parser.Lex(); // Eat the comma.
1214 // Parse and remember the operand.
1215 if (X86Operand *Op = ParseOperand())
1216 Operands.push_back(Op);
1218 Parser.EatToEndOfStatement();
1223 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1224 SMLoc Loc = getLexer().getLoc();
1225 Parser.EatToEndOfStatement();
1226 return Error(Loc, "unexpected token in argument list");
1230 if (getLexer().is(AsmToken::EndOfStatement))
1231 Parser.Lex(); // Consume the EndOfStatement
1232 else if (isPrefix && getLexer().is(AsmToken::Slash))
1233 Parser.Lex(); // Consume the prefix separator Slash
1235 if (ExtraImmOp && isParsingIntelSyntax())
1236 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1238 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1239 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1240 // documented form in various unofficial manuals, so a lot of code uses it.
1241 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1242 Operands.size() == 3) {
1243 X86Operand &Op = *(X86Operand*)Operands.back();
1244 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1245 isa<MCConstantExpr>(Op.Mem.Disp) &&
1246 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1247 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1248 SMLoc Loc = Op.getEndLoc();
1249 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1253 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1254 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1255 Operands.size() == 3) {
1256 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1257 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1258 isa<MCConstantExpr>(Op.Mem.Disp) &&
1259 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1260 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1261 SMLoc Loc = Op.getEndLoc();
1262 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1266 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1267 if (Name.startswith("ins") && Operands.size() == 3 &&
1268 (Name == "insb" || Name == "insw" || Name == "insl")) {
1269 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1270 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1271 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1272 Operands.pop_back();
1273 Operands.pop_back();
1279 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1280 if (Name.startswith("outs") && Operands.size() == 3 &&
1281 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1282 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1283 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1284 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1285 Operands.pop_back();
1286 Operands.pop_back();
1292 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1293 if (Name.startswith("movs") && Operands.size() == 3 &&
1294 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1295 (is64BitMode() && Name == "movsq"))) {
1296 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1297 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1298 if (isSrcOp(Op) && isDstOp(Op2)) {
1299 Operands.pop_back();
1300 Operands.pop_back();
1305 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1306 if (Name.startswith("lods") && Operands.size() == 3 &&
1307 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1308 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1309 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1310 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1311 if (isSrcOp(*Op1) && Op2->isReg()) {
1313 unsigned reg = Op2->getReg();
1314 bool isLods = Name == "lods";
1315 if (reg == X86::AL && (isLods || Name == "lodsb"))
1317 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1319 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1321 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1326 Operands.pop_back();
1327 Operands.pop_back();
1331 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1335 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1336 if (Name.startswith("stos") && Operands.size() == 3 &&
1337 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1338 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1339 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1340 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1341 if (isDstOp(*Op2) && Op1->isReg()) {
1343 unsigned reg = Op1->getReg();
1344 bool isStos = Name == "stos";
1345 if (reg == X86::AL && (isStos || Name == "stosb"))
1347 else if (reg == X86::AX && (isStos || Name == "stosw"))
1349 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1351 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1356 Operands.pop_back();
1357 Operands.pop_back();
1361 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1366 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1368 if ((Name.startswith("shr") || Name.startswith("sar") ||
1369 Name.startswith("shl") || Name.startswith("sal") ||
1370 Name.startswith("rcl") || Name.startswith("rcr") ||
1371 Name.startswith("rol") || Name.startswith("ror")) &&
1372 Operands.size() == 3) {
1373 if (isParsingIntelSyntax()) {
1375 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1376 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1377 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1379 Operands.pop_back();
1382 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1383 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1384 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1386 Operands.erase(Operands.begin() + 1);
1391 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1392 // instalias with an immediate operand yet.
1393 if (Name == "int" && Operands.size() == 2) {
1394 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1395 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1396 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1398 Operands.erase(Operands.begin() + 1);
1399 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1407 processInstruction(MCInst &Inst,
1408 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1409 switch (Inst.getOpcode()) {
1410 default: return false;
1411 case X86::AND16i16: {
1412 if (!Inst.getOperand(0).isImm() ||
1413 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1417 TmpInst.setOpcode(X86::AND16ri8);
1418 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1419 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1420 TmpInst.addOperand(Inst.getOperand(0));
1424 case X86::AND32i32: {
1425 if (!Inst.getOperand(0).isImm() ||
1426 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1430 TmpInst.setOpcode(X86::AND32ri8);
1431 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1432 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1433 TmpInst.addOperand(Inst.getOperand(0));
1437 case X86::AND64i32: {
1438 if (!Inst.getOperand(0).isImm() ||
1439 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1443 TmpInst.setOpcode(X86::AND64ri8);
1444 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1445 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1446 TmpInst.addOperand(Inst.getOperand(0));
1450 case X86::XOR16i16: {
1451 if (!Inst.getOperand(0).isImm() ||
1452 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1456 TmpInst.setOpcode(X86::XOR16ri8);
1457 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1458 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1459 TmpInst.addOperand(Inst.getOperand(0));
1463 case X86::XOR32i32: {
1464 if (!Inst.getOperand(0).isImm() ||
1465 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1469 TmpInst.setOpcode(X86::XOR32ri8);
1470 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1471 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1472 TmpInst.addOperand(Inst.getOperand(0));
1476 case X86::XOR64i32: {
1477 if (!Inst.getOperand(0).isImm() ||
1478 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1482 TmpInst.setOpcode(X86::XOR64ri8);
1483 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1484 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1485 TmpInst.addOperand(Inst.getOperand(0));
1489 case X86::OR16i16: {
1490 if (!Inst.getOperand(0).isImm() ||
1491 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1495 TmpInst.setOpcode(X86::OR16ri8);
1496 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1497 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1498 TmpInst.addOperand(Inst.getOperand(0));
1502 case X86::OR32i32: {
1503 if (!Inst.getOperand(0).isImm() ||
1504 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1508 TmpInst.setOpcode(X86::OR32ri8);
1509 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1510 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1511 TmpInst.addOperand(Inst.getOperand(0));
1515 case X86::OR64i32: {
1516 if (!Inst.getOperand(0).isImm() ||
1517 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1521 TmpInst.setOpcode(X86::OR64ri8);
1522 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1523 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1524 TmpInst.addOperand(Inst.getOperand(0));
1528 case X86::CMP16i16: {
1529 if (!Inst.getOperand(0).isImm() ||
1530 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1534 TmpInst.setOpcode(X86::CMP16ri8);
1535 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1536 TmpInst.addOperand(Inst.getOperand(0));
1540 case X86::CMP32i32: {
1541 if (!Inst.getOperand(0).isImm() ||
1542 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1546 TmpInst.setOpcode(X86::CMP32ri8);
1547 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1548 TmpInst.addOperand(Inst.getOperand(0));
1552 case X86::CMP64i32: {
1553 if (!Inst.getOperand(0).isImm() ||
1554 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1558 TmpInst.setOpcode(X86::CMP64ri8);
1559 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1560 TmpInst.addOperand(Inst.getOperand(0));
1564 case X86::ADD16i16: {
1565 if (!Inst.getOperand(0).isImm() ||
1566 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1570 TmpInst.setOpcode(X86::ADD16ri8);
1571 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1572 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1573 TmpInst.addOperand(Inst.getOperand(0));
1577 case X86::ADD32i32: {
1578 if (!Inst.getOperand(0).isImm() ||
1579 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1583 TmpInst.setOpcode(X86::ADD32ri8);
1584 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1585 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1586 TmpInst.addOperand(Inst.getOperand(0));
1590 case X86::ADD64i32: {
1591 if (!Inst.getOperand(0).isImm() ||
1592 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1596 TmpInst.setOpcode(X86::ADD64ri8);
1597 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1598 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1599 TmpInst.addOperand(Inst.getOperand(0));
1603 case X86::SUB16i16: {
1604 if (!Inst.getOperand(0).isImm() ||
1605 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1609 TmpInst.setOpcode(X86::SUB16ri8);
1610 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1611 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1612 TmpInst.addOperand(Inst.getOperand(0));
1616 case X86::SUB32i32: {
1617 if (!Inst.getOperand(0).isImm() ||
1618 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1622 TmpInst.setOpcode(X86::SUB32ri8);
1623 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1624 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1625 TmpInst.addOperand(Inst.getOperand(0));
1629 case X86::SUB64i32: {
1630 if (!Inst.getOperand(0).isImm() ||
1631 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1635 TmpInst.setOpcode(X86::SUB64ri8);
1636 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1637 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1638 TmpInst.addOperand(Inst.getOperand(0));
1646 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1647 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1648 MCStreamer &Out, unsigned &ErrorInfo,
1649 bool MatchingInlineAsm) {
1650 assert(!Operands.empty() && "Unexpect empty operand list!");
1651 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1652 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1653 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
1655 // First, handle aliases that expand to multiple instructions.
1656 // FIXME: This should be replaced with a real .td file alias mechanism.
1657 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
1659 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1660 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1661 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1662 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1664 Inst.setOpcode(X86::WAIT);
1666 if (!MatchingInlineAsm)
1667 Out.EmitInstruction(Inst);
1670 StringSwitch<const char*>(Op->getToken())
1671 .Case("finit", "fninit")
1672 .Case("fsave", "fnsave")
1673 .Case("fstcw", "fnstcw")
1674 .Case("fstcww", "fnstcw")
1675 .Case("fstenv", "fnstenv")
1676 .Case("fstsw", "fnstsw")
1677 .Case("fstsww", "fnstsw")
1678 .Case("fclex", "fnclex")
1680 assert(Repl && "Unknown wait-prefixed instruction");
1682 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1685 bool WasOriginallyInvalidOperand = false;
1688 // First, try a direct match.
1689 switch (MatchInstructionImpl(Operands, Inst,
1690 ErrorInfo, MatchingInlineAsm,
1691 isParsingIntelSyntax())) {
1694 // Some instructions need post-processing to, for example, tweak which
1695 // encoding is selected. Loop on it while changes happen so the
1696 // individual transformations can chain off each other.
1697 if (!MatchingInlineAsm)
1698 while (processInstruction(Inst, Operands))
1702 if (!MatchingInlineAsm)
1703 Out.EmitInstruction(Inst);
1704 Opcode = Inst.getOpcode();
1706 case Match_MissingFeature:
1707 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1708 EmptyRanges, MatchingInlineAsm);
1710 case Match_InvalidOperand:
1711 WasOriginallyInvalidOperand = true;
1713 case Match_MnemonicFail:
1717 // FIXME: Ideally, we would only attempt suffix matches for things which are
1718 // valid prefixes, and we could just infer the right unambiguous
1719 // type. However, that requires substantially more matcher support than the
1722 // Change the operand to point to a temporary token.
1723 StringRef Base = Op->getToken();
1724 SmallString<16> Tmp;
1727 Op->setTokenValue(Tmp.str());
1729 // If this instruction starts with an 'f', then it is a floating point stack
1730 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1731 // 80-bit floating point, which use the suffixes s,l,t respectively.
1733 // Otherwise, we assume that this may be an integer instruction, which comes
1734 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1735 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1737 // Check for the various suffix matches.
1738 Tmp[Base.size()] = Suffixes[0];
1739 unsigned ErrorInfoIgnore;
1740 unsigned Match1, Match2, Match3, Match4;
1742 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1743 isParsingIntelSyntax());
1744 Tmp[Base.size()] = Suffixes[1];
1745 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1746 isParsingIntelSyntax());
1747 Tmp[Base.size()] = Suffixes[2];
1748 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1749 isParsingIntelSyntax());
1750 Tmp[Base.size()] = Suffixes[3];
1751 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1752 isParsingIntelSyntax());
1754 // Restore the old token.
1755 Op->setTokenValue(Base);
1757 // If exactly one matched, then we treat that as a successful match (and the
1758 // instruction will already have been filled in correctly, since the failing
1759 // matches won't have modified it).
1760 unsigned NumSuccessfulMatches =
1761 (Match1 == Match_Success) + (Match2 == Match_Success) +
1762 (Match3 == Match_Success) + (Match4 == Match_Success);
1763 if (NumSuccessfulMatches == 1) {
1765 if (!MatchingInlineAsm)
1766 Out.EmitInstruction(Inst);
1767 Opcode = Inst.getOpcode();
1771 // Otherwise, the match failed, try to produce a decent error message.
1773 // If we had multiple suffix matches, then identify this as an ambiguous
1775 if (NumSuccessfulMatches > 1) {
1777 unsigned NumMatches = 0;
1778 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1779 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1780 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1781 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1783 SmallString<126> Msg;
1784 raw_svector_ostream OS(Msg);
1785 OS << "ambiguous instructions require an explicit suffix (could be ";
1786 for (unsigned i = 0; i != NumMatches; ++i) {
1789 if (i + 1 == NumMatches)
1791 OS << "'" << Base << MatchChars[i] << "'";
1794 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
1798 // Okay, we know that none of the variants matched successfully.
1800 // If all of the instructions reported an invalid mnemonic, then the original
1801 // mnemonic was invalid.
1802 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1803 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1804 if (!WasOriginallyInvalidOperand) {
1805 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
1807 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1808 Ranges, MatchingInlineAsm);
1811 // Recover location info for the operand if we know which was the problem.
1812 if (ErrorInfo != ~0U) {
1813 if (ErrorInfo >= Operands.size())
1814 return Error(IDLoc, "too few operands for instruction",
1815 EmptyRanges, MatchingInlineAsm);
1817 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
1818 if (Operand->getStartLoc().isValid()) {
1819 SMRange OperandRange = Operand->getLocRange();
1820 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1821 OperandRange, MatchingInlineAsm);
1825 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1829 // If one instruction matched with a missing feature, report this as a
1831 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1832 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1833 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1834 EmptyRanges, MatchingInlineAsm);
1838 // If one instruction matched with an invalid operand, report this as an
1840 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1841 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1842 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1847 // If all of these were an outright failure, report it in a useless way.
1848 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
1849 EmptyRanges, MatchingInlineAsm);
1854 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1855 StringRef IDVal = DirectiveID.getIdentifier();
1856 if (IDVal == ".word")
1857 return ParseDirectiveWord(2, DirectiveID.getLoc());
1858 else if (IDVal.startswith(".code"))
1859 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1860 else if (IDVal.startswith(".att_syntax")) {
1861 getParser().setAssemblerDialect(0);
1863 } else if (IDVal.startswith(".intel_syntax")) {
1864 getParser().setAssemblerDialect(1);
1865 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1866 if(Parser.getTok().getString() == "noprefix") {
1867 // FIXME : Handle noprefix
1877 /// ParseDirectiveWord
1878 /// ::= .word [ expression (, expression)* ]
1879 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1880 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1882 const MCExpr *Value;
1883 if (getParser().ParseExpression(Value))
1886 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1888 if (getLexer().is(AsmToken::EndOfStatement))
1891 // FIXME: Improve diagnostic.
1892 if (getLexer().isNot(AsmToken::Comma))
1893 return Error(L, "unexpected token in directive");
1902 /// ParseDirectiveCode
1903 /// ::= .code32 | .code64
1904 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1905 if (IDVal == ".code32") {
1907 if (is64BitMode()) {
1909 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1911 } else if (IDVal == ".code64") {
1913 if (!is64BitMode()) {
1915 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1918 return Error(L, "unexpected directive " + IDVal);
1925 extern "C" void LLVMInitializeX86AsmLexer();
1927 // Force static initialization.
1928 extern "C" void LLVMInitializeX86AsmParser() {
1929 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1930 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1931 LLVMInitializeX86AsmLexer();
1934 #define GET_REGISTER_MATCHER
1935 #define GET_MATCHER_IMPLEMENTATION
1936 #include "X86GenAsmMatcher.inc"