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 {
38 ParseInstructionInfo *InstInfo;
40 MCAsmParser &getParser() const { return Parser; }
42 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
44 bool Error(SMLoc L, const Twine &Msg,
45 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>(),
46 bool MatchingInlineAsm = false) {
47 if (MatchingInlineAsm) return true;
48 return Parser.Error(L, Msg, Ranges);
51 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
56 X86Operand *ParseOperand();
57 X86Operand *ParseATTOperand();
58 X86Operand *ParseIntelOperand();
59 X86Operand *ParseIntelOffsetOfOperator(SMLoc StartLoc);
60 X86Operand *ParseIntelMemOperand(unsigned SegReg, SMLoc StartLoc);
61 X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
62 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
64 bool ParseIntelDotOperator(const MCExpr *Disp, const MCExpr **NewDisp,
65 SmallString<64> &Err);
67 bool ParseDirectiveWord(unsigned Size, SMLoc L);
68 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
70 bool processInstruction(MCInst &Inst,
71 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
73 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
74 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
75 MCStreamer &Out, unsigned &ErrorInfo,
76 bool MatchingInlineAsm);
78 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
79 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
80 bool isSrcOp(X86Operand &Op);
82 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
83 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
84 bool isDstOp(X86Operand &Op);
86 bool is64BitMode() const {
87 // FIXME: Can tablegen auto-generate this?
88 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
91 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
92 setAvailableFeatures(FB);
95 /// @name Auto-generated Matcher Functions
98 #define GET_ASSEMBLER_HEADER
99 #include "X86GenAsmMatcher.inc"
104 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
105 : MCTargetAsmParser(), STI(sti), Parser(parser), InstInfo(0) {
107 // Initialize the set of available features.
108 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
110 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
112 virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
114 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
116 virtual bool ParseDirective(AsmToken DirectiveID);
118 bool isParsingIntelSyntax() {
119 return getParser().getAssemblerDialect();
122 } // end anonymous namespace
124 /// @name Auto-generated Match Functions
127 static unsigned MatchRegisterName(StringRef Name);
131 static bool isImmSExti16i8Value(uint64_t Value) {
132 return (( Value <= 0x000000000000007FULL)||
133 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
134 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
137 static bool isImmSExti32i8Value(uint64_t Value) {
138 return (( Value <= 0x000000000000007FULL)||
139 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
140 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
143 static bool isImmZExtu32u8Value(uint64_t Value) {
144 return (Value <= 0x00000000000000FFULL);
147 static bool isImmSExti64i8Value(uint64_t Value) {
148 return (( Value <= 0x000000000000007FULL)||
149 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
152 static bool isImmSExti64i32Value(uint64_t Value) {
153 return (( Value <= 0x000000007FFFFFFFULL)||
154 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
158 /// X86Operand - Instances of this class represent a parsed X86 machine
160 struct X86Operand : public MCParsedAsmOperand {
168 SMLoc StartLoc, EndLoc;
196 X86Operand(KindTy K, SMLoc Start, SMLoc End)
197 : Kind(K), StartLoc(Start), EndLoc(End) {}
199 /// getStartLoc - Get the location of the first token of this operand.
200 SMLoc getStartLoc() const { return StartLoc; }
201 /// getEndLoc - Get the location of the last token of this operand.
202 SMLoc getEndLoc() const { return EndLoc; }
203 /// getLocRange - Get the range between the first and last token of this
205 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
206 /// getOffsetOfLoc - Get the location of the offset operator.
207 SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
209 virtual void print(raw_ostream &OS) const {}
211 StringRef getToken() const {
212 assert(Kind == Token && "Invalid access!");
213 return StringRef(Tok.Data, Tok.Length);
215 void setTokenValue(StringRef Value) {
216 assert(Kind == Token && "Invalid access!");
217 Tok.Data = Value.data();
218 Tok.Length = Value.size();
221 unsigned getReg() const {
222 assert(Kind == Register && "Invalid access!");
226 const MCExpr *getImm() const {
227 assert(Kind == Immediate && "Invalid access!");
231 const MCExpr *getMemDisp() const {
232 assert(Kind == Memory && "Invalid access!");
235 unsigned getMemSegReg() const {
236 assert(Kind == Memory && "Invalid access!");
239 unsigned getMemBaseReg() const {
240 assert(Kind == Memory && "Invalid access!");
243 unsigned getMemIndexReg() const {
244 assert(Kind == Memory && "Invalid access!");
247 unsigned getMemScale() const {
248 assert(Kind == Memory && "Invalid access!");
252 bool isToken() const {return Kind == Token; }
254 bool isImm() const { return Kind == Immediate; }
256 bool isImmSExti16i8() const {
260 // If this isn't a constant expr, just assume it fits and let relaxation
262 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
266 // Otherwise, check the value is in a range that makes sense for this
268 return isImmSExti16i8Value(CE->getValue());
270 bool isImmSExti32i8() const {
274 // If this isn't a constant expr, just assume it fits and let relaxation
276 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
280 // Otherwise, check the value is in a range that makes sense for this
282 return isImmSExti32i8Value(CE->getValue());
284 bool isImmZExtu32u8() const {
288 // If this isn't a constant expr, just assume it fits and let relaxation
290 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
294 // Otherwise, check the value is in a range that makes sense for this
296 return isImmZExtu32u8Value(CE->getValue());
298 bool isImmSExti64i8() const {
302 // If this isn't a constant expr, just assume it fits and let relaxation
304 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
308 // Otherwise, check the value is in a range that makes sense for this
310 return isImmSExti64i8Value(CE->getValue());
312 bool isImmSExti64i32() const {
316 // If this isn't a constant expr, just assume it fits and let relaxation
318 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
322 // Otherwise, check the value is in a range that makes sense for this
324 return isImmSExti64i32Value(CE->getValue());
327 unsigned getMemSize() const {
328 assert(Kind == Memory && "Invalid access!");
332 bool isOffsetOf() const {
333 return OffsetOfLoc.getPointer();
336 bool needSizeDirective() const {
337 assert(Kind == Memory && "Invalid access!");
338 return Mem.NeedSizeDir;
341 bool isMem() const { return Kind == Memory; }
342 bool isMem8() const {
343 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
345 bool isMem16() const {
346 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
348 bool isMem32() const {
349 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
351 bool isMem64() const {
352 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
354 bool isMem80() const {
355 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
357 bool isMem128() const {
358 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
360 bool isMem256() const {
361 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
364 bool isMemVX32() const {
365 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
366 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
368 bool isMemVY32() const {
369 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
370 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
372 bool isMemVX64() const {
373 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
374 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
376 bool isMemVY64() const {
377 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
378 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
381 bool isAbsMem() const {
382 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
383 !getMemIndexReg() && getMemScale() == 1;
386 bool isReg() const { return Kind == Register; }
388 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
389 // Add as immediates when possible.
390 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
391 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
393 Inst.addOperand(MCOperand::CreateExpr(Expr));
396 void addRegOperands(MCInst &Inst, unsigned N) const {
397 assert(N == 1 && "Invalid number of operands!");
398 Inst.addOperand(MCOperand::CreateReg(getReg()));
401 void addImmOperands(MCInst &Inst, unsigned N) const {
402 assert(N == 1 && "Invalid number of operands!");
403 addExpr(Inst, getImm());
406 void addMem8Operands(MCInst &Inst, unsigned N) const {
407 addMemOperands(Inst, N);
409 void addMem16Operands(MCInst &Inst, unsigned N) const {
410 addMemOperands(Inst, N);
412 void addMem32Operands(MCInst &Inst, unsigned N) const {
413 addMemOperands(Inst, N);
415 void addMem64Operands(MCInst &Inst, unsigned N) const {
416 addMemOperands(Inst, N);
418 void addMem80Operands(MCInst &Inst, unsigned N) const {
419 addMemOperands(Inst, N);
421 void addMem128Operands(MCInst &Inst, unsigned N) const {
422 addMemOperands(Inst, N);
424 void addMem256Operands(MCInst &Inst, unsigned N) const {
425 addMemOperands(Inst, N);
427 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
428 addMemOperands(Inst, N);
430 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
431 addMemOperands(Inst, N);
433 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
434 addMemOperands(Inst, N);
436 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
437 addMemOperands(Inst, N);
440 void addMemOperands(MCInst &Inst, unsigned N) const {
441 assert((N == 5) && "Invalid number of operands!");
442 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
443 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
444 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
445 addExpr(Inst, getMemDisp());
446 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
449 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
450 assert((N == 1) && "Invalid number of operands!");
451 // Add as immediates when possible.
452 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
453 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
455 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
458 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
459 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
460 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
461 Res->Tok.Data = Str.data();
462 Res->Tok.Length = Str.size();
466 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
467 SMLoc OffsetOfLoc = SMLoc()) {
468 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
469 Res->Reg.RegNo = RegNo;
470 Res->OffsetOfLoc = OffsetOfLoc;
474 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
475 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
480 /// Create an absolute memory operand.
481 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc,
482 unsigned Size = 0, bool NeedSizeDir = false){
483 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
485 Res->Mem.Disp = Disp;
486 Res->Mem.BaseReg = 0;
487 Res->Mem.IndexReg = 0;
489 Res->Mem.Size = Size;
490 Res->Mem.NeedSizeDir = NeedSizeDir;
494 /// Create a generalized memory operand.
495 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
496 unsigned BaseReg, unsigned IndexReg,
497 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
498 unsigned Size = 0, bool NeedSizeDir = false) {
499 // We should never just have a displacement, that should be parsed as an
500 // absolute memory operand.
501 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
503 // The scale should always be one of {1,2,4,8}.
504 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
506 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
507 Res->Mem.SegReg = SegReg;
508 Res->Mem.Disp = Disp;
509 Res->Mem.BaseReg = BaseReg;
510 Res->Mem.IndexReg = IndexReg;
511 Res->Mem.Scale = Scale;
512 Res->Mem.Size = Size;
513 Res->Mem.NeedSizeDir = NeedSizeDir;
518 } // end anonymous namespace.
520 bool X86AsmParser::isSrcOp(X86Operand &Op) {
521 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
523 return (Op.isMem() &&
524 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
525 isa<MCConstantExpr>(Op.Mem.Disp) &&
526 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
527 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
530 bool X86AsmParser::isDstOp(X86Operand &Op) {
531 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
534 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
535 isa<MCConstantExpr>(Op.Mem.Disp) &&
536 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
537 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
540 bool X86AsmParser::ParseRegister(unsigned &RegNo,
541 SMLoc &StartLoc, SMLoc &EndLoc) {
543 const AsmToken &PercentTok = Parser.getTok();
544 StartLoc = PercentTok.getLoc();
546 // If we encounter a %, ignore it. This code handles registers with and
547 // without the prefix, unprefixed registers can occur in cfi directives.
548 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
549 Parser.Lex(); // Eat percent token.
551 const AsmToken &Tok = Parser.getTok();
552 if (Tok.isNot(AsmToken::Identifier)) {
553 if (isParsingIntelSyntax()) return true;
554 return Error(StartLoc, "invalid register name",
555 SMRange(StartLoc, Tok.getEndLoc()));
558 RegNo = MatchRegisterName(Tok.getString());
560 // If the match failed, try the register name as lowercase.
562 RegNo = MatchRegisterName(Tok.getString().lower());
564 if (!is64BitMode()) {
565 // FIXME: This should be done using Requires<In32BitMode> and
566 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
568 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
570 if (RegNo == X86::RIZ ||
571 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
572 X86II::isX86_64NonExtLowByteReg(RegNo) ||
573 X86II::isX86_64ExtendedReg(RegNo))
574 return Error(StartLoc, "register %"
575 + Tok.getString() + " is only available in 64-bit mode",
576 SMRange(StartLoc, Tok.getEndLoc()));
579 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
580 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
582 EndLoc = Tok.getLoc();
583 Parser.Lex(); // Eat 'st'
585 // Check to see if we have '(4)' after %st.
586 if (getLexer().isNot(AsmToken::LParen))
591 const AsmToken &IntTok = Parser.getTok();
592 if (IntTok.isNot(AsmToken::Integer))
593 return Error(IntTok.getLoc(), "expected stack index");
594 switch (IntTok.getIntVal()) {
595 case 0: RegNo = X86::ST0; break;
596 case 1: RegNo = X86::ST1; break;
597 case 2: RegNo = X86::ST2; break;
598 case 3: RegNo = X86::ST3; break;
599 case 4: RegNo = X86::ST4; break;
600 case 5: RegNo = X86::ST5; break;
601 case 6: RegNo = X86::ST6; break;
602 case 7: RegNo = X86::ST7; break;
603 default: return Error(IntTok.getLoc(), "invalid stack index");
606 if (getParser().Lex().isNot(AsmToken::RParen))
607 return Error(Parser.getTok().getLoc(), "expected ')'");
609 EndLoc = Tok.getLoc();
610 Parser.Lex(); // Eat ')'
614 // If this is "db[0-7]", match it as an alias
616 if (RegNo == 0 && Tok.getString().size() == 3 &&
617 Tok.getString().startswith("db")) {
618 switch (Tok.getString()[2]) {
619 case '0': RegNo = X86::DR0; break;
620 case '1': RegNo = X86::DR1; break;
621 case '2': RegNo = X86::DR2; break;
622 case '3': RegNo = X86::DR3; break;
623 case '4': RegNo = X86::DR4; break;
624 case '5': RegNo = X86::DR5; break;
625 case '6': RegNo = X86::DR6; break;
626 case '7': RegNo = X86::DR7; break;
630 EndLoc = Tok.getLoc();
631 Parser.Lex(); // Eat it.
637 if (isParsingIntelSyntax()) return true;
638 return Error(StartLoc, "invalid register name",
639 SMRange(StartLoc, Tok.getEndLoc()));
642 EndLoc = Tok.getEndLoc();
643 Parser.Lex(); // Eat identifier token.
647 X86Operand *X86AsmParser::ParseOperand() {
648 if (isParsingIntelSyntax())
649 return ParseIntelOperand();
650 return ParseATTOperand();
653 /// getIntelMemOperandSize - Return intel memory operand size.
654 static unsigned getIntelMemOperandSize(StringRef OpStr) {
655 unsigned Size = StringSwitch<unsigned>(OpStr)
656 .Cases("BYTE", "byte", 8)
657 .Cases("WORD", "word", 16)
658 .Cases("DWORD", "dword", 32)
659 .Cases("QWORD", "qword", 64)
660 .Cases("XWORD", "xword", 80)
661 .Cases("XMMWORD", "xmmword", 128)
662 .Cases("YMMWORD", "ymmword", 256)
667 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
669 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
670 const AsmToken &Tok = Parser.getTok();
671 SMLoc Start = Tok.getLoc(), End;
673 const MCExpr *Disp = MCConstantExpr::Create(0, getContext());
674 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
677 if (getLexer().isNot(AsmToken::LBrac))
678 return ErrorOperand(Start, "Expected '[' token!");
681 if (getLexer().is(AsmToken::Identifier)) {
683 if (ParseRegister(BaseReg, Start, End)) {
684 // Handle '[' 'symbol' ']'
685 if (getParser().ParseExpression(Disp, End)) return 0;
686 if (getLexer().isNot(AsmToken::RBrac))
687 return ErrorOperand(Start, "Expected ']' token!");
689 return X86Operand::CreateMem(Disp, Start, End, Size);
691 } else if (getLexer().is(AsmToken::Integer)) {
692 int64_t Val = Tok.getIntVal();
694 SMLoc Loc = Tok.getLoc();
695 if (getLexer().is(AsmToken::RBrac)) {
696 // Handle '[' number ']'
698 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
700 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
702 return X86Operand::CreateMem(Disp, Start, End, Size);
703 } else if (getLexer().is(AsmToken::Star)) {
704 // Handle '[' Scale*IndexReg ']'
706 SMLoc IdxRegLoc = Tok.getLoc();
707 if (ParseRegister(IndexReg, IdxRegLoc, End))
708 return ErrorOperand(IdxRegLoc, "Expected register");
711 return ErrorOperand(Loc, "Unexpected token");
714 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
715 bool isPlus = getLexer().is(AsmToken::Plus);
717 SMLoc PlusLoc = Tok.getLoc();
718 if (getLexer().is(AsmToken::Integer)) {
719 int64_t Val = Tok.getIntVal();
721 if (getLexer().is(AsmToken::Star)) {
723 SMLoc IdxRegLoc = Tok.getLoc();
724 if (ParseRegister(IndexReg, IdxRegLoc, End))
725 return ErrorOperand(IdxRegLoc, "Expected register");
727 } else if (getLexer().is(AsmToken::RBrac)) {
728 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
729 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
731 return ErrorOperand(PlusLoc, "unexpected token after +");
732 } else if (getLexer().is(AsmToken::Identifier)) {
733 // This could be an index register or a displacement expression.
736 ParseRegister(IndexReg, Start, End);
737 else if (getParser().ParseExpression(Disp, End)) return 0;
741 if (getLexer().isNot(AsmToken::RBrac))
742 if (getParser().ParseExpression(Disp, End)) return 0;
745 if (getLexer().isNot(AsmToken::RBrac))
746 return ErrorOperand(End, "expected ']' token!");
750 if (Tok.getString().startswith(".")) {
752 const MCExpr *NewDisp;
753 if (ParseIntelDotOperator(Disp, &NewDisp, Err))
754 return ErrorOperand(Tok.getLoc(), Err);
756 Parser.Lex(); // Eat the field.
763 if (!BaseReg && !IndexReg)
764 return X86Operand::CreateMem(Disp, Start, End, Size);
766 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
770 /// ParseIntelMemOperand - Parse intel style memory operand.
771 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg, SMLoc Start) {
772 const AsmToken &Tok = Parser.getTok();
775 unsigned Size = getIntelMemOperandSize(Tok.getString());
778 assert ((Tok.getString() == "PTR" || Tok.getString() == "ptr") &&
779 "Unexpected token!");
783 if (getLexer().is(AsmToken::LBrac))
784 return ParseIntelBracExpression(SegReg, Size);
786 if (!ParseRegister(SegReg, Start, End)) {
787 // Handel SegReg : [ ... ]
788 if (getLexer().isNot(AsmToken::Colon))
789 return ErrorOperand(Start, "Expected ':' token!");
790 Parser.Lex(); // Eat :
791 if (getLexer().isNot(AsmToken::LBrac))
792 return ErrorOperand(Start, "Expected '[' token!");
793 return ParseIntelBracExpression(SegReg, Size);
796 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
797 if (getParser().ParseExpression(Disp, End)) return 0;
798 End = Parser.getTok().getLoc();
800 bool NeedSizeDir = false;
801 if (!Size && isParsingInlineAsm()) {
802 if (const MCSymbolRefExpr *SymRef = dyn_cast<MCSymbolRefExpr>(Disp)) {
803 const MCSymbol &Sym = SymRef->getSymbol();
804 // FIXME: The SemaLookup will fail if the name is anything other then an
806 // FIXME: Pass a valid SMLoc.
807 SemaCallback->LookupInlineAsmIdentifier(Sym.getName(), NULL, Size);
808 NeedSizeDir = Size > 0;
811 if (!isParsingInlineAsm())
812 return X86Operand::CreateMem(Disp, Start, End, Size);
814 // When parsing inline assembly we set the base register to a non-zero value
815 // as we don't know the actual value at this time. This is necessary to
816 // get the matching correct in some cases.
817 return X86Operand::CreateMem(/*SegReg*/0, Disp, /*BaseReg*/1, /*IndexReg*/0,
818 /*Scale*/1, Start, End, Size, NeedSizeDir);
821 /// Parse the '.' operator.
822 bool X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp,
823 const MCExpr **NewDisp,
824 SmallString<64> &Err) {
825 AsmToken Tok = *&Parser.getTok();
826 uint64_t OrigDispVal, DotDispVal;
828 // FIXME: Handle non-constant expressions.
829 if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp)) {
830 OrigDispVal = OrigDisp->getValue();
832 Err = "Non-constant offsets are not supported!";
837 StringRef DotDispStr = Tok.getString().drop_front(1);
839 // .Imm gets lexed as a real.
840 if (Tok.is(AsmToken::Real)) {
842 DotDispStr.getAsInteger(10, DotDisp);
843 DotDispVal = DotDisp.getZExtValue();
844 } else if (Tok.is(AsmToken::Identifier)) {
845 // We should only see an identifier when parsing the original inline asm.
846 // The front-end should rewrite this in terms of immediates.
847 assert (isParsingInlineAsm() && "Unexpected field name!");
850 std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
851 if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second,
853 Err = "Unable to lookup field reference!";
856 DotDispVal = DotDisp;
858 Err = "Unexpected token type!";
862 if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
863 SMLoc Loc = SMLoc::getFromPointer(DotDispStr.data());
864 unsigned Len = DotDispStr.size();
865 unsigned Val = OrigDispVal + DotDispVal;
866 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_DotOperator, Loc, Len,
870 *NewDisp = MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext());
874 /// Parse the 'offset' operator. This operator is used to specify the
875 /// location rather then the content of a variable.
876 X86Operand *X86AsmParser::ParseIntelOffsetOfOperator(SMLoc Start) {
877 SMLoc OffsetOfLoc = Start;
878 Parser.Lex(); // Eat offset.
879 Start = Parser.getTok().getLoc();
880 assert (Parser.getTok().is(AsmToken::Identifier) && "Expected an identifier");
884 if (getParser().ParseExpression(Val, End))
887 End = Parser.getTok().getLoc();
889 // Don't emit the offset operator.
890 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Skip, OffsetOfLoc, 7));
892 // The offset operator will have an 'r' constraint, thus we need to create
893 // register operand to ensure proper matching. Just pick a GPR based on
894 // the size of a pointer.
895 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
896 return X86Operand::CreateReg(RegNo, Start, End, OffsetOfLoc);
899 X86Operand *X86AsmParser::ParseIntelOperand() {
900 SMLoc Start = Parser.getTok().getLoc(), End;
903 const AsmToken &Tok = Parser.getTok();
904 if ((Tok.getString() == "offset" || Tok.getString() == "OFFSET") &&
905 isParsingInlineAsm())
906 return ParseIntelOffsetOfOperator(Start);
909 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
910 getLexer().is(AsmToken::Minus)) {
912 if (!getParser().ParseExpression(Val, End)) {
913 End = Parser.getTok().getLoc();
914 return X86Operand::CreateImm(Val, Start, End);
920 if (!ParseRegister(RegNo, Start, End)) {
921 // If this is a segment register followed by a ':', then this is the start
922 // of a memory reference, otherwise this is a normal register reference.
923 if (getLexer().isNot(AsmToken::Colon))
924 return X86Operand::CreateReg(RegNo, Start, Parser.getTok().getLoc());
926 getParser().Lex(); // Eat the colon.
927 return ParseIntelMemOperand(RegNo, Start);
931 return ParseIntelMemOperand(0, Start);
934 X86Operand *X86AsmParser::ParseATTOperand() {
935 switch (getLexer().getKind()) {
937 // Parse a memory operand with no segment register.
938 return ParseMemOperand(0, Parser.getTok().getLoc());
939 case AsmToken::Percent: {
940 // Read the register.
943 if (ParseRegister(RegNo, Start, End)) return 0;
944 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
945 Error(Start, "%eiz and %riz can only be used as index registers",
946 SMRange(Start, End));
950 // If this is a segment register followed by a ':', then this is the start
951 // of a memory reference, otherwise this is a normal register reference.
952 if (getLexer().isNot(AsmToken::Colon))
953 return X86Operand::CreateReg(RegNo, Start, End);
956 getParser().Lex(); // Eat the colon.
957 return ParseMemOperand(RegNo, Start);
959 case AsmToken::Dollar: {
961 SMLoc Start = Parser.getTok().getLoc(), End;
964 if (getParser().ParseExpression(Val, End))
966 return X86Operand::CreateImm(Val, Start, End);
971 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
972 /// has already been parsed if present.
973 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
975 // We have to disambiguate a parenthesized expression "(4+5)" from the start
976 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
977 // only way to do this without lookahead is to eat the '(' and see what is
979 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
980 if (getLexer().isNot(AsmToken::LParen)) {
982 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
984 // After parsing the base expression we could either have a parenthesized
985 // memory address or not. If not, return now. If so, eat the (.
986 if (getLexer().isNot(AsmToken::LParen)) {
987 // Unless we have a segment register, treat this as an immediate.
989 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
990 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
996 // Okay, we have a '('. We don't know if this is an expression or not, but
997 // so we have to eat the ( to see beyond it.
998 SMLoc LParenLoc = Parser.getTok().getLoc();
999 Parser.Lex(); // Eat the '('.
1001 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
1002 // Nothing to do here, fall into the code below with the '(' part of the
1003 // memory operand consumed.
1007 // It must be an parenthesized expression, parse it now.
1008 if (getParser().ParseParenExpression(Disp, ExprEnd))
1011 // After parsing the base expression we could either have a parenthesized
1012 // memory address or not. If not, return now. If so, eat the (.
1013 if (getLexer().isNot(AsmToken::LParen)) {
1014 // Unless we have a segment register, treat this as an immediate.
1016 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
1017 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1025 // If we reached here, then we just ate the ( of the memory operand. Process
1026 // the rest of the memory operand.
1027 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
1030 if (getLexer().is(AsmToken::Percent)) {
1031 SMLoc StartLoc, EndLoc;
1032 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
1033 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
1034 Error(StartLoc, "eiz and riz can only be used as index registers",
1035 SMRange(StartLoc, EndLoc));
1040 if (getLexer().is(AsmToken::Comma)) {
1041 Parser.Lex(); // Eat the comma.
1042 IndexLoc = Parser.getTok().getLoc();
1044 // Following the comma we should have either an index register, or a scale
1045 // value. We don't support the later form, but we want to parse it
1048 // Not that even though it would be completely consistent to support syntax
1049 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
1050 if (getLexer().is(AsmToken::Percent)) {
1052 if (ParseRegister(IndexReg, L, L)) return 0;
1054 if (getLexer().isNot(AsmToken::RParen)) {
1055 // Parse the scale amount:
1056 // ::= ',' [scale-expression]
1057 if (getLexer().isNot(AsmToken::Comma)) {
1058 Error(Parser.getTok().getLoc(),
1059 "expected comma in scale expression");
1062 Parser.Lex(); // Eat the comma.
1064 if (getLexer().isNot(AsmToken::RParen)) {
1065 SMLoc Loc = Parser.getTok().getLoc();
1068 if (getParser().ParseAbsoluteExpression(ScaleVal)){
1069 Error(Loc, "expected scale expression");
1073 // Validate the scale amount.
1074 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
1075 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
1078 Scale = (unsigned)ScaleVal;
1081 } else if (getLexer().isNot(AsmToken::RParen)) {
1082 // A scale amount without an index is ignored.
1084 SMLoc Loc = Parser.getTok().getLoc();
1087 if (getParser().ParseAbsoluteExpression(Value))
1091 Warning(Loc, "scale factor without index register is ignored");
1096 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1097 if (getLexer().isNot(AsmToken::RParen)) {
1098 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1101 SMLoc MemEnd = Parser.getTok().getLoc();
1102 Parser.Lex(); // Eat the ')'.
1104 // If we have both a base register and an index register make sure they are
1105 // both 64-bit or 32-bit registers.
1106 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1107 if (BaseReg != 0 && IndexReg != 0) {
1108 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1109 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1110 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1111 IndexReg != X86::RIZ) {
1112 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1115 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1116 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1117 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1118 IndexReg != X86::EIZ){
1119 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1124 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1129 ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
1130 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1132 StringRef PatchedName = Name;
1134 // FIXME: Hack to recognize setneb as setne.
1135 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1136 PatchedName != "setb" && PatchedName != "setnb")
1137 PatchedName = PatchedName.substr(0, Name.size()-1);
1139 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1140 const MCExpr *ExtraImmOp = 0;
1141 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1142 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1143 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1144 bool IsVCMP = PatchedName[0] == 'v';
1145 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1146 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1147 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1151 .Case("unord", 0x03)
1156 /* AVX only from here */
1157 .Case("eq_uq", 0x08)
1160 .Case("false", 0x0B)
1161 .Case("neq_oq", 0x0C)
1165 .Case("eq_os", 0x10)
1166 .Case("lt_oq", 0x11)
1167 .Case("le_oq", 0x12)
1168 .Case("unord_s", 0x13)
1169 .Case("neq_us", 0x14)
1170 .Case("nlt_uq", 0x15)
1171 .Case("nle_uq", 0x16)
1172 .Case("ord_s", 0x17)
1173 .Case("eq_us", 0x18)
1174 .Case("nge_uq", 0x19)
1175 .Case("ngt_uq", 0x1A)
1176 .Case("false_os", 0x1B)
1177 .Case("neq_os", 0x1C)
1178 .Case("ge_oq", 0x1D)
1179 .Case("gt_oq", 0x1E)
1180 .Case("true_us", 0x1F)
1182 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1183 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1184 getParser().getContext());
1185 if (PatchedName.endswith("ss")) {
1186 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1187 } else if (PatchedName.endswith("sd")) {
1188 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1189 } else if (PatchedName.endswith("ps")) {
1190 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1192 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1193 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1198 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1200 if (ExtraImmOp && !isParsingIntelSyntax())
1201 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1203 // Determine whether this is an instruction prefix.
1205 Name == "lock" || Name == "rep" ||
1206 Name == "repe" || Name == "repz" ||
1207 Name == "repne" || Name == "repnz" ||
1208 Name == "rex64" || Name == "data16";
1211 // This does the actual operand parsing. Don't parse any more if we have a
1212 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1213 // just want to parse the "lock" as the first instruction and the "incl" as
1215 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1217 // Parse '*' modifier.
1218 if (getLexer().is(AsmToken::Star)) {
1219 SMLoc Loc = Parser.getTok().getLoc();
1220 Operands.push_back(X86Operand::CreateToken("*", Loc));
1221 Parser.Lex(); // Eat the star.
1224 // Read the first operand.
1225 if (X86Operand *Op = ParseOperand())
1226 Operands.push_back(Op);
1228 Parser.EatToEndOfStatement();
1232 while (getLexer().is(AsmToken::Comma)) {
1233 Parser.Lex(); // Eat the comma.
1235 // Parse and remember the operand.
1236 if (X86Operand *Op = ParseOperand())
1237 Operands.push_back(Op);
1239 Parser.EatToEndOfStatement();
1244 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1245 SMLoc Loc = getLexer().getLoc();
1246 Parser.EatToEndOfStatement();
1247 return Error(Loc, "unexpected token in argument list");
1251 if (getLexer().is(AsmToken::EndOfStatement))
1252 Parser.Lex(); // Consume the EndOfStatement
1253 else if (isPrefix && getLexer().is(AsmToken::Slash))
1254 Parser.Lex(); // Consume the prefix separator Slash
1256 if (ExtraImmOp && isParsingIntelSyntax())
1257 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1259 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1260 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1261 // documented form in various unofficial manuals, so a lot of code uses it.
1262 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1263 Operands.size() == 3) {
1264 X86Operand &Op = *(X86Operand*)Operands.back();
1265 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1266 isa<MCConstantExpr>(Op.Mem.Disp) &&
1267 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1268 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1269 SMLoc Loc = Op.getEndLoc();
1270 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1274 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1275 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1276 Operands.size() == 3) {
1277 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1278 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1279 isa<MCConstantExpr>(Op.Mem.Disp) &&
1280 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1281 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1282 SMLoc Loc = Op.getEndLoc();
1283 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1287 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1288 if (Name.startswith("ins") && Operands.size() == 3 &&
1289 (Name == "insb" || Name == "insw" || Name == "insl")) {
1290 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1291 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1292 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1293 Operands.pop_back();
1294 Operands.pop_back();
1300 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1301 if (Name.startswith("outs") && Operands.size() == 3 &&
1302 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1303 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1304 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1305 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1306 Operands.pop_back();
1307 Operands.pop_back();
1313 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1314 if (Name.startswith("movs") && Operands.size() == 3 &&
1315 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1316 (is64BitMode() && Name == "movsq"))) {
1317 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1318 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1319 if (isSrcOp(Op) && isDstOp(Op2)) {
1320 Operands.pop_back();
1321 Operands.pop_back();
1326 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1327 if (Name.startswith("lods") && Operands.size() == 3 &&
1328 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1329 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1330 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1331 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1332 if (isSrcOp(*Op1) && Op2->isReg()) {
1334 unsigned reg = Op2->getReg();
1335 bool isLods = Name == "lods";
1336 if (reg == X86::AL && (isLods || Name == "lodsb"))
1338 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1340 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1342 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1347 Operands.pop_back();
1348 Operands.pop_back();
1352 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1356 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1357 if (Name.startswith("stos") && Operands.size() == 3 &&
1358 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1359 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1360 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1361 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1362 if (isDstOp(*Op2) && Op1->isReg()) {
1364 unsigned reg = Op1->getReg();
1365 bool isStos = Name == "stos";
1366 if (reg == X86::AL && (isStos || Name == "stosb"))
1368 else if (reg == X86::AX && (isStos || Name == "stosw"))
1370 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1372 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1377 Operands.pop_back();
1378 Operands.pop_back();
1382 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1387 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1389 if ((Name.startswith("shr") || Name.startswith("sar") ||
1390 Name.startswith("shl") || Name.startswith("sal") ||
1391 Name.startswith("rcl") || Name.startswith("rcr") ||
1392 Name.startswith("rol") || Name.startswith("ror")) &&
1393 Operands.size() == 3) {
1394 if (isParsingIntelSyntax()) {
1396 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1397 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1398 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1400 Operands.pop_back();
1403 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1404 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1405 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1407 Operands.erase(Operands.begin() + 1);
1412 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1413 // instalias with an immediate operand yet.
1414 if (Name == "int" && Operands.size() == 2) {
1415 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1416 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1417 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1419 Operands.erase(Operands.begin() + 1);
1420 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1428 processInstruction(MCInst &Inst,
1429 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1430 switch (Inst.getOpcode()) {
1431 default: return false;
1432 case X86::AND16i16: {
1433 if (!Inst.getOperand(0).isImm() ||
1434 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1438 TmpInst.setOpcode(X86::AND16ri8);
1439 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1440 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1441 TmpInst.addOperand(Inst.getOperand(0));
1445 case X86::AND32i32: {
1446 if (!Inst.getOperand(0).isImm() ||
1447 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1451 TmpInst.setOpcode(X86::AND32ri8);
1452 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1453 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1454 TmpInst.addOperand(Inst.getOperand(0));
1458 case X86::AND64i32: {
1459 if (!Inst.getOperand(0).isImm() ||
1460 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1464 TmpInst.setOpcode(X86::AND64ri8);
1465 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1466 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1467 TmpInst.addOperand(Inst.getOperand(0));
1471 case X86::XOR16i16: {
1472 if (!Inst.getOperand(0).isImm() ||
1473 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1477 TmpInst.setOpcode(X86::XOR16ri8);
1478 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1479 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1480 TmpInst.addOperand(Inst.getOperand(0));
1484 case X86::XOR32i32: {
1485 if (!Inst.getOperand(0).isImm() ||
1486 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1490 TmpInst.setOpcode(X86::XOR32ri8);
1491 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1492 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1493 TmpInst.addOperand(Inst.getOperand(0));
1497 case X86::XOR64i32: {
1498 if (!Inst.getOperand(0).isImm() ||
1499 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1503 TmpInst.setOpcode(X86::XOR64ri8);
1504 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1505 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1506 TmpInst.addOperand(Inst.getOperand(0));
1510 case X86::OR16i16: {
1511 if (!Inst.getOperand(0).isImm() ||
1512 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1516 TmpInst.setOpcode(X86::OR16ri8);
1517 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1518 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1519 TmpInst.addOperand(Inst.getOperand(0));
1523 case X86::OR32i32: {
1524 if (!Inst.getOperand(0).isImm() ||
1525 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1529 TmpInst.setOpcode(X86::OR32ri8);
1530 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1531 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1532 TmpInst.addOperand(Inst.getOperand(0));
1536 case X86::OR64i32: {
1537 if (!Inst.getOperand(0).isImm() ||
1538 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1542 TmpInst.setOpcode(X86::OR64ri8);
1543 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1544 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1545 TmpInst.addOperand(Inst.getOperand(0));
1549 case X86::CMP16i16: {
1550 if (!Inst.getOperand(0).isImm() ||
1551 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1555 TmpInst.setOpcode(X86::CMP16ri8);
1556 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1557 TmpInst.addOperand(Inst.getOperand(0));
1561 case X86::CMP32i32: {
1562 if (!Inst.getOperand(0).isImm() ||
1563 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1567 TmpInst.setOpcode(X86::CMP32ri8);
1568 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1569 TmpInst.addOperand(Inst.getOperand(0));
1573 case X86::CMP64i32: {
1574 if (!Inst.getOperand(0).isImm() ||
1575 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1579 TmpInst.setOpcode(X86::CMP64ri8);
1580 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1581 TmpInst.addOperand(Inst.getOperand(0));
1585 case X86::ADD16i16: {
1586 if (!Inst.getOperand(0).isImm() ||
1587 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1591 TmpInst.setOpcode(X86::ADD16ri8);
1592 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1593 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1594 TmpInst.addOperand(Inst.getOperand(0));
1598 case X86::ADD32i32: {
1599 if (!Inst.getOperand(0).isImm() ||
1600 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1604 TmpInst.setOpcode(X86::ADD32ri8);
1605 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1606 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1607 TmpInst.addOperand(Inst.getOperand(0));
1611 case X86::ADD64i32: {
1612 if (!Inst.getOperand(0).isImm() ||
1613 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1617 TmpInst.setOpcode(X86::ADD64ri8);
1618 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1619 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1620 TmpInst.addOperand(Inst.getOperand(0));
1624 case X86::SUB16i16: {
1625 if (!Inst.getOperand(0).isImm() ||
1626 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1630 TmpInst.setOpcode(X86::SUB16ri8);
1631 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1632 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1633 TmpInst.addOperand(Inst.getOperand(0));
1637 case X86::SUB32i32: {
1638 if (!Inst.getOperand(0).isImm() ||
1639 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1643 TmpInst.setOpcode(X86::SUB32ri8);
1644 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1645 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1646 TmpInst.addOperand(Inst.getOperand(0));
1650 case X86::SUB64i32: {
1651 if (!Inst.getOperand(0).isImm() ||
1652 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1656 TmpInst.setOpcode(X86::SUB64ri8);
1657 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1658 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1659 TmpInst.addOperand(Inst.getOperand(0));
1667 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1668 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1669 MCStreamer &Out, unsigned &ErrorInfo,
1670 bool MatchingInlineAsm) {
1671 assert(!Operands.empty() && "Unexpect empty operand list!");
1672 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1673 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1674 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
1676 // First, handle aliases that expand to multiple instructions.
1677 // FIXME: This should be replaced with a real .td file alias mechanism.
1678 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
1680 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1681 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1682 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1683 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1685 Inst.setOpcode(X86::WAIT);
1687 if (!MatchingInlineAsm)
1688 Out.EmitInstruction(Inst);
1691 StringSwitch<const char*>(Op->getToken())
1692 .Case("finit", "fninit")
1693 .Case("fsave", "fnsave")
1694 .Case("fstcw", "fnstcw")
1695 .Case("fstcww", "fnstcw")
1696 .Case("fstenv", "fnstenv")
1697 .Case("fstsw", "fnstsw")
1698 .Case("fstsww", "fnstsw")
1699 .Case("fclex", "fnclex")
1701 assert(Repl && "Unknown wait-prefixed instruction");
1703 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1706 bool WasOriginallyInvalidOperand = false;
1709 // First, try a direct match.
1710 switch (MatchInstructionImpl(Operands, Inst,
1711 ErrorInfo, MatchingInlineAsm,
1712 isParsingIntelSyntax())) {
1715 // Some instructions need post-processing to, for example, tweak which
1716 // encoding is selected. Loop on it while changes happen so the
1717 // individual transformations can chain off each other.
1718 if (!MatchingInlineAsm)
1719 while (processInstruction(Inst, Operands))
1723 if (!MatchingInlineAsm)
1724 Out.EmitInstruction(Inst);
1725 Opcode = Inst.getOpcode();
1727 case Match_MissingFeature:
1728 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1729 EmptyRanges, MatchingInlineAsm);
1731 case Match_InvalidOperand:
1732 WasOriginallyInvalidOperand = true;
1734 case Match_MnemonicFail:
1738 // FIXME: Ideally, we would only attempt suffix matches for things which are
1739 // valid prefixes, and we could just infer the right unambiguous
1740 // type. However, that requires substantially more matcher support than the
1743 // Change the operand to point to a temporary token.
1744 StringRef Base = Op->getToken();
1745 SmallString<16> Tmp;
1748 Op->setTokenValue(Tmp.str());
1750 // If this instruction starts with an 'f', then it is a floating point stack
1751 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1752 // 80-bit floating point, which use the suffixes s,l,t respectively.
1754 // Otherwise, we assume that this may be an integer instruction, which comes
1755 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1756 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1758 // Check for the various suffix matches.
1759 Tmp[Base.size()] = Suffixes[0];
1760 unsigned ErrorInfoIgnore;
1761 unsigned Match1, Match2, Match3, Match4;
1763 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1764 isParsingIntelSyntax());
1765 Tmp[Base.size()] = Suffixes[1];
1766 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1767 isParsingIntelSyntax());
1768 Tmp[Base.size()] = Suffixes[2];
1769 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1770 isParsingIntelSyntax());
1771 Tmp[Base.size()] = Suffixes[3];
1772 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1773 isParsingIntelSyntax());
1775 // Restore the old token.
1776 Op->setTokenValue(Base);
1778 // If exactly one matched, then we treat that as a successful match (and the
1779 // instruction will already have been filled in correctly, since the failing
1780 // matches won't have modified it).
1781 unsigned NumSuccessfulMatches =
1782 (Match1 == Match_Success) + (Match2 == Match_Success) +
1783 (Match3 == Match_Success) + (Match4 == Match_Success);
1784 if (NumSuccessfulMatches == 1) {
1786 if (!MatchingInlineAsm)
1787 Out.EmitInstruction(Inst);
1788 Opcode = Inst.getOpcode();
1792 // Otherwise, the match failed, try to produce a decent error message.
1794 // If we had multiple suffix matches, then identify this as an ambiguous
1796 if (NumSuccessfulMatches > 1) {
1798 unsigned NumMatches = 0;
1799 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1800 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1801 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1802 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1804 SmallString<126> Msg;
1805 raw_svector_ostream OS(Msg);
1806 OS << "ambiguous instructions require an explicit suffix (could be ";
1807 for (unsigned i = 0; i != NumMatches; ++i) {
1810 if (i + 1 == NumMatches)
1812 OS << "'" << Base << MatchChars[i] << "'";
1815 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
1819 // Okay, we know that none of the variants matched successfully.
1821 // If all of the instructions reported an invalid mnemonic, then the original
1822 // mnemonic was invalid.
1823 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1824 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1825 if (!WasOriginallyInvalidOperand) {
1826 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
1828 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1829 Ranges, MatchingInlineAsm);
1832 // Recover location info for the operand if we know which was the problem.
1833 if (ErrorInfo != ~0U) {
1834 if (ErrorInfo >= Operands.size())
1835 return Error(IDLoc, "too few operands for instruction",
1836 EmptyRanges, MatchingInlineAsm);
1838 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
1839 if (Operand->getStartLoc().isValid()) {
1840 SMRange OperandRange = Operand->getLocRange();
1841 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1842 OperandRange, MatchingInlineAsm);
1846 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1850 // If one instruction matched with a missing feature, report this as a
1852 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1853 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1854 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1855 EmptyRanges, MatchingInlineAsm);
1859 // If one instruction matched with an invalid operand, report this as an
1861 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1862 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1863 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1868 // If all of these were an outright failure, report it in a useless way.
1869 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
1870 EmptyRanges, MatchingInlineAsm);
1875 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1876 StringRef IDVal = DirectiveID.getIdentifier();
1877 if (IDVal == ".word")
1878 return ParseDirectiveWord(2, DirectiveID.getLoc());
1879 else if (IDVal.startswith(".code"))
1880 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1881 else if (IDVal.startswith(".att_syntax")) {
1882 getParser().setAssemblerDialect(0);
1884 } else if (IDVal.startswith(".intel_syntax")) {
1885 getParser().setAssemblerDialect(1);
1886 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1887 if(Parser.getTok().getString() == "noprefix") {
1888 // FIXME : Handle noprefix
1898 /// ParseDirectiveWord
1899 /// ::= .word [ expression (, expression)* ]
1900 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1901 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1903 const MCExpr *Value;
1904 if (getParser().ParseExpression(Value))
1907 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1909 if (getLexer().is(AsmToken::EndOfStatement))
1912 // FIXME: Improve diagnostic.
1913 if (getLexer().isNot(AsmToken::Comma))
1914 return Error(L, "unexpected token in directive");
1923 /// ParseDirectiveCode
1924 /// ::= .code32 | .code64
1925 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1926 if (IDVal == ".code32") {
1928 if (is64BitMode()) {
1930 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1932 } else if (IDVal == ".code64") {
1934 if (!is64BitMode()) {
1936 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1939 return Error(L, "unexpected directive " + IDVal);
1946 extern "C" void LLVMInitializeX86AsmLexer();
1948 // Force static initialization.
1949 extern "C" void LLVMInitializeX86AsmParser() {
1950 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1951 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1952 LLVMInitializeX86AsmLexer();
1955 #define GET_REGISTER_MATCHER
1956 #define GET_MATCHER_IMPLEMENTATION
1957 #include "X86GenAsmMatcher.inc"