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;
190 X86Operand(KindTy K, SMLoc Start, SMLoc End)
191 : Kind(K), StartLoc(Start), EndLoc(End) {}
193 /// getStartLoc - Get the location of the first token of this operand.
194 SMLoc getStartLoc() const { return StartLoc; }
195 /// getEndLoc - Get the location of the last token of this operand.
196 SMLoc getEndLoc() const { return EndLoc; }
197 /// getLocRange - Get the range between the first and last token of this
199 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
200 /// getOffsetOfLoc - Get the location of the offset operator.
201 SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
203 virtual void print(raw_ostream &OS) const {}
205 StringRef getToken() const {
206 assert(Kind == Token && "Invalid access!");
207 return StringRef(Tok.Data, Tok.Length);
209 void setTokenValue(StringRef Value) {
210 assert(Kind == Token && "Invalid access!");
211 Tok.Data = Value.data();
212 Tok.Length = Value.size();
215 unsigned getReg() const {
216 assert(Kind == Register && "Invalid access!");
220 const MCExpr *getImm() const {
221 assert(Kind == Immediate && "Invalid access!");
225 const MCExpr *getMemDisp() const {
226 assert(Kind == Memory && "Invalid access!");
229 unsigned getMemSegReg() const {
230 assert(Kind == Memory && "Invalid access!");
233 unsigned getMemBaseReg() const {
234 assert(Kind == Memory && "Invalid access!");
237 unsigned getMemIndexReg() const {
238 assert(Kind == Memory && "Invalid access!");
241 unsigned getMemScale() const {
242 assert(Kind == Memory && "Invalid access!");
246 bool isToken() const {return Kind == Token; }
248 bool isImm() const { return Kind == Immediate; }
250 bool isImmSExti16i8() const {
254 // If this isn't a constant expr, just assume it fits and let relaxation
256 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
260 // Otherwise, check the value is in a range that makes sense for this
262 return isImmSExti16i8Value(CE->getValue());
264 bool isImmSExti32i8() const {
268 // If this isn't a constant expr, just assume it fits and let relaxation
270 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
274 // Otherwise, check the value is in a range that makes sense for this
276 return isImmSExti32i8Value(CE->getValue());
278 bool isImmZExtu32u8() const {
282 // If this isn't a constant expr, just assume it fits and let relaxation
284 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
288 // Otherwise, check the value is in a range that makes sense for this
290 return isImmZExtu32u8Value(CE->getValue());
292 bool isImmSExti64i8() const {
296 // If this isn't a constant expr, just assume it fits and let relaxation
298 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
302 // Otherwise, check the value is in a range that makes sense for this
304 return isImmSExti64i8Value(CE->getValue());
306 bool isImmSExti64i32() const {
310 // If this isn't a constant expr, just assume it fits and let relaxation
312 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
316 // Otherwise, check the value is in a range that makes sense for this
318 return isImmSExti64i32Value(CE->getValue());
321 unsigned getMemSize() const {
322 assert(Kind == Memory && "Invalid access!");
326 bool isOffsetOf() const {
327 assert(Kind == Memory && "Invalid access!");
331 bool needSizeDirective() const {
332 assert(Kind == Memory && "Invalid access!");
333 return Mem.NeedSizeDir;
336 bool isMem() const { return Kind == Memory; }
337 bool isMem8() const {
338 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
340 bool isMem16() const {
341 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
343 bool isMem32() const {
344 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
346 bool isMem64() const {
347 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
349 bool isMem80() const {
350 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
352 bool isMem128() const {
353 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
355 bool isMem256() const {
356 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
359 bool isMemVX32() const {
360 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
361 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
363 bool isMemVY32() const {
364 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
365 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
367 bool isMemVX64() const {
368 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
369 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
371 bool isMemVY64() const {
372 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
373 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
376 bool isAbsMem() const {
377 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
378 !getMemIndexReg() && getMemScale() == 1;
381 bool isReg() const { return Kind == Register; }
383 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
384 // Add as immediates when possible.
385 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
386 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
388 Inst.addOperand(MCOperand::CreateExpr(Expr));
391 void addRegOperands(MCInst &Inst, unsigned N) const {
392 assert(N == 1 && "Invalid number of operands!");
393 Inst.addOperand(MCOperand::CreateReg(getReg()));
396 void addImmOperands(MCInst &Inst, unsigned N) const {
397 assert(N == 1 && "Invalid number of operands!");
398 addExpr(Inst, getImm());
401 void addMem8Operands(MCInst &Inst, unsigned N) const {
402 addMemOperands(Inst, N);
404 void addMem16Operands(MCInst &Inst, unsigned N) const {
405 addMemOperands(Inst, N);
407 void addMem32Operands(MCInst &Inst, unsigned N) const {
408 addMemOperands(Inst, N);
410 void addMem64Operands(MCInst &Inst, unsigned N) const {
411 addMemOperands(Inst, N);
413 void addMem80Operands(MCInst &Inst, unsigned N) const {
414 addMemOperands(Inst, N);
416 void addMem128Operands(MCInst &Inst, unsigned N) const {
417 addMemOperands(Inst, N);
419 void addMem256Operands(MCInst &Inst, unsigned N) const {
420 addMemOperands(Inst, N);
422 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
423 addMemOperands(Inst, N);
425 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
426 addMemOperands(Inst, N);
428 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
429 addMemOperands(Inst, N);
431 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
432 addMemOperands(Inst, N);
435 void addMemOperands(MCInst &Inst, unsigned N) const {
436 assert((N == 5) && "Invalid number of operands!");
437 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
438 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
439 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
440 addExpr(Inst, getMemDisp());
441 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
444 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
445 assert((N == 1) && "Invalid number of operands!");
446 // Add as immediates when possible.
447 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
448 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
450 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
453 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
454 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
455 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
456 Res->Tok.Data = Str.data();
457 Res->Tok.Length = Str.size();
461 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
462 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
463 Res->Reg.RegNo = RegNo;
467 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
468 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
473 /// Create an absolute memory operand.
474 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
475 SMLoc EndLoc, SMLoc OffsetOfLoc = SMLoc(),
476 unsigned Size = 0, bool OffsetOf = false,
477 bool NeedSizeDir = false){
478 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
480 Res->Mem.Disp = Disp;
481 Res->Mem.BaseReg = 0;
482 Res->Mem.IndexReg = 0;
484 Res->Mem.Size = Size;
485 Res->Mem.OffsetOf = OffsetOf;
486 Res->OffsetOfLoc = OffsetOfLoc;
487 Res->Mem.NeedSizeDir = NeedSizeDir;
491 /// Create a generalized memory operand.
492 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
493 unsigned BaseReg, unsigned IndexReg,
494 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
495 SMLoc OffsetOfLoc = SMLoc(), unsigned Size = 0,
496 bool OffsetOf = false, bool NeedSizeDir = false){
497 // We should never just have a displacement, that should be parsed as an
498 // absolute memory operand.
499 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
501 // The scale should always be one of {1,2,4,8}.
502 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
504 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
505 Res->Mem.SegReg = SegReg;
506 Res->Mem.Disp = Disp;
507 Res->Mem.BaseReg = BaseReg;
508 Res->Mem.IndexReg = IndexReg;
509 Res->Mem.Scale = Scale;
510 Res->Mem.Size = Size;
511 Res->Mem.OffsetOf = OffsetOf;
512 Res->OffsetOfLoc = OffsetOfLoc;
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 SMLoc Start = Parser.getTok().getLoc(), End, OffsetOfLoc;
672 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
673 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
676 if (getLexer().isNot(AsmToken::LBrac))
677 return ErrorOperand(Start, "Expected '[' token!");
680 if (getLexer().is(AsmToken::Identifier)) {
682 if (ParseRegister(BaseReg, Start, End)) {
683 // Handle '[' 'symbol' ']'
684 if (getParser().ParseExpression(Disp, End)) return 0;
685 if (getLexer().isNot(AsmToken::RBrac))
686 return ErrorOperand(Start, "Expected ']' token!");
688 return X86Operand::CreateMem(Disp, Start, End, OffsetOfLoc, Size);
690 } else if (getLexer().is(AsmToken::Integer)) {
691 int64_t Val = Parser.getTok().getIntVal();
693 SMLoc Loc = Parser.getTok().getLoc();
694 if (getLexer().is(AsmToken::RBrac)) {
695 // Handle '[' number ']'
697 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
699 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
700 Start, End, OffsetOfLoc, Size);
701 return X86Operand::CreateMem(Disp, Start, End, OffsetOfLoc, Size);
702 } else if (getLexer().is(AsmToken::Star)) {
703 // Handle '[' Scale*IndexReg ']'
705 SMLoc IdxRegLoc = Parser.getTok().getLoc();
706 if (ParseRegister(IndexReg, IdxRegLoc, End))
707 return ErrorOperand(IdxRegLoc, "Expected register");
710 return ErrorOperand(Loc, "Unexpected token");
713 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
714 bool isPlus = getLexer().is(AsmToken::Plus);
716 SMLoc PlusLoc = Parser.getTok().getLoc();
717 if (getLexer().is(AsmToken::Integer)) {
718 int64_t Val = Parser.getTok().getIntVal();
720 if (getLexer().is(AsmToken::Star)) {
722 SMLoc IdxRegLoc = Parser.getTok().getLoc();
723 if (ParseRegister(IndexReg, IdxRegLoc, End))
724 return ErrorOperand(IdxRegLoc, "Expected register");
726 } else if (getLexer().is(AsmToken::RBrac)) {
727 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
728 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
730 return ErrorOperand(PlusLoc, "unexpected token after +");
731 } else if (getLexer().is(AsmToken::Identifier)) {
732 // This could be an index register or a displacement expression.
733 End = Parser.getTok().getLoc();
735 ParseRegister(IndexReg, Start, End);
736 else if (getParser().ParseExpression(Disp, End)) return 0;
740 if (getLexer().isNot(AsmToken::RBrac))
741 if (getParser().ParseExpression(Disp, End)) return 0;
743 End = Parser.getTok().getLoc();
744 if (getLexer().isNot(AsmToken::RBrac))
745 return ErrorOperand(End, "expected ']' token!");
747 End = Parser.getTok().getLoc();
750 if (!BaseReg && !IndexReg)
751 return X86Operand::CreateMem(Disp, Start, End, OffsetOfLoc, Size);
753 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
754 Start, End, OffsetOfLoc, Size);
757 /// ParseIntelMemOperand - Parse intel style memory operand.
758 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg, SMLoc Start) {
759 const AsmToken &Tok = Parser.getTok();
760 SMLoc End, OffsetOfLoc;
762 unsigned Size = getIntelMemOperandSize(Tok.getString());
765 assert ((Tok.getString() == "PTR" || Tok.getString() == "ptr") &&
766 "Unexpected token!");
770 // Parse the 'offset' operator. This operator is used to specify the
771 // location rather then the content of a variable.
772 bool OffsetOf = false;
773 if(isParsingInlineAsm() && (Tok.getString() == "offset" ||
774 Tok.getString() == "OFFSET")) {
776 OffsetOfLoc = Parser.getTok().getLoc();
777 Parser.Lex(); // Eat offset.
780 if (getLexer().is(AsmToken::LBrac)) {
781 assert (!OffsetOf && "Unexpected offset operator!");
782 return ParseIntelBracExpression(SegReg, Size);
785 if (!ParseRegister(SegReg, Start, End)) {
786 assert (!OffsetOf && "Unexpected offset operator!");
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, OffsetOfLoc, 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, OffsetOfLoc, Size,
819 OffsetOf, NeedSizeDir);
822 X86Operand *X86AsmParser::ParseIntelOperand() {
823 SMLoc Start = Parser.getTok().getLoc(), End;
826 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
827 getLexer().is(AsmToken::Minus)) {
829 if (!getParser().ParseExpression(Val, End)) {
830 End = Parser.getTok().getLoc();
831 return X86Operand::CreateImm(Val, Start, End);
837 if (!ParseRegister(RegNo, Start, End)) {
838 // If this is a segment register followed by a ':', then this is the start
839 // of a memory reference, otherwise this is a normal register reference.
840 if (getLexer().isNot(AsmToken::Colon))
841 return X86Operand::CreateReg(RegNo, Start, Parser.getTok().getLoc());
843 getParser().Lex(); // Eat the colon.
844 return ParseIntelMemOperand(RegNo, Start);
848 return ParseIntelMemOperand(0, Start);
851 X86Operand *X86AsmParser::ParseATTOperand() {
852 switch (getLexer().getKind()) {
854 // Parse a memory operand with no segment register.
855 return ParseMemOperand(0, Parser.getTok().getLoc());
856 case AsmToken::Percent: {
857 // Read the register.
860 if (ParseRegister(RegNo, Start, End)) return 0;
861 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
862 Error(Start, "%eiz and %riz can only be used as index registers",
863 SMRange(Start, End));
867 // If this is a segment register followed by a ':', then this is the start
868 // of a memory reference, otherwise this is a normal register reference.
869 if (getLexer().isNot(AsmToken::Colon))
870 return X86Operand::CreateReg(RegNo, Start, End);
873 getParser().Lex(); // Eat the colon.
874 return ParseMemOperand(RegNo, Start);
876 case AsmToken::Dollar: {
878 SMLoc Start = Parser.getTok().getLoc(), End;
881 if (getParser().ParseExpression(Val, End))
883 return X86Operand::CreateImm(Val, Start, End);
888 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
889 /// has already been parsed if present.
890 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
892 // We have to disambiguate a parenthesized expression "(4+5)" from the start
893 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
894 // only way to do this without lookahead is to eat the '(' and see what is
896 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
897 if (getLexer().isNot(AsmToken::LParen)) {
899 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
901 // After parsing the base expression we could either have a parenthesized
902 // memory address or not. If not, return now. If so, eat the (.
903 if (getLexer().isNot(AsmToken::LParen)) {
904 // Unless we have a segment register, treat this as an immediate.
906 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
907 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
913 // Okay, we have a '('. We don't know if this is an expression or not, but
914 // so we have to eat the ( to see beyond it.
915 SMLoc LParenLoc = Parser.getTok().getLoc();
916 Parser.Lex(); // Eat the '('.
918 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
919 // Nothing to do here, fall into the code below with the '(' part of the
920 // memory operand consumed.
924 // It must be an parenthesized expression, parse it now.
925 if (getParser().ParseParenExpression(Disp, ExprEnd))
928 // After parsing the base expression we could either have a parenthesized
929 // memory address or not. If not, return now. If so, eat the (.
930 if (getLexer().isNot(AsmToken::LParen)) {
931 // Unless we have a segment register, treat this as an immediate.
933 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
934 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
942 // If we reached here, then we just ate the ( of the memory operand. Process
943 // the rest of the memory operand.
944 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
947 if (getLexer().is(AsmToken::Percent)) {
948 SMLoc StartLoc, EndLoc;
949 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
950 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
951 Error(StartLoc, "eiz and riz can only be used as index registers",
952 SMRange(StartLoc, EndLoc));
957 if (getLexer().is(AsmToken::Comma)) {
958 Parser.Lex(); // Eat the comma.
959 IndexLoc = Parser.getTok().getLoc();
961 // Following the comma we should have either an index register, or a scale
962 // value. We don't support the later form, but we want to parse it
965 // Not that even though it would be completely consistent to support syntax
966 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
967 if (getLexer().is(AsmToken::Percent)) {
969 if (ParseRegister(IndexReg, L, L)) return 0;
971 if (getLexer().isNot(AsmToken::RParen)) {
972 // Parse the scale amount:
973 // ::= ',' [scale-expression]
974 if (getLexer().isNot(AsmToken::Comma)) {
975 Error(Parser.getTok().getLoc(),
976 "expected comma in scale expression");
979 Parser.Lex(); // Eat the comma.
981 if (getLexer().isNot(AsmToken::RParen)) {
982 SMLoc Loc = Parser.getTok().getLoc();
985 if (getParser().ParseAbsoluteExpression(ScaleVal)){
986 Error(Loc, "expected scale expression");
990 // Validate the scale amount.
991 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
992 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
995 Scale = (unsigned)ScaleVal;
998 } else if (getLexer().isNot(AsmToken::RParen)) {
999 // A scale amount without an index is ignored.
1001 SMLoc Loc = Parser.getTok().getLoc();
1004 if (getParser().ParseAbsoluteExpression(Value))
1008 Warning(Loc, "scale factor without index register is ignored");
1013 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1014 if (getLexer().isNot(AsmToken::RParen)) {
1015 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1018 SMLoc MemEnd = Parser.getTok().getLoc();
1019 Parser.Lex(); // Eat the ')'.
1021 // If we have both a base register and an index register make sure they are
1022 // both 64-bit or 32-bit registers.
1023 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1024 if (BaseReg != 0 && IndexReg != 0) {
1025 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1026 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1027 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1028 IndexReg != X86::RIZ) {
1029 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1032 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1033 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1034 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1035 IndexReg != X86::EIZ){
1036 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1041 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1046 ParseInstruction(StringRef Name, SMLoc NameLoc,
1047 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1048 StringRef PatchedName = Name;
1050 // FIXME: Hack to recognize setneb as setne.
1051 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1052 PatchedName != "setb" && PatchedName != "setnb")
1053 PatchedName = PatchedName.substr(0, Name.size()-1);
1055 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1056 const MCExpr *ExtraImmOp = 0;
1057 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1058 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1059 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1060 bool IsVCMP = PatchedName[0] == 'v';
1061 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1062 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1063 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1067 .Case("unord", 0x03)
1072 /* AVX only from here */
1073 .Case("eq_uq", 0x08)
1076 .Case("false", 0x0B)
1077 .Case("neq_oq", 0x0C)
1081 .Case("eq_os", 0x10)
1082 .Case("lt_oq", 0x11)
1083 .Case("le_oq", 0x12)
1084 .Case("unord_s", 0x13)
1085 .Case("neq_us", 0x14)
1086 .Case("nlt_uq", 0x15)
1087 .Case("nle_uq", 0x16)
1088 .Case("ord_s", 0x17)
1089 .Case("eq_us", 0x18)
1090 .Case("nge_uq", 0x19)
1091 .Case("ngt_uq", 0x1A)
1092 .Case("false_os", 0x1B)
1093 .Case("neq_os", 0x1C)
1094 .Case("ge_oq", 0x1D)
1095 .Case("gt_oq", 0x1E)
1096 .Case("true_us", 0x1F)
1098 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1099 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1100 getParser().getContext());
1101 if (PatchedName.endswith("ss")) {
1102 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1103 } else if (PatchedName.endswith("sd")) {
1104 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1105 } else if (PatchedName.endswith("ps")) {
1106 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1108 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1109 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1114 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1116 if (ExtraImmOp && !isParsingIntelSyntax())
1117 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1119 // Determine whether this is an instruction prefix.
1121 Name == "lock" || Name == "rep" ||
1122 Name == "repe" || Name == "repz" ||
1123 Name == "repne" || Name == "repnz" ||
1124 Name == "rex64" || Name == "data16";
1127 // This does the actual operand parsing. Don't parse any more if we have a
1128 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1129 // just want to parse the "lock" as the first instruction and the "incl" as
1131 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1133 // Parse '*' modifier.
1134 if (getLexer().is(AsmToken::Star)) {
1135 SMLoc Loc = Parser.getTok().getLoc();
1136 Operands.push_back(X86Operand::CreateToken("*", Loc));
1137 Parser.Lex(); // Eat the star.
1140 // Read the first operand.
1141 if (X86Operand *Op = ParseOperand())
1142 Operands.push_back(Op);
1144 Parser.EatToEndOfStatement();
1148 while (getLexer().is(AsmToken::Comma)) {
1149 Parser.Lex(); // Eat the comma.
1151 // Parse and remember the operand.
1152 if (X86Operand *Op = ParseOperand())
1153 Operands.push_back(Op);
1155 Parser.EatToEndOfStatement();
1160 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1161 SMLoc Loc = getLexer().getLoc();
1162 Parser.EatToEndOfStatement();
1163 return Error(Loc, "unexpected token in argument list");
1167 if (getLexer().is(AsmToken::EndOfStatement))
1168 Parser.Lex(); // Consume the EndOfStatement
1169 else if (isPrefix && getLexer().is(AsmToken::Slash))
1170 Parser.Lex(); // Consume the prefix separator Slash
1172 if (ExtraImmOp && isParsingIntelSyntax())
1173 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1175 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1176 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1177 // documented form in various unofficial manuals, so a lot of code uses it.
1178 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1179 Operands.size() == 3) {
1180 X86Operand &Op = *(X86Operand*)Operands.back();
1181 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1182 isa<MCConstantExpr>(Op.Mem.Disp) &&
1183 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1184 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1185 SMLoc Loc = Op.getEndLoc();
1186 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1190 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1191 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1192 Operands.size() == 3) {
1193 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1194 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1195 isa<MCConstantExpr>(Op.Mem.Disp) &&
1196 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1197 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1198 SMLoc Loc = Op.getEndLoc();
1199 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1203 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1204 if (Name.startswith("ins") && Operands.size() == 3 &&
1205 (Name == "insb" || Name == "insw" || Name == "insl")) {
1206 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1207 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1208 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1209 Operands.pop_back();
1210 Operands.pop_back();
1216 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1217 if (Name.startswith("outs") && Operands.size() == 3 &&
1218 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1219 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1220 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1221 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1222 Operands.pop_back();
1223 Operands.pop_back();
1229 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1230 if (Name.startswith("movs") && Operands.size() == 3 &&
1231 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1232 (is64BitMode() && Name == "movsq"))) {
1233 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1234 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1235 if (isSrcOp(Op) && isDstOp(Op2)) {
1236 Operands.pop_back();
1237 Operands.pop_back();
1242 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1243 if (Name.startswith("lods") && Operands.size() == 3 &&
1244 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1245 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1246 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1247 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1248 if (isSrcOp(*Op1) && Op2->isReg()) {
1250 unsigned reg = Op2->getReg();
1251 bool isLods = Name == "lods";
1252 if (reg == X86::AL && (isLods || Name == "lodsb"))
1254 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1256 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1258 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1263 Operands.pop_back();
1264 Operands.pop_back();
1268 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1272 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1273 if (Name.startswith("stos") && Operands.size() == 3 &&
1274 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1275 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1276 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1277 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1278 if (isDstOp(*Op2) && Op1->isReg()) {
1280 unsigned reg = Op1->getReg();
1281 bool isStos = Name == "stos";
1282 if (reg == X86::AL && (isStos || Name == "stosb"))
1284 else if (reg == X86::AX && (isStos || Name == "stosw"))
1286 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1288 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1293 Operands.pop_back();
1294 Operands.pop_back();
1298 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1303 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1305 if ((Name.startswith("shr") || Name.startswith("sar") ||
1306 Name.startswith("shl") || Name.startswith("sal") ||
1307 Name.startswith("rcl") || Name.startswith("rcr") ||
1308 Name.startswith("rol") || Name.startswith("ror")) &&
1309 Operands.size() == 3) {
1310 if (isParsingIntelSyntax()) {
1312 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1313 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1314 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1316 Operands.pop_back();
1319 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1320 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1321 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1323 Operands.erase(Operands.begin() + 1);
1328 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1329 // instalias with an immediate operand yet.
1330 if (Name == "int" && Operands.size() == 2) {
1331 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1332 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1333 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1335 Operands.erase(Operands.begin() + 1);
1336 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1344 processInstruction(MCInst &Inst,
1345 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1346 switch (Inst.getOpcode()) {
1347 default: return false;
1348 case X86::AND16i16: {
1349 if (!Inst.getOperand(0).isImm() ||
1350 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1354 TmpInst.setOpcode(X86::AND16ri8);
1355 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1356 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1357 TmpInst.addOperand(Inst.getOperand(0));
1361 case X86::AND32i32: {
1362 if (!Inst.getOperand(0).isImm() ||
1363 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1367 TmpInst.setOpcode(X86::AND32ri8);
1368 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1369 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1370 TmpInst.addOperand(Inst.getOperand(0));
1374 case X86::AND64i32: {
1375 if (!Inst.getOperand(0).isImm() ||
1376 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1380 TmpInst.setOpcode(X86::AND64ri8);
1381 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1382 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1383 TmpInst.addOperand(Inst.getOperand(0));
1387 case X86::XOR16i16: {
1388 if (!Inst.getOperand(0).isImm() ||
1389 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1393 TmpInst.setOpcode(X86::XOR16ri8);
1394 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1395 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1396 TmpInst.addOperand(Inst.getOperand(0));
1400 case X86::XOR32i32: {
1401 if (!Inst.getOperand(0).isImm() ||
1402 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1406 TmpInst.setOpcode(X86::XOR32ri8);
1407 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1408 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1409 TmpInst.addOperand(Inst.getOperand(0));
1413 case X86::XOR64i32: {
1414 if (!Inst.getOperand(0).isImm() ||
1415 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1419 TmpInst.setOpcode(X86::XOR64ri8);
1420 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1421 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1422 TmpInst.addOperand(Inst.getOperand(0));
1426 case X86::OR16i16: {
1427 if (!Inst.getOperand(0).isImm() ||
1428 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1432 TmpInst.setOpcode(X86::OR16ri8);
1433 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1434 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1435 TmpInst.addOperand(Inst.getOperand(0));
1439 case X86::OR32i32: {
1440 if (!Inst.getOperand(0).isImm() ||
1441 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1445 TmpInst.setOpcode(X86::OR32ri8);
1446 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1447 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1448 TmpInst.addOperand(Inst.getOperand(0));
1452 case X86::OR64i32: {
1453 if (!Inst.getOperand(0).isImm() ||
1454 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1458 TmpInst.setOpcode(X86::OR64ri8);
1459 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1460 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1461 TmpInst.addOperand(Inst.getOperand(0));
1465 case X86::CMP16i16: {
1466 if (!Inst.getOperand(0).isImm() ||
1467 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1471 TmpInst.setOpcode(X86::CMP16ri8);
1472 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1473 TmpInst.addOperand(Inst.getOperand(0));
1477 case X86::CMP32i32: {
1478 if (!Inst.getOperand(0).isImm() ||
1479 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1483 TmpInst.setOpcode(X86::CMP32ri8);
1484 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1485 TmpInst.addOperand(Inst.getOperand(0));
1489 case X86::CMP64i32: {
1490 if (!Inst.getOperand(0).isImm() ||
1491 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1495 TmpInst.setOpcode(X86::CMP64ri8);
1496 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1497 TmpInst.addOperand(Inst.getOperand(0));
1501 case X86::ADD16i16: {
1502 if (!Inst.getOperand(0).isImm() ||
1503 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1507 TmpInst.setOpcode(X86::ADD16ri8);
1508 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1509 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1510 TmpInst.addOperand(Inst.getOperand(0));
1514 case X86::ADD32i32: {
1515 if (!Inst.getOperand(0).isImm() ||
1516 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1520 TmpInst.setOpcode(X86::ADD32ri8);
1521 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1522 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1523 TmpInst.addOperand(Inst.getOperand(0));
1527 case X86::ADD64i32: {
1528 if (!Inst.getOperand(0).isImm() ||
1529 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1533 TmpInst.setOpcode(X86::ADD64ri8);
1534 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1535 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1536 TmpInst.addOperand(Inst.getOperand(0));
1540 case X86::SUB16i16: {
1541 if (!Inst.getOperand(0).isImm() ||
1542 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1546 TmpInst.setOpcode(X86::SUB16ri8);
1547 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1548 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1549 TmpInst.addOperand(Inst.getOperand(0));
1553 case X86::SUB32i32: {
1554 if (!Inst.getOperand(0).isImm() ||
1555 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1559 TmpInst.setOpcode(X86::SUB32ri8);
1560 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1561 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1562 TmpInst.addOperand(Inst.getOperand(0));
1566 case X86::SUB64i32: {
1567 if (!Inst.getOperand(0).isImm() ||
1568 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1572 TmpInst.setOpcode(X86::SUB64ri8);
1573 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1574 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1575 TmpInst.addOperand(Inst.getOperand(0));
1583 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1584 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1585 MCStreamer &Out, unsigned &ErrorInfo,
1586 bool MatchingInlineAsm) {
1587 assert(!Operands.empty() && "Unexpect empty operand list!");
1588 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1589 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1590 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
1592 // First, handle aliases that expand to multiple instructions.
1593 // FIXME: This should be replaced with a real .td file alias mechanism.
1594 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
1596 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1597 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1598 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1599 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1601 Inst.setOpcode(X86::WAIT);
1603 if (!MatchingInlineAsm)
1604 Out.EmitInstruction(Inst);
1607 StringSwitch<const char*>(Op->getToken())
1608 .Case("finit", "fninit")
1609 .Case("fsave", "fnsave")
1610 .Case("fstcw", "fnstcw")
1611 .Case("fstcww", "fnstcw")
1612 .Case("fstenv", "fnstenv")
1613 .Case("fstsw", "fnstsw")
1614 .Case("fstsww", "fnstsw")
1615 .Case("fclex", "fnclex")
1617 assert(Repl && "Unknown wait-prefixed instruction");
1619 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1622 bool WasOriginallyInvalidOperand = false;
1625 // First, try a direct match.
1626 switch (MatchInstructionImpl(Operands, Inst,
1627 ErrorInfo, MatchingInlineAsm,
1628 isParsingIntelSyntax())) {
1631 // Some instructions need post-processing to, for example, tweak which
1632 // encoding is selected. Loop on it while changes happen so the
1633 // individual transformations can chain off each other.
1634 if (!MatchingInlineAsm)
1635 while (processInstruction(Inst, Operands))
1639 if (!MatchingInlineAsm)
1640 Out.EmitInstruction(Inst);
1641 Opcode = Inst.getOpcode();
1643 case Match_MissingFeature:
1644 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1645 EmptyRanges, MatchingInlineAsm);
1647 case Match_InvalidOperand:
1648 WasOriginallyInvalidOperand = true;
1650 case Match_MnemonicFail:
1654 // FIXME: Ideally, we would only attempt suffix matches for things which are
1655 // valid prefixes, and we could just infer the right unambiguous
1656 // type. However, that requires substantially more matcher support than the
1659 // Change the operand to point to a temporary token.
1660 StringRef Base = Op->getToken();
1661 SmallString<16> Tmp;
1664 Op->setTokenValue(Tmp.str());
1666 // If this instruction starts with an 'f', then it is a floating point stack
1667 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1668 // 80-bit floating point, which use the suffixes s,l,t respectively.
1670 // Otherwise, we assume that this may be an integer instruction, which comes
1671 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1672 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1674 // Check for the various suffix matches.
1675 Tmp[Base.size()] = Suffixes[0];
1676 unsigned ErrorInfoIgnore;
1677 unsigned Match1, Match2, Match3, Match4;
1679 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1680 isParsingIntelSyntax());
1681 Tmp[Base.size()] = Suffixes[1];
1682 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1683 isParsingIntelSyntax());
1684 Tmp[Base.size()] = Suffixes[2];
1685 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1686 isParsingIntelSyntax());
1687 Tmp[Base.size()] = Suffixes[3];
1688 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1689 isParsingIntelSyntax());
1691 // Restore the old token.
1692 Op->setTokenValue(Base);
1694 // If exactly one matched, then we treat that as a successful match (and the
1695 // instruction will already have been filled in correctly, since the failing
1696 // matches won't have modified it).
1697 unsigned NumSuccessfulMatches =
1698 (Match1 == Match_Success) + (Match2 == Match_Success) +
1699 (Match3 == Match_Success) + (Match4 == Match_Success);
1700 if (NumSuccessfulMatches == 1) {
1702 if (!MatchingInlineAsm)
1703 Out.EmitInstruction(Inst);
1704 Opcode = Inst.getOpcode();
1708 // Otherwise, the match failed, try to produce a decent error message.
1710 // If we had multiple suffix matches, then identify this as an ambiguous
1712 if (NumSuccessfulMatches > 1) {
1714 unsigned NumMatches = 0;
1715 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1716 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1717 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1718 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1720 SmallString<126> Msg;
1721 raw_svector_ostream OS(Msg);
1722 OS << "ambiguous instructions require an explicit suffix (could be ";
1723 for (unsigned i = 0; i != NumMatches; ++i) {
1726 if (i + 1 == NumMatches)
1728 OS << "'" << Base << MatchChars[i] << "'";
1731 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
1735 // Okay, we know that none of the variants matched successfully.
1737 // If all of the instructions reported an invalid mnemonic, then the original
1738 // mnemonic was invalid.
1739 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1740 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1741 if (!WasOriginallyInvalidOperand) {
1742 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
1744 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1745 Ranges, MatchingInlineAsm);
1748 // Recover location info for the operand if we know which was the problem.
1749 if (ErrorInfo != ~0U) {
1750 if (ErrorInfo >= Operands.size())
1751 return Error(IDLoc, "too few operands for instruction",
1752 EmptyRanges, MatchingInlineAsm);
1754 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
1755 if (Operand->getStartLoc().isValid()) {
1756 SMRange OperandRange = Operand->getLocRange();
1757 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1758 OperandRange, MatchingInlineAsm);
1762 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1766 // If one instruction matched with a missing feature, report this as a
1768 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1769 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1770 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1771 EmptyRanges, MatchingInlineAsm);
1775 // If one instruction matched with an invalid operand, report this as an
1777 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1778 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1779 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1784 // If all of these were an outright failure, report it in a useless way.
1785 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
1786 EmptyRanges, MatchingInlineAsm);
1791 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1792 StringRef IDVal = DirectiveID.getIdentifier();
1793 if (IDVal == ".word")
1794 return ParseDirectiveWord(2, DirectiveID.getLoc());
1795 else if (IDVal.startswith(".code"))
1796 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1797 else if (IDVal.startswith(".att_syntax")) {
1798 getParser().setAssemblerDialect(0);
1800 } else if (IDVal.startswith(".intel_syntax")) {
1801 getParser().setAssemblerDialect(1);
1802 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1803 if(Parser.getTok().getString() == "noprefix") {
1804 // FIXME : Handle noprefix
1814 /// ParseDirectiveWord
1815 /// ::= .word [ expression (, expression)* ]
1816 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1817 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1819 const MCExpr *Value;
1820 if (getParser().ParseExpression(Value))
1823 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1825 if (getLexer().is(AsmToken::EndOfStatement))
1828 // FIXME: Improve diagnostic.
1829 if (getLexer().isNot(AsmToken::Comma))
1830 return Error(L, "unexpected token in directive");
1839 /// ParseDirectiveCode
1840 /// ::= .code32 | .code64
1841 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1842 if (IDVal == ".code32") {
1844 if (is64BitMode()) {
1846 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1848 } else if (IDVal == ".code64") {
1850 if (!is64BitMode()) {
1852 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1855 return Error(L, "unexpected directive " + IDVal);
1862 extern "C" void LLVMInitializeX86AsmLexer();
1864 // Force static initialization.
1865 extern "C" void LLVMInitializeX86AsmParser() {
1866 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1867 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1868 LLVMInitializeX86AsmLexer();
1871 #define GET_REGISTER_MATCHER
1872 #define GET_MATCHER_IMPLEMENTATION
1873 #include "X86GenAsmMatcher.inc"