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/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/TargetRegistry.h"
27 #include "llvm/Support/raw_ostream.h"
34 class X86AsmParser : public MCTargetAsmParser {
38 MCAsmParser &getParser() const { return Parser; }
40 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
42 bool Error(SMLoc L, const Twine &Msg,
43 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>(),
44 bool MatchingInlineAsm = false) {
45 if (MatchingInlineAsm) return true;
46 return Parser.Error(L, Msg, Ranges);
49 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
54 X86Operand *ParseOperand();
55 X86Operand *ParseATTOperand();
56 X86Operand *ParseIntelOperand();
57 X86Operand *ParseIntelMemOperand(unsigned SegReg, SMLoc StartLoc);
58 X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
59 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
61 bool ParseDirectiveWord(unsigned Size, SMLoc L);
62 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
64 bool processInstruction(MCInst &Inst,
65 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
67 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
68 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
69 MCStreamer &Out, unsigned &ErrorInfo,
70 bool MatchingInlineAsm);
72 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
73 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
74 bool isSrcOp(X86Operand &Op);
76 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
77 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
78 bool isDstOp(X86Operand &Op);
80 bool is64BitMode() const {
81 // FIXME: Can tablegen auto-generate this?
82 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
85 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
86 setAvailableFeatures(FB);
89 /// @name Auto-generated Matcher Functions
92 #define GET_ASSEMBLER_HEADER
93 #include "X86GenAsmMatcher.inc"
98 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
99 : MCTargetAsmParser(), STI(sti), Parser(parser) {
101 // Initialize the set of available features.
102 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
104 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
106 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
107 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
109 virtual bool ParseDirective(AsmToken DirectiveID);
111 bool isParsingIntelSyntax() {
112 return getParser().getAssemblerDialect();
115 } // end anonymous namespace
117 /// @name Auto-generated Match Functions
120 static unsigned MatchRegisterName(StringRef Name);
124 static bool isImmSExti16i8Value(uint64_t Value) {
125 return (( Value <= 0x000000000000007FULL)||
126 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
127 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
130 static bool isImmSExti32i8Value(uint64_t Value) {
131 return (( Value <= 0x000000000000007FULL)||
132 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
133 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
136 static bool isImmZExtu32u8Value(uint64_t Value) {
137 return (Value <= 0x00000000000000FFULL);
140 static bool isImmSExti64i8Value(uint64_t Value) {
141 return (( Value <= 0x000000000000007FULL)||
142 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
145 static bool isImmSExti64i32Value(uint64_t Value) {
146 return (( Value <= 0x000000007FFFFFFFULL)||
147 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
151 /// X86Operand - Instances of this class represent a parsed X86 machine
153 struct X86Operand : public MCParsedAsmOperand {
161 SMLoc StartLoc, EndLoc;
189 X86Operand(KindTy K, SMLoc Start, SMLoc End)
190 : Kind(K), StartLoc(Start), EndLoc(End) {}
192 /// getStartLoc - Get the location of the first token of this operand.
193 SMLoc getStartLoc() const { return StartLoc; }
194 /// getEndLoc - Get the location of the last token of this operand.
195 SMLoc getEndLoc() const { return EndLoc; }
196 /// getLocRange - Get the range between the first and last token of this
198 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
200 virtual void print(raw_ostream &OS) const {}
202 StringRef getToken() const {
203 assert(Kind == Token && "Invalid access!");
204 return StringRef(Tok.Data, Tok.Length);
206 void setTokenValue(StringRef Value) {
207 assert(Kind == Token && "Invalid access!");
208 Tok.Data = Value.data();
209 Tok.Length = Value.size();
212 unsigned getReg() const {
213 assert(Kind == Register && "Invalid access!");
217 const MCExpr *getImm() const {
218 assert(Kind == Immediate && "Invalid access!");
222 const MCExpr *getMemDisp() const {
223 assert(Kind == Memory && "Invalid access!");
226 unsigned getMemSegReg() const {
227 assert(Kind == Memory && "Invalid access!");
230 unsigned getMemBaseReg() const {
231 assert(Kind == Memory && "Invalid access!");
234 unsigned getMemIndexReg() const {
235 assert(Kind == Memory && "Invalid access!");
238 unsigned getMemScale() const {
239 assert(Kind == Memory && "Invalid access!");
243 bool isToken() const {return Kind == Token; }
245 bool isImm() const { return Kind == Immediate; }
247 bool isImmSExti16i8() const {
251 // If this isn't a constant expr, just assume it fits and let relaxation
253 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
257 // Otherwise, check the value is in a range that makes sense for this
259 return isImmSExti16i8Value(CE->getValue());
261 bool isImmSExti32i8() const {
265 // If this isn't a constant expr, just assume it fits and let relaxation
267 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
271 // Otherwise, check the value is in a range that makes sense for this
273 return isImmSExti32i8Value(CE->getValue());
275 bool isImmZExtu32u8() const {
279 // If this isn't a constant expr, just assume it fits and let relaxation
281 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
285 // Otherwise, check the value is in a range that makes sense for this
287 return isImmZExtu32u8Value(CE->getValue());
289 bool isImmSExti64i8() const {
293 // If this isn't a constant expr, just assume it fits and let relaxation
295 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
299 // Otherwise, check the value is in a range that makes sense for this
301 return isImmSExti64i8Value(CE->getValue());
303 bool isImmSExti64i32() const {
307 // If this isn't a constant expr, just assume it fits and let relaxation
309 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
313 // Otherwise, check the value is in a range that makes sense for this
315 return isImmSExti64i32Value(CE->getValue());
318 unsigned getMemSize() const {
319 assert(Kind == Memory && "Invalid access!");
323 bool needSizeDirective() const {
324 assert(Kind == Memory && "Invalid access!");
325 return Mem.NeedSizeDir;
328 bool isMem() const { return Kind == Memory; }
329 bool isMem8() const {
330 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
332 bool isMem16() const {
333 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
335 bool isMem32() const {
336 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
338 bool isMem64() const {
339 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
341 bool isMem80() const {
342 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
344 bool isMem128() const {
345 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
347 bool isMem256() const {
348 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
351 bool isMemVX32() const {
352 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
353 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
355 bool isMemVY32() const {
356 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
357 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
359 bool isMemVX64() const {
360 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
361 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
363 bool isMemVY64() const {
364 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
365 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
368 bool isAbsMem() const {
369 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
370 !getMemIndexReg() && getMemScale() == 1;
373 bool isReg() const { return Kind == Register; }
375 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
376 // Add as immediates when possible.
377 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
378 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
380 Inst.addOperand(MCOperand::CreateExpr(Expr));
383 void addRegOperands(MCInst &Inst, unsigned N) const {
384 assert(N == 1 && "Invalid number of operands!");
385 Inst.addOperand(MCOperand::CreateReg(getReg()));
388 void addImmOperands(MCInst &Inst, unsigned N) const {
389 assert(N == 1 && "Invalid number of operands!");
390 addExpr(Inst, getImm());
393 void addMem8Operands(MCInst &Inst, unsigned N) const {
394 addMemOperands(Inst, N);
396 void addMem16Operands(MCInst &Inst, unsigned N) const {
397 addMemOperands(Inst, N);
399 void addMem32Operands(MCInst &Inst, unsigned N) const {
400 addMemOperands(Inst, N);
402 void addMem64Operands(MCInst &Inst, unsigned N) const {
403 addMemOperands(Inst, N);
405 void addMem80Operands(MCInst &Inst, unsigned N) const {
406 addMemOperands(Inst, N);
408 void addMem128Operands(MCInst &Inst, unsigned N) const {
409 addMemOperands(Inst, N);
411 void addMem256Operands(MCInst &Inst, unsigned N) const {
412 addMemOperands(Inst, N);
414 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
415 addMemOperands(Inst, N);
417 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
418 addMemOperands(Inst, N);
420 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
421 addMemOperands(Inst, N);
423 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
424 addMemOperands(Inst, N);
427 void addMemOperands(MCInst &Inst, unsigned N) const {
428 assert((N == 5) && "Invalid number of operands!");
429 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
430 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
431 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
432 addExpr(Inst, getMemDisp());
433 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
436 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
437 assert((N == 1) && "Invalid number of operands!");
438 // Add as immediates when possible.
439 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
440 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
442 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
445 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
446 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
447 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
448 Res->Tok.Data = Str.data();
449 Res->Tok.Length = Str.size();
453 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
454 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
455 Res->Reg.RegNo = RegNo;
459 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
460 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
465 /// Create an absolute memory operand.
466 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
467 SMLoc EndLoc, unsigned Size = 0,
468 bool OffsetOf = false, bool NeedSizeDir = false){
469 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
471 Res->Mem.Disp = Disp;
472 Res->Mem.BaseReg = 0;
473 Res->Mem.IndexReg = 0;
475 Res->Mem.Size = Size;
476 Res->Mem.OffsetOf = OffsetOf;
477 Res->Mem.NeedSizeDir = NeedSizeDir;
481 /// Create a generalized memory operand.
482 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
483 unsigned BaseReg, unsigned IndexReg,
484 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
485 unsigned Size = 0, bool OffsetOf = false,
486 bool NeedSizeDir = false) {
487 // We should never just have a displacement, that should be parsed as an
488 // absolute memory operand.
489 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
491 // The scale should always be one of {1,2,4,8}.
492 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
494 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
495 Res->Mem.SegReg = SegReg;
496 Res->Mem.Disp = Disp;
497 Res->Mem.BaseReg = BaseReg;
498 Res->Mem.IndexReg = IndexReg;
499 Res->Mem.Scale = Scale;
500 Res->Mem.Size = Size;
501 Res->Mem.OffsetOf = OffsetOf;
502 Res->Mem.NeedSizeDir = NeedSizeDir;
507 } // end anonymous namespace.
509 bool X86AsmParser::isSrcOp(X86Operand &Op) {
510 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
512 return (Op.isMem() &&
513 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
514 isa<MCConstantExpr>(Op.Mem.Disp) &&
515 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
516 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
519 bool X86AsmParser::isDstOp(X86Operand &Op) {
520 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
523 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
524 isa<MCConstantExpr>(Op.Mem.Disp) &&
525 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
526 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
529 bool X86AsmParser::ParseRegister(unsigned &RegNo,
530 SMLoc &StartLoc, SMLoc &EndLoc) {
532 const AsmToken &PercentTok = Parser.getTok();
533 StartLoc = PercentTok.getLoc();
535 // If we encounter a %, ignore it. This code handles registers with and
536 // without the prefix, unprefixed registers can occur in cfi directives.
537 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
538 Parser.Lex(); // Eat percent token.
540 const AsmToken &Tok = Parser.getTok();
541 if (Tok.isNot(AsmToken::Identifier)) {
542 if (isParsingIntelSyntax()) return true;
543 return Error(StartLoc, "invalid register name",
544 SMRange(StartLoc, Tok.getEndLoc()));
547 RegNo = MatchRegisterName(Tok.getString());
549 // If the match failed, try the register name as lowercase.
551 RegNo = MatchRegisterName(Tok.getString().lower());
553 if (!is64BitMode()) {
554 // FIXME: This should be done using Requires<In32BitMode> and
555 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
557 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
559 if (RegNo == X86::RIZ ||
560 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
561 X86II::isX86_64NonExtLowByteReg(RegNo) ||
562 X86II::isX86_64ExtendedReg(RegNo))
563 return Error(StartLoc, "register %"
564 + Tok.getString() + " is only available in 64-bit mode",
565 SMRange(StartLoc, Tok.getEndLoc()));
568 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
569 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
571 EndLoc = Tok.getLoc();
572 Parser.Lex(); // Eat 'st'
574 // Check to see if we have '(4)' after %st.
575 if (getLexer().isNot(AsmToken::LParen))
580 const AsmToken &IntTok = Parser.getTok();
581 if (IntTok.isNot(AsmToken::Integer))
582 return Error(IntTok.getLoc(), "expected stack index");
583 switch (IntTok.getIntVal()) {
584 case 0: RegNo = X86::ST0; break;
585 case 1: RegNo = X86::ST1; break;
586 case 2: RegNo = X86::ST2; break;
587 case 3: RegNo = X86::ST3; break;
588 case 4: RegNo = X86::ST4; break;
589 case 5: RegNo = X86::ST5; break;
590 case 6: RegNo = X86::ST6; break;
591 case 7: RegNo = X86::ST7; break;
592 default: return Error(IntTok.getLoc(), "invalid stack index");
595 if (getParser().Lex().isNot(AsmToken::RParen))
596 return Error(Parser.getTok().getLoc(), "expected ')'");
598 EndLoc = Tok.getLoc();
599 Parser.Lex(); // Eat ')'
603 // If this is "db[0-7]", match it as an alias
605 if (RegNo == 0 && Tok.getString().size() == 3 &&
606 Tok.getString().startswith("db")) {
607 switch (Tok.getString()[2]) {
608 case '0': RegNo = X86::DR0; break;
609 case '1': RegNo = X86::DR1; break;
610 case '2': RegNo = X86::DR2; break;
611 case '3': RegNo = X86::DR3; break;
612 case '4': RegNo = X86::DR4; break;
613 case '5': RegNo = X86::DR5; break;
614 case '6': RegNo = X86::DR6; break;
615 case '7': RegNo = X86::DR7; break;
619 EndLoc = Tok.getLoc();
620 Parser.Lex(); // Eat it.
626 if (isParsingIntelSyntax()) return true;
627 return Error(StartLoc, "invalid register name",
628 SMRange(StartLoc, Tok.getEndLoc()));
631 EndLoc = Tok.getEndLoc();
632 Parser.Lex(); // Eat identifier token.
636 X86Operand *X86AsmParser::ParseOperand() {
637 if (isParsingIntelSyntax())
638 return ParseIntelOperand();
639 return ParseATTOperand();
642 /// getIntelMemOperandSize - Return intel memory operand size.
643 static unsigned getIntelMemOperandSize(StringRef OpStr) {
644 unsigned Size = StringSwitch<unsigned>(OpStr)
645 .Cases("BYTE", "byte", 8)
646 .Cases("WORD", "word", 16)
647 .Cases("DWORD", "dword", 32)
648 .Cases("QWORD", "qword", 64)
649 .Cases("XWORD", "xword", 80)
650 .Cases("XMMWORD", "xmmword", 128)
651 .Cases("YMMWORD", "ymmword", 256)
656 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
658 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
659 SMLoc Start = Parser.getTok().getLoc(), End;
661 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
662 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
665 if (getLexer().isNot(AsmToken::LBrac))
666 return ErrorOperand(Start, "Expected '[' token!");
669 if (getLexer().is(AsmToken::Identifier)) {
671 if (ParseRegister(BaseReg, Start, End)) {
672 // Handle '[' 'symbol' ']'
673 if (getParser().ParseExpression(Disp, End)) return 0;
674 if (getLexer().isNot(AsmToken::RBrac))
675 return ErrorOperand(Start, "Expected ']' token!");
677 return X86Operand::CreateMem(Disp, Start, End, Size);
679 } else if (getLexer().is(AsmToken::Integer)) {
680 int64_t Val = Parser.getTok().getIntVal();
682 SMLoc Loc = Parser.getTok().getLoc();
683 if (getLexer().is(AsmToken::RBrac)) {
684 // Handle '[' number ']'
686 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
688 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
690 return X86Operand::CreateMem(Disp, Start, End, Size);
691 } else if (getLexer().is(AsmToken::Star)) {
692 // Handle '[' Scale*IndexReg ']'
694 SMLoc IdxRegLoc = Parser.getTok().getLoc();
695 if (ParseRegister(IndexReg, IdxRegLoc, End))
696 return ErrorOperand(IdxRegLoc, "Expected register");
699 return ErrorOperand(Loc, "Unexpected token");
702 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
703 bool isPlus = getLexer().is(AsmToken::Plus);
705 SMLoc PlusLoc = Parser.getTok().getLoc();
706 if (getLexer().is(AsmToken::Integer)) {
707 int64_t Val = Parser.getTok().getIntVal();
709 if (getLexer().is(AsmToken::Star)) {
711 SMLoc IdxRegLoc = Parser.getTok().getLoc();
712 if (ParseRegister(IndexReg, IdxRegLoc, End))
713 return ErrorOperand(IdxRegLoc, "Expected register");
715 } else if (getLexer().is(AsmToken::RBrac)) {
716 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
717 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
719 return ErrorOperand(PlusLoc, "unexpected token after +");
720 } else if (getLexer().is(AsmToken::Identifier)) {
721 // This could be an index register or a displacement expression.
722 End = Parser.getTok().getLoc();
724 ParseRegister(IndexReg, Start, End);
725 else if (getParser().ParseExpression(Disp, End)) return 0;
729 if (getLexer().isNot(AsmToken::RBrac))
730 if (getParser().ParseExpression(Disp, End)) return 0;
732 End = Parser.getTok().getLoc();
733 if (getLexer().isNot(AsmToken::RBrac))
734 return ErrorOperand(End, "expected ']' token!");
736 End = Parser.getTok().getLoc();
739 if (!BaseReg && !IndexReg)
740 return X86Operand::CreateMem(Disp, Start, End, Size);
742 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
746 /// ParseIntelMemOperand - Parse intel style memory operand.
747 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg, SMLoc Start) {
748 const AsmToken &Tok = Parser.getTok();
751 unsigned Size = getIntelMemOperandSize(Tok.getString());
754 assert ((Tok.getString() == "PTR" || Tok.getString() == "ptr") &&
755 "Unexpected token!");
759 // Parse the 'offset' operator. This operator is used to specify the
760 // location rather then the content of a variable.
761 bool OffsetOf = false;
762 if(isParsingInlineAsm() && (Tok.getString() == "offset" ||
763 Tok.getString() == "OFFSET")) {
765 Parser.Lex(); // Eat offset.
768 if (getLexer().is(AsmToken::LBrac)) {
769 assert (!OffsetOf && "Unexpected offset operator!");
770 return ParseIntelBracExpression(SegReg, Size);
773 if (!ParseRegister(SegReg, Start, End)) {
774 assert (!OffsetOf && "Unexpected offset operator!");
775 // Handel SegReg : [ ... ]
776 if (getLexer().isNot(AsmToken::Colon))
777 return ErrorOperand(Start, "Expected ':' token!");
778 Parser.Lex(); // Eat :
779 if (getLexer().isNot(AsmToken::LBrac))
780 return ErrorOperand(Start, "Expected '[' token!");
781 return ParseIntelBracExpression(SegReg, Size);
784 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
785 if (getParser().ParseExpression(Disp, End)) return 0;
786 End = Parser.getTok().getLoc();
788 bool NeedSizeDir = false;
789 if (!Size && isParsingInlineAsm()) {
790 if (const MCSymbolRefExpr *SymRef = dyn_cast<MCSymbolRefExpr>(Disp)) {
791 const MCSymbol &Sym = SymRef->getSymbol();
792 // FIXME: The SemaLookup will fail if the name is anything other then an
794 // FIXME: Pass a valid SMLoc.
795 SemaCallback->LookupInlineAsmIdentifier(Sym.getName(), NULL, Size);
796 NeedSizeDir = Size > 0;
799 return X86Operand::CreateMem(Disp, Start, End, Size, OffsetOf, NeedSizeDir);
802 X86Operand *X86AsmParser::ParseIntelOperand() {
803 SMLoc Start = Parser.getTok().getLoc(), End;
806 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
807 getLexer().is(AsmToken::Minus)) {
809 if (!getParser().ParseExpression(Val, End)) {
810 End = Parser.getTok().getLoc();
811 return X86Operand::CreateImm(Val, Start, End);
817 if (!ParseRegister(RegNo, Start, End)) {
818 // If this is a segment register followed by a ':', then this is the start
819 // of a memory reference, otherwise this is a normal register reference.
820 if (getLexer().isNot(AsmToken::Colon))
821 return X86Operand::CreateReg(RegNo, Start, Parser.getTok().getLoc());
823 getParser().Lex(); // Eat the colon.
824 return ParseIntelMemOperand(RegNo, Start);
828 return ParseIntelMemOperand(0, Start);
831 X86Operand *X86AsmParser::ParseATTOperand() {
832 switch (getLexer().getKind()) {
834 // Parse a memory operand with no segment register.
835 return ParseMemOperand(0, Parser.getTok().getLoc());
836 case AsmToken::Percent: {
837 // Read the register.
840 if (ParseRegister(RegNo, Start, End)) return 0;
841 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
842 Error(Start, "%eiz and %riz can only be used as index registers",
843 SMRange(Start, End));
847 // If this is a segment register followed by a ':', then this is the start
848 // of a memory reference, otherwise this is a normal register reference.
849 if (getLexer().isNot(AsmToken::Colon))
850 return X86Operand::CreateReg(RegNo, Start, End);
853 getParser().Lex(); // Eat the colon.
854 return ParseMemOperand(RegNo, Start);
856 case AsmToken::Dollar: {
858 SMLoc Start = Parser.getTok().getLoc(), End;
861 if (getParser().ParseExpression(Val, End))
863 return X86Operand::CreateImm(Val, Start, End);
868 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
869 /// has already been parsed if present.
870 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
872 // We have to disambiguate a parenthesized expression "(4+5)" from the start
873 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
874 // only way to do this without lookahead is to eat the '(' and see what is
876 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
877 if (getLexer().isNot(AsmToken::LParen)) {
879 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
881 // After parsing the base expression we could either have a parenthesized
882 // memory address or not. If not, return now. If so, eat the (.
883 if (getLexer().isNot(AsmToken::LParen)) {
884 // Unless we have a segment register, treat this as an immediate.
886 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
887 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
893 // Okay, we have a '('. We don't know if this is an expression or not, but
894 // so we have to eat the ( to see beyond it.
895 SMLoc LParenLoc = Parser.getTok().getLoc();
896 Parser.Lex(); // Eat the '('.
898 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
899 // Nothing to do here, fall into the code below with the '(' part of the
900 // memory operand consumed.
904 // It must be an parenthesized expression, parse it now.
905 if (getParser().ParseParenExpression(Disp, ExprEnd))
908 // After parsing the base expression we could either have a parenthesized
909 // memory address or not. If not, return now. If so, eat the (.
910 if (getLexer().isNot(AsmToken::LParen)) {
911 // Unless we have a segment register, treat this as an immediate.
913 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
914 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
922 // If we reached here, then we just ate the ( of the memory operand. Process
923 // the rest of the memory operand.
924 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
927 if (getLexer().is(AsmToken::Percent)) {
928 SMLoc StartLoc, EndLoc;
929 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
930 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
931 Error(StartLoc, "eiz and riz can only be used as index registers",
932 SMRange(StartLoc, EndLoc));
937 if (getLexer().is(AsmToken::Comma)) {
938 Parser.Lex(); // Eat the comma.
939 IndexLoc = Parser.getTok().getLoc();
941 // Following the comma we should have either an index register, or a scale
942 // value. We don't support the later form, but we want to parse it
945 // Not that even though it would be completely consistent to support syntax
946 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
947 if (getLexer().is(AsmToken::Percent)) {
949 if (ParseRegister(IndexReg, L, L)) return 0;
951 if (getLexer().isNot(AsmToken::RParen)) {
952 // Parse the scale amount:
953 // ::= ',' [scale-expression]
954 if (getLexer().isNot(AsmToken::Comma)) {
955 Error(Parser.getTok().getLoc(),
956 "expected comma in scale expression");
959 Parser.Lex(); // Eat the comma.
961 if (getLexer().isNot(AsmToken::RParen)) {
962 SMLoc Loc = Parser.getTok().getLoc();
965 if (getParser().ParseAbsoluteExpression(ScaleVal)){
966 Error(Loc, "expected scale expression");
970 // Validate the scale amount.
971 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
972 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
975 Scale = (unsigned)ScaleVal;
978 } else if (getLexer().isNot(AsmToken::RParen)) {
979 // A scale amount without an index is ignored.
981 SMLoc Loc = Parser.getTok().getLoc();
984 if (getParser().ParseAbsoluteExpression(Value))
988 Warning(Loc, "scale factor without index register is ignored");
993 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
994 if (getLexer().isNot(AsmToken::RParen)) {
995 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
998 SMLoc MemEnd = Parser.getTok().getLoc();
999 Parser.Lex(); // Eat the ')'.
1001 // If we have both a base register and an index register make sure they are
1002 // both 64-bit or 32-bit registers.
1003 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1004 if (BaseReg != 0 && IndexReg != 0) {
1005 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1006 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1007 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1008 IndexReg != X86::RIZ) {
1009 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1012 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1013 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1014 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1015 IndexReg != X86::EIZ){
1016 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1021 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1026 ParseInstruction(StringRef Name, SMLoc NameLoc,
1027 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1028 StringRef PatchedName = Name;
1030 // FIXME: Hack to recognize setneb as setne.
1031 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1032 PatchedName != "setb" && PatchedName != "setnb")
1033 PatchedName = PatchedName.substr(0, Name.size()-1);
1035 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1036 const MCExpr *ExtraImmOp = 0;
1037 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1038 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1039 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1040 bool IsVCMP = PatchedName[0] == 'v';
1041 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1042 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1043 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1047 .Case("unord", 0x03)
1052 /* AVX only from here */
1053 .Case("eq_uq", 0x08)
1056 .Case("false", 0x0B)
1057 .Case("neq_oq", 0x0C)
1061 .Case("eq_os", 0x10)
1062 .Case("lt_oq", 0x11)
1063 .Case("le_oq", 0x12)
1064 .Case("unord_s", 0x13)
1065 .Case("neq_us", 0x14)
1066 .Case("nlt_uq", 0x15)
1067 .Case("nle_uq", 0x16)
1068 .Case("ord_s", 0x17)
1069 .Case("eq_us", 0x18)
1070 .Case("nge_uq", 0x19)
1071 .Case("ngt_uq", 0x1A)
1072 .Case("false_os", 0x1B)
1073 .Case("neq_os", 0x1C)
1074 .Case("ge_oq", 0x1D)
1075 .Case("gt_oq", 0x1E)
1076 .Case("true_us", 0x1F)
1078 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1079 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1080 getParser().getContext());
1081 if (PatchedName.endswith("ss")) {
1082 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1083 } else if (PatchedName.endswith("sd")) {
1084 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1085 } else if (PatchedName.endswith("ps")) {
1086 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1088 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1089 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1094 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1096 if (ExtraImmOp && !isParsingIntelSyntax())
1097 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1099 // Determine whether this is an instruction prefix.
1101 Name == "lock" || Name == "rep" ||
1102 Name == "repe" || Name == "repz" ||
1103 Name == "repne" || Name == "repnz" ||
1104 Name == "rex64" || Name == "data16";
1107 // This does the actual operand parsing. Don't parse any more if we have a
1108 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1109 // just want to parse the "lock" as the first instruction and the "incl" as
1111 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1113 // Parse '*' modifier.
1114 if (getLexer().is(AsmToken::Star)) {
1115 SMLoc Loc = Parser.getTok().getLoc();
1116 Operands.push_back(X86Operand::CreateToken("*", Loc));
1117 Parser.Lex(); // Eat the star.
1120 // Read the first operand.
1121 if (X86Operand *Op = ParseOperand())
1122 Operands.push_back(Op);
1124 Parser.EatToEndOfStatement();
1128 while (getLexer().is(AsmToken::Comma)) {
1129 Parser.Lex(); // Eat the comma.
1131 // Parse and remember the operand.
1132 if (X86Operand *Op = ParseOperand())
1133 Operands.push_back(Op);
1135 Parser.EatToEndOfStatement();
1140 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1141 SMLoc Loc = getLexer().getLoc();
1142 Parser.EatToEndOfStatement();
1143 return Error(Loc, "unexpected token in argument list");
1147 if (getLexer().is(AsmToken::EndOfStatement))
1148 Parser.Lex(); // Consume the EndOfStatement
1149 else if (isPrefix && getLexer().is(AsmToken::Slash))
1150 Parser.Lex(); // Consume the prefix separator Slash
1152 if (ExtraImmOp && isParsingIntelSyntax())
1153 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1155 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1156 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1157 // documented form in various unofficial manuals, so a lot of code uses it.
1158 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1159 Operands.size() == 3) {
1160 X86Operand &Op = *(X86Operand*)Operands.back();
1161 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1162 isa<MCConstantExpr>(Op.Mem.Disp) &&
1163 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1164 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1165 SMLoc Loc = Op.getEndLoc();
1166 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1170 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1171 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1172 Operands.size() == 3) {
1173 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1174 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1175 isa<MCConstantExpr>(Op.Mem.Disp) &&
1176 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1177 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1178 SMLoc Loc = Op.getEndLoc();
1179 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1183 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1184 if (Name.startswith("ins") && Operands.size() == 3 &&
1185 (Name == "insb" || Name == "insw" || Name == "insl")) {
1186 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1187 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1188 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1189 Operands.pop_back();
1190 Operands.pop_back();
1196 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1197 if (Name.startswith("outs") && Operands.size() == 3 &&
1198 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1199 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1200 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1201 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1202 Operands.pop_back();
1203 Operands.pop_back();
1209 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1210 if (Name.startswith("movs") && Operands.size() == 3 &&
1211 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1212 (is64BitMode() && Name == "movsq"))) {
1213 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1214 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1215 if (isSrcOp(Op) && isDstOp(Op2)) {
1216 Operands.pop_back();
1217 Operands.pop_back();
1222 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1223 if (Name.startswith("lods") && Operands.size() == 3 &&
1224 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1225 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1226 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1227 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1228 if (isSrcOp(*Op1) && Op2->isReg()) {
1230 unsigned reg = Op2->getReg();
1231 bool isLods = Name == "lods";
1232 if (reg == X86::AL && (isLods || Name == "lodsb"))
1234 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1236 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1238 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1243 Operands.pop_back();
1244 Operands.pop_back();
1248 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1252 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1253 if (Name.startswith("stos") && Operands.size() == 3 &&
1254 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1255 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1256 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1257 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1258 if (isDstOp(*Op2) && Op1->isReg()) {
1260 unsigned reg = Op1->getReg();
1261 bool isStos = Name == "stos";
1262 if (reg == X86::AL && (isStos || Name == "stosb"))
1264 else if (reg == X86::AX && (isStos || Name == "stosw"))
1266 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1268 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1273 Operands.pop_back();
1274 Operands.pop_back();
1278 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1283 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1285 if ((Name.startswith("shr") || Name.startswith("sar") ||
1286 Name.startswith("shl") || Name.startswith("sal") ||
1287 Name.startswith("rcl") || Name.startswith("rcr") ||
1288 Name.startswith("rol") || Name.startswith("ror")) &&
1289 Operands.size() == 3) {
1290 if (isParsingIntelSyntax()) {
1292 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1293 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1294 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1296 Operands.pop_back();
1299 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1300 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1301 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1303 Operands.erase(Operands.begin() + 1);
1308 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1309 // instalias with an immediate operand yet.
1310 if (Name == "int" && Operands.size() == 2) {
1311 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1312 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1313 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1315 Operands.erase(Operands.begin() + 1);
1316 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1324 processInstruction(MCInst &Inst,
1325 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1326 switch (Inst.getOpcode()) {
1327 default: return false;
1328 case X86::AND16i16: {
1329 if (!Inst.getOperand(0).isImm() ||
1330 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1334 TmpInst.setOpcode(X86::AND16ri8);
1335 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1336 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1337 TmpInst.addOperand(Inst.getOperand(0));
1341 case X86::AND32i32: {
1342 if (!Inst.getOperand(0).isImm() ||
1343 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1347 TmpInst.setOpcode(X86::AND32ri8);
1348 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1349 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1350 TmpInst.addOperand(Inst.getOperand(0));
1354 case X86::AND64i32: {
1355 if (!Inst.getOperand(0).isImm() ||
1356 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1360 TmpInst.setOpcode(X86::AND64ri8);
1361 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1362 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1363 TmpInst.addOperand(Inst.getOperand(0));
1367 case X86::XOR16i16: {
1368 if (!Inst.getOperand(0).isImm() ||
1369 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1373 TmpInst.setOpcode(X86::XOR16ri8);
1374 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1375 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1376 TmpInst.addOperand(Inst.getOperand(0));
1380 case X86::XOR32i32: {
1381 if (!Inst.getOperand(0).isImm() ||
1382 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1386 TmpInst.setOpcode(X86::XOR32ri8);
1387 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1388 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1389 TmpInst.addOperand(Inst.getOperand(0));
1393 case X86::XOR64i32: {
1394 if (!Inst.getOperand(0).isImm() ||
1395 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1399 TmpInst.setOpcode(X86::XOR64ri8);
1400 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1401 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1402 TmpInst.addOperand(Inst.getOperand(0));
1406 case X86::OR16i16: {
1407 if (!Inst.getOperand(0).isImm() ||
1408 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1412 TmpInst.setOpcode(X86::OR16ri8);
1413 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1414 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1415 TmpInst.addOperand(Inst.getOperand(0));
1419 case X86::OR32i32: {
1420 if (!Inst.getOperand(0).isImm() ||
1421 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1425 TmpInst.setOpcode(X86::OR32ri8);
1426 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1427 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1428 TmpInst.addOperand(Inst.getOperand(0));
1432 case X86::OR64i32: {
1433 if (!Inst.getOperand(0).isImm() ||
1434 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1438 TmpInst.setOpcode(X86::OR64ri8);
1439 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1440 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1441 TmpInst.addOperand(Inst.getOperand(0));
1445 case X86::CMP16i16: {
1446 if (!Inst.getOperand(0).isImm() ||
1447 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1451 TmpInst.setOpcode(X86::CMP16ri8);
1452 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1453 TmpInst.addOperand(Inst.getOperand(0));
1457 case X86::CMP32i32: {
1458 if (!Inst.getOperand(0).isImm() ||
1459 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1463 TmpInst.setOpcode(X86::CMP32ri8);
1464 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1465 TmpInst.addOperand(Inst.getOperand(0));
1469 case X86::CMP64i32: {
1470 if (!Inst.getOperand(0).isImm() ||
1471 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1475 TmpInst.setOpcode(X86::CMP64ri8);
1476 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1477 TmpInst.addOperand(Inst.getOperand(0));
1481 case X86::ADD16i16: {
1482 if (!Inst.getOperand(0).isImm() ||
1483 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1487 TmpInst.setOpcode(X86::ADD16ri8);
1488 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1489 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1490 TmpInst.addOperand(Inst.getOperand(0));
1494 case X86::ADD32i32: {
1495 if (!Inst.getOperand(0).isImm() ||
1496 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1500 TmpInst.setOpcode(X86::ADD32ri8);
1501 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1502 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1503 TmpInst.addOperand(Inst.getOperand(0));
1507 case X86::ADD64i32: {
1508 if (!Inst.getOperand(0).isImm() ||
1509 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1513 TmpInst.setOpcode(X86::ADD64ri8);
1514 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1515 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1516 TmpInst.addOperand(Inst.getOperand(0));
1520 case X86::SUB16i16: {
1521 if (!Inst.getOperand(0).isImm() ||
1522 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1526 TmpInst.setOpcode(X86::SUB16ri8);
1527 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1528 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1529 TmpInst.addOperand(Inst.getOperand(0));
1533 case X86::SUB32i32: {
1534 if (!Inst.getOperand(0).isImm() ||
1535 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1539 TmpInst.setOpcode(X86::SUB32ri8);
1540 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1541 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1542 TmpInst.addOperand(Inst.getOperand(0));
1546 case X86::SUB64i32: {
1547 if (!Inst.getOperand(0).isImm() ||
1548 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1552 TmpInst.setOpcode(X86::SUB64ri8);
1553 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1554 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1555 TmpInst.addOperand(Inst.getOperand(0));
1563 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1564 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1565 MCStreamer &Out, unsigned &ErrorInfo,
1566 bool MatchingInlineAsm) {
1567 assert(!Operands.empty() && "Unexpect empty operand list!");
1568 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1569 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1570 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
1572 // First, handle aliases that expand to multiple instructions.
1573 // FIXME: This should be replaced with a real .td file alias mechanism.
1574 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
1576 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1577 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1578 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1579 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1581 Inst.setOpcode(X86::WAIT);
1583 if (!MatchingInlineAsm)
1584 Out.EmitInstruction(Inst);
1587 StringSwitch<const char*>(Op->getToken())
1588 .Case("finit", "fninit")
1589 .Case("fsave", "fnsave")
1590 .Case("fstcw", "fnstcw")
1591 .Case("fstcww", "fnstcw")
1592 .Case("fstenv", "fnstenv")
1593 .Case("fstsw", "fnstsw")
1594 .Case("fstsww", "fnstsw")
1595 .Case("fclex", "fnclex")
1597 assert(Repl && "Unknown wait-prefixed instruction");
1599 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1602 bool WasOriginallyInvalidOperand = false;
1605 // First, try a direct match.
1606 switch (MatchInstructionImpl(Operands, Inst,
1607 ErrorInfo, MatchingInlineAsm,
1608 isParsingIntelSyntax())) {
1611 // Some instructions need post-processing to, for example, tweak which
1612 // encoding is selected. Loop on it while changes happen so the
1613 // individual transformations can chain off each other.
1614 if (!MatchingInlineAsm)
1615 while (processInstruction(Inst, Operands))
1619 if (!MatchingInlineAsm)
1620 Out.EmitInstruction(Inst);
1621 Opcode = Inst.getOpcode();
1623 case Match_MissingFeature:
1624 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1625 EmptyRanges, MatchingInlineAsm);
1627 case Match_InvalidOperand:
1628 WasOriginallyInvalidOperand = true;
1630 case Match_MnemonicFail:
1634 // FIXME: Ideally, we would only attempt suffix matches for things which are
1635 // valid prefixes, and we could just infer the right unambiguous
1636 // type. However, that requires substantially more matcher support than the
1639 // Change the operand to point to a temporary token.
1640 StringRef Base = Op->getToken();
1641 SmallString<16> Tmp;
1644 Op->setTokenValue(Tmp.str());
1646 // If this instruction starts with an 'f', then it is a floating point stack
1647 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1648 // 80-bit floating point, which use the suffixes s,l,t respectively.
1650 // Otherwise, we assume that this may be an integer instruction, which comes
1651 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1652 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1654 // Check for the various suffix matches.
1655 Tmp[Base.size()] = Suffixes[0];
1656 unsigned ErrorInfoIgnore;
1657 unsigned Match1, Match2, Match3, Match4;
1659 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1660 isParsingIntelSyntax());
1661 Tmp[Base.size()] = Suffixes[1];
1662 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1663 isParsingIntelSyntax());
1664 Tmp[Base.size()] = Suffixes[2];
1665 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1666 isParsingIntelSyntax());
1667 Tmp[Base.size()] = Suffixes[3];
1668 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1669 isParsingIntelSyntax());
1671 // Restore the old token.
1672 Op->setTokenValue(Base);
1674 // If exactly one matched, then we treat that as a successful match (and the
1675 // instruction will already have been filled in correctly, since the failing
1676 // matches won't have modified it).
1677 unsigned NumSuccessfulMatches =
1678 (Match1 == Match_Success) + (Match2 == Match_Success) +
1679 (Match3 == Match_Success) + (Match4 == Match_Success);
1680 if (NumSuccessfulMatches == 1) {
1682 if (!MatchingInlineAsm)
1683 Out.EmitInstruction(Inst);
1684 Opcode = Inst.getOpcode();
1688 // Otherwise, the match failed, try to produce a decent error message.
1690 // If we had multiple suffix matches, then identify this as an ambiguous
1692 if (NumSuccessfulMatches > 1) {
1694 unsigned NumMatches = 0;
1695 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1696 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1697 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1698 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1700 SmallString<126> Msg;
1701 raw_svector_ostream OS(Msg);
1702 OS << "ambiguous instructions require an explicit suffix (could be ";
1703 for (unsigned i = 0; i != NumMatches; ++i) {
1706 if (i + 1 == NumMatches)
1708 OS << "'" << Base << MatchChars[i] << "'";
1711 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
1715 // Okay, we know that none of the variants matched successfully.
1717 // If all of the instructions reported an invalid mnemonic, then the original
1718 // mnemonic was invalid.
1719 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1720 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1721 if (!WasOriginallyInvalidOperand) {
1722 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
1724 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1725 Ranges, MatchingInlineAsm);
1728 // Recover location info for the operand if we know which was the problem.
1729 if (ErrorInfo != ~0U) {
1730 if (ErrorInfo >= Operands.size())
1731 return Error(IDLoc, "too few operands for instruction",
1732 EmptyRanges, MatchingInlineAsm);
1734 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
1735 if (Operand->getStartLoc().isValid()) {
1736 SMRange OperandRange = Operand->getLocRange();
1737 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1738 OperandRange, MatchingInlineAsm);
1742 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1746 // If one instruction matched with a missing feature, report this as a
1748 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1749 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1750 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1751 EmptyRanges, MatchingInlineAsm);
1755 // If one instruction matched with an invalid operand, report this as an
1757 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1758 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1759 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1764 // If all of these were an outright failure, report it in a useless way.
1765 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
1766 EmptyRanges, MatchingInlineAsm);
1771 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1772 StringRef IDVal = DirectiveID.getIdentifier();
1773 if (IDVal == ".word")
1774 return ParseDirectiveWord(2, DirectiveID.getLoc());
1775 else if (IDVal.startswith(".code"))
1776 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1777 else if (IDVal.startswith(".att_syntax")) {
1778 getParser().setAssemblerDialect(0);
1780 } else if (IDVal.startswith(".intel_syntax")) {
1781 getParser().setAssemblerDialect(1);
1782 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1783 if(Parser.getTok().getString() == "noprefix") {
1784 // FIXME : Handle noprefix
1794 /// ParseDirectiveWord
1795 /// ::= .word [ expression (, expression)* ]
1796 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1797 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1799 const MCExpr *Value;
1800 if (getParser().ParseExpression(Value))
1803 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1805 if (getLexer().is(AsmToken::EndOfStatement))
1808 // FIXME: Improve diagnostic.
1809 if (getLexer().isNot(AsmToken::Comma))
1810 return Error(L, "unexpected token in directive");
1819 /// ParseDirectiveCode
1820 /// ::= .code32 | .code64
1821 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1822 if (IDVal == ".code32") {
1824 if (is64BitMode()) {
1826 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1828 } else if (IDVal == ".code64") {
1830 if (!is64BitMode()) {
1832 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1835 return Error(L, "unexpected directive " + IDVal);
1842 extern "C" void LLVMInitializeX86AsmLexer();
1844 // Force static initialization.
1845 extern "C" void LLVMInitializeX86AsmParser() {
1846 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1847 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1848 LLVMInitializeX86AsmLexer();
1851 #define GET_REGISTER_MATCHER
1852 #define GET_MATCHER_IMPLEMENTATION
1853 #include "X86GenAsmMatcher.inc"