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/ADT/APFloat.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCInst.h"
20 #include "llvm/MC/MCParser/MCAsmLexer.h"
21 #include "llvm/MC/MCParser/MCAsmParser.h"
22 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
23 #include "llvm/MC/MCRegisterInfo.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCTargetAsmParser.h"
28 #include "llvm/Support/SourceMgr.h"
29 #include "llvm/Support/TargetRegistry.h"
30 #include "llvm/Support/raw_ostream.h"
37 static const char OpPrecedence[] = {
48 class X86AsmParser : public MCTargetAsmParser {
51 ParseInstructionInfo *InstInfo;
53 enum InfixCalculatorTok {
64 class InfixCalculator {
65 typedef std::pair< InfixCalculatorTok, int64_t > ICToken;
66 SmallVector<InfixCalculatorTok, 4> InfixOperatorStack;
67 SmallVector<ICToken, 4> PostfixStack;
70 int64_t popOperand() {
71 assert (!PostfixStack.empty() && "Poped an empty stack!");
72 ICToken Op = PostfixStack.pop_back_val();
73 assert ((Op.first == IC_IMM || Op.first == IC_REGISTER)
74 && "Expected and immediate or register!");
77 void pushOperand(InfixCalculatorTok Op, int64_t Val = 0) {
78 assert ((Op == IC_IMM || Op == IC_REGISTER) &&
79 "Unexpected operand!");
80 PostfixStack.push_back(std::make_pair(Op, Val));
83 void popOperator() { InfixOperatorStack.pop_back_val(); }
84 void pushOperator(InfixCalculatorTok Op) {
85 // Push the new operator if the stack is empty.
86 if (InfixOperatorStack.empty()) {
87 InfixOperatorStack.push_back(Op);
91 // Push the new operator if it has a higher precedence than the operator
92 // on the top of the stack or the operator on the top of the stack is a
94 unsigned Idx = InfixOperatorStack.size() - 1;
95 InfixCalculatorTok StackOp = InfixOperatorStack[Idx];
96 if (OpPrecedence[Op] > OpPrecedence[StackOp] || StackOp == IC_LPAREN) {
97 InfixOperatorStack.push_back(Op);
101 // The operator on the top of the stack has higher precedence than the
103 unsigned ParenCount = 0;
105 // Nothing to process.
106 if (InfixOperatorStack.empty())
109 Idx = InfixOperatorStack.size() - 1;
110 StackOp = InfixOperatorStack[Idx];
111 if (!(OpPrecedence[StackOp] >= OpPrecedence[Op] || ParenCount))
114 // If we have an even parentheses count and we see a left parentheses,
115 // then stop processing.
116 if (!ParenCount && StackOp == IC_LPAREN)
119 if (StackOp == IC_RPAREN) {
121 InfixOperatorStack.pop_back_val();
122 } else if (StackOp == IC_LPAREN) {
124 InfixOperatorStack.pop_back_val();
126 InfixOperatorStack.pop_back_val();
127 PostfixStack.push_back(std::make_pair(StackOp, 0));
130 // Push the new operator.
131 InfixOperatorStack.push_back(Op);
134 // Push any remaining operators onto the postfix stack.
135 while (!InfixOperatorStack.empty()) {
136 InfixCalculatorTok StackOp = InfixOperatorStack.pop_back_val();
137 if (StackOp != IC_LPAREN && StackOp != IC_RPAREN)
138 PostfixStack.push_back(std::make_pair(StackOp, 0));
141 if (PostfixStack.empty())
144 SmallVector<ICToken, 16> OperandStack;
145 for (unsigned i = 0, e = PostfixStack.size(); i != e; ++i) {
146 ICToken Op = PostfixStack[i];
147 if (Op.first == IC_IMM || Op.first == IC_REGISTER) {
148 OperandStack.push_back(Op);
150 assert (OperandStack.size() > 1 && "Too few operands.");
152 ICToken Op2 = OperandStack.pop_back_val();
153 ICToken Op1 = OperandStack.pop_back_val();
156 report_fatal_error("Unexpected operator!");
159 Val = Op1.second + Op2.second;
160 OperandStack.push_back(std::make_pair(IC_IMM, Val));
163 Val = Op1.second - Op2.second;
164 OperandStack.push_back(std::make_pair(IC_IMM, Val));
167 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
168 "Multiply operation with an immediate and a register!");
169 Val = Op1.second * Op2.second;
170 OperandStack.push_back(std::make_pair(IC_IMM, Val));
173 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
174 "Divide operation with an immediate and a register!");
175 assert (Op2.second != 0 && "Division by zero!");
176 Val = Op1.second / Op2.second;
177 OperandStack.push_back(std::make_pair(IC_IMM, Val));
182 assert (OperandStack.size() == 1 && "Expected a single result.");
183 return OperandStack.pop_back_val().second;
187 enum IntelExprState {
202 class IntelExprStateMachine {
203 IntelExprState State, PrevState;
204 unsigned BaseReg, IndexReg, TmpReg, Scale;
208 bool StopOnLBrac, AddImmPrefix;
210 InlineAsmIdentifierInfo Info;
212 IntelExprStateMachine(int64_t imm, bool stoponlbrac, bool addimmprefix) :
213 State(IES_PLUS), PrevState(IES_ERROR), BaseReg(0), IndexReg(0), TmpReg(0),
214 Scale(1), Imm(imm), Sym(0), StopOnLBrac(stoponlbrac),
215 AddImmPrefix(addimmprefix) { Info.clear(); }
217 unsigned getBaseReg() { return BaseReg; }
218 unsigned getIndexReg() { return IndexReg; }
219 unsigned getScale() { return Scale; }
220 const MCExpr *getSym() { return Sym; }
221 StringRef getSymName() { return SymName; }
222 int64_t getImm() { return Imm + IC.execute(); }
223 bool isValidEndState() {
224 return State == IES_RBRAC || State == IES_INTEGER;
226 bool getStopOnLBrac() { return StopOnLBrac; }
227 bool getAddImmPrefix() { return AddImmPrefix; }
228 bool hadError() { return State == IES_ERROR; }
230 InlineAsmIdentifierInfo &getIdentifierInfo() {
235 IntelExprState CurrState = State;
244 IC.pushOperator(IC_PLUS);
245 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
246 // If we already have a BaseReg, then assume this is the IndexReg with
251 assert (!IndexReg && "BaseReg/IndexReg already set!");
258 PrevState = CurrState;
261 IntelExprState CurrState = State;
276 // Only push the minus operator if it is not a unary operator.
277 if (!(CurrState == IES_PLUS || CurrState == IES_MINUS ||
278 CurrState == IES_MULTIPLY || CurrState == IES_DIVIDE ||
279 CurrState == IES_LPAREN || CurrState == IES_LBRAC))
280 IC.pushOperator(IC_MINUS);
281 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
282 // If we already have a BaseReg, then assume this is the IndexReg with
287 assert (!IndexReg && "BaseReg/IndexReg already set!");
294 PrevState = CurrState;
296 void onRegister(unsigned Reg) {
297 IntelExprState CurrState = State;
304 State = IES_REGISTER;
306 IC.pushOperand(IC_REGISTER);
309 // Index Register - Scale * Register
310 if (PrevState == IES_INTEGER) {
311 assert (!IndexReg && "IndexReg already set!");
312 State = IES_REGISTER;
314 // Get the scale and replace the 'Scale * Register' with '0'.
315 Scale = IC.popOperand();
316 IC.pushOperand(IC_IMM);
323 PrevState = CurrState;
325 void onIdentifierExpr(const MCExpr *SymRef, StringRef SymRefName) {
335 SymName = SymRefName;
336 IC.pushOperand(IC_IMM);
340 void onInteger(int64_t TmpInt) {
341 IntelExprState CurrState = State;
352 if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) {
353 // Index Register - Register * Scale
354 assert (!IndexReg && "IndexReg already set!");
357 // Get the scale and replace the 'Register * Scale' with '0'.
359 } else if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
360 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
361 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
362 CurrState == IES_MINUS) {
363 // Unary minus. No need to pop the minus operand because it was never
365 IC.pushOperand(IC_IMM, -TmpInt); // Push -Imm.
367 IC.pushOperand(IC_IMM, TmpInt);
371 PrevState = CurrState;
382 State = IES_MULTIPLY;
383 IC.pushOperator(IC_MULTIPLY);
396 IC.pushOperator(IC_DIVIDE);
408 IC.pushOperator(IC_PLUS);
413 IntelExprState CurrState = State;
422 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
423 // If we already have a BaseReg, then assume this is the IndexReg with
428 assert (!IndexReg && "BaseReg/IndexReg already set!");
435 PrevState = CurrState;
438 IntelExprState CurrState = State;
448 // FIXME: We don't handle this type of unary minus, yet.
449 if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
450 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
451 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
452 CurrState == IES_MINUS) {
457 IC.pushOperator(IC_LPAREN);
460 PrevState = CurrState;
472 IC.pushOperator(IC_RPAREN);
478 MCAsmParser &getParser() const { return Parser; }
480 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
482 bool Error(SMLoc L, const Twine &Msg,
483 ArrayRef<SMRange> Ranges = None,
484 bool MatchingInlineAsm = false) {
485 if (MatchingInlineAsm) return true;
486 return Parser.Error(L, Msg, Ranges);
489 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
494 X86Operand *ParseOperand();
495 X86Operand *ParseATTOperand();
496 X86Operand *ParseIntelOperand();
497 X86Operand *ParseIntelOffsetOfOperator();
498 X86Operand *ParseIntelDotOperator(const MCExpr *Disp, const MCExpr *&NewDisp);
499 X86Operand *ParseIntelOperator(unsigned OpKind);
500 X86Operand *ParseIntelMemOperand(unsigned SegReg, int64_t ImmDisp,
502 X86Operand *ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End);
503 X86Operand *ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
504 int64_t ImmDisp, unsigned Size);
505 X86Operand *ParseIntelIdentifier(const MCExpr *&Val, StringRef &Identifier,
506 InlineAsmIdentifierInfo &Info,
507 bool IsUnevaluatedOperand, SMLoc &End);
509 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
511 X86Operand *CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
512 unsigned BaseReg, unsigned IndexReg,
513 unsigned Scale, SMLoc Start, SMLoc End,
514 unsigned Size, StringRef Identifier,
515 InlineAsmIdentifierInfo &Info);
517 bool ParseDirectiveWord(unsigned Size, SMLoc L);
518 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
520 bool processInstruction(MCInst &Inst,
521 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
523 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
524 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
525 MCStreamer &Out, unsigned &ErrorInfo,
526 bool MatchingInlineAsm);
528 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
529 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
530 bool isSrcOp(X86Operand &Op);
532 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
533 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
534 bool isDstOp(X86Operand &Op);
536 bool is64BitMode() const {
537 // FIXME: Can tablegen auto-generate this?
538 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
541 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
542 setAvailableFeatures(FB);
545 bool isParsingIntelSyntax() {
546 return getParser().getAssemblerDialect();
549 /// @name Auto-generated Matcher Functions
552 #define GET_ASSEMBLER_HEADER
553 #include "X86GenAsmMatcher.inc"
558 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
559 : MCTargetAsmParser(), STI(sti), Parser(parser), InstInfo(0) {
561 // Initialize the set of available features.
562 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
564 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
566 virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
568 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
570 virtual bool ParseDirective(AsmToken DirectiveID);
572 } // end anonymous namespace
574 /// @name Auto-generated Match Functions
577 static unsigned MatchRegisterName(StringRef Name);
581 static bool isImmSExti16i8Value(uint64_t Value) {
582 return (( Value <= 0x000000000000007FULL)||
583 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
584 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
587 static bool isImmSExti32i8Value(uint64_t Value) {
588 return (( Value <= 0x000000000000007FULL)||
589 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
590 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
593 static bool isImmZExtu32u8Value(uint64_t Value) {
594 return (Value <= 0x00000000000000FFULL);
597 static bool isImmSExti64i8Value(uint64_t Value) {
598 return (( Value <= 0x000000000000007FULL)||
599 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
602 static bool isImmSExti64i32Value(uint64_t Value) {
603 return (( Value <= 0x000000007FFFFFFFULL)||
604 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
608 /// X86Operand - Instances of this class represent a parsed X86 machine
610 struct X86Operand : public MCParsedAsmOperand {
618 SMLoc StartLoc, EndLoc;
653 X86Operand(KindTy K, SMLoc Start, SMLoc End)
654 : Kind(K), StartLoc(Start), EndLoc(End) {}
656 StringRef getSymName() { return SymName; }
657 void *getOpDecl() { return OpDecl; }
659 /// getStartLoc - Get the location of the first token of this operand.
660 SMLoc getStartLoc() const { return StartLoc; }
661 /// getEndLoc - Get the location of the last token of this operand.
662 SMLoc getEndLoc() const { return EndLoc; }
663 /// getLocRange - Get the range between the first and last token of this
665 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
666 /// getOffsetOfLoc - Get the location of the offset operator.
667 SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
669 virtual void print(raw_ostream &OS) const {}
671 StringRef getToken() const {
672 assert(Kind == Token && "Invalid access!");
673 return StringRef(Tok.Data, Tok.Length);
675 void setTokenValue(StringRef Value) {
676 assert(Kind == Token && "Invalid access!");
677 Tok.Data = Value.data();
678 Tok.Length = Value.size();
681 unsigned getReg() const {
682 assert(Kind == Register && "Invalid access!");
686 const MCExpr *getImm() const {
687 assert(Kind == Immediate && "Invalid access!");
691 const MCExpr *getMemDisp() const {
692 assert(Kind == Memory && "Invalid access!");
695 unsigned getMemSegReg() const {
696 assert(Kind == Memory && "Invalid access!");
699 unsigned getMemBaseReg() const {
700 assert(Kind == Memory && "Invalid access!");
703 unsigned getMemIndexReg() const {
704 assert(Kind == Memory && "Invalid access!");
707 unsigned getMemScale() const {
708 assert(Kind == Memory && "Invalid access!");
712 bool isToken() const {return Kind == Token; }
714 bool isImm() const { return Kind == Immediate; }
716 bool isImmSExti16i8() const {
720 // If this isn't a constant expr, just assume it fits and let relaxation
722 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
726 // Otherwise, check the value is in a range that makes sense for this
728 return isImmSExti16i8Value(CE->getValue());
730 bool isImmSExti32i8() const {
734 // If this isn't a constant expr, just assume it fits and let relaxation
736 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
740 // Otherwise, check the value is in a range that makes sense for this
742 return isImmSExti32i8Value(CE->getValue());
744 bool isImmZExtu32u8() const {
748 // If this isn't a constant expr, just assume it fits and let relaxation
750 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
754 // Otherwise, check the value is in a range that makes sense for this
756 return isImmZExtu32u8Value(CE->getValue());
758 bool isImmSExti64i8() const {
762 // If this isn't a constant expr, just assume it fits and let relaxation
764 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
768 // Otherwise, check the value is in a range that makes sense for this
770 return isImmSExti64i8Value(CE->getValue());
772 bool isImmSExti64i32() const {
776 // If this isn't a constant expr, just assume it fits and let relaxation
778 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
782 // Otherwise, check the value is in a range that makes sense for this
784 return isImmSExti64i32Value(CE->getValue());
787 bool isOffsetOf() const {
788 return OffsetOfLoc.getPointer();
791 bool needAddressOf() const {
795 bool isMem() const { return Kind == Memory; }
796 bool isMem8() const {
797 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
799 bool isMem16() const {
800 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
802 bool isMem32() const {
803 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
805 bool isMem64() const {
806 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
808 bool isMem80() const {
809 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
811 bool isMem128() const {
812 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
814 bool isMem256() const {
815 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
818 bool isMemVX32() const {
819 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
820 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
822 bool isMemVY32() const {
823 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
824 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
826 bool isMemVX64() const {
827 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
828 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
830 bool isMemVY64() const {
831 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
832 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
835 bool isAbsMem() const {
836 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
837 !getMemIndexReg() && getMemScale() == 1;
840 bool isReg() const { return Kind == Register; }
842 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
843 // Add as immediates when possible.
844 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
845 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
847 Inst.addOperand(MCOperand::CreateExpr(Expr));
850 void addRegOperands(MCInst &Inst, unsigned N) const {
851 assert(N == 1 && "Invalid number of operands!");
852 Inst.addOperand(MCOperand::CreateReg(getReg()));
855 void addImmOperands(MCInst &Inst, unsigned N) const {
856 assert(N == 1 && "Invalid number of operands!");
857 addExpr(Inst, getImm());
860 void addMem8Operands(MCInst &Inst, unsigned N) const {
861 addMemOperands(Inst, N);
863 void addMem16Operands(MCInst &Inst, unsigned N) const {
864 addMemOperands(Inst, N);
866 void addMem32Operands(MCInst &Inst, unsigned N) const {
867 addMemOperands(Inst, N);
869 void addMem64Operands(MCInst &Inst, unsigned N) const {
870 addMemOperands(Inst, N);
872 void addMem80Operands(MCInst &Inst, unsigned N) const {
873 addMemOperands(Inst, N);
875 void addMem128Operands(MCInst &Inst, unsigned N) const {
876 addMemOperands(Inst, N);
878 void addMem256Operands(MCInst &Inst, unsigned N) const {
879 addMemOperands(Inst, N);
881 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
882 addMemOperands(Inst, N);
884 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
885 addMemOperands(Inst, N);
887 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
888 addMemOperands(Inst, N);
890 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
891 addMemOperands(Inst, N);
894 void addMemOperands(MCInst &Inst, unsigned N) const {
895 assert((N == 5) && "Invalid number of operands!");
896 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
897 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
898 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
899 addExpr(Inst, getMemDisp());
900 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
903 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
904 assert((N == 1) && "Invalid number of operands!");
905 // Add as immediates when possible.
906 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
907 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
909 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
912 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
913 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size());
914 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
915 Res->Tok.Data = Str.data();
916 Res->Tok.Length = Str.size();
920 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
921 bool AddressOf = false,
922 SMLoc OffsetOfLoc = SMLoc(),
923 StringRef SymName = StringRef(),
925 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
926 Res->Reg.RegNo = RegNo;
927 Res->AddressOf = AddressOf;
928 Res->OffsetOfLoc = OffsetOfLoc;
929 Res->SymName = SymName;
930 Res->OpDecl = OpDecl;
934 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
935 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
940 /// Create an absolute memory operand.
941 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc,
942 unsigned Size = 0, StringRef SymName = StringRef(),
944 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
946 Res->Mem.Disp = Disp;
947 Res->Mem.BaseReg = 0;
948 Res->Mem.IndexReg = 0;
950 Res->Mem.Size = Size;
951 Res->SymName = SymName;
952 Res->OpDecl = OpDecl;
953 Res->AddressOf = false;
957 /// Create a generalized memory operand.
958 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
959 unsigned BaseReg, unsigned IndexReg,
960 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
962 StringRef SymName = StringRef(),
964 // We should never just have a displacement, that should be parsed as an
965 // absolute memory operand.
966 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
968 // The scale should always be one of {1,2,4,8}.
969 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
971 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
972 Res->Mem.SegReg = SegReg;
973 Res->Mem.Disp = Disp;
974 Res->Mem.BaseReg = BaseReg;
975 Res->Mem.IndexReg = IndexReg;
976 Res->Mem.Scale = Scale;
977 Res->Mem.Size = Size;
978 Res->SymName = SymName;
979 Res->OpDecl = OpDecl;
980 Res->AddressOf = false;
985 } // end anonymous namespace.
987 bool X86AsmParser::isSrcOp(X86Operand &Op) {
988 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
990 return (Op.isMem() &&
991 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
992 isa<MCConstantExpr>(Op.Mem.Disp) &&
993 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
994 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
997 bool X86AsmParser::isDstOp(X86Operand &Op) {
998 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
1000 return Op.isMem() &&
1001 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
1002 isa<MCConstantExpr>(Op.Mem.Disp) &&
1003 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1004 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
1007 bool X86AsmParser::ParseRegister(unsigned &RegNo,
1008 SMLoc &StartLoc, SMLoc &EndLoc) {
1010 const AsmToken &PercentTok = Parser.getTok();
1011 StartLoc = PercentTok.getLoc();
1013 // If we encounter a %, ignore it. This code handles registers with and
1014 // without the prefix, unprefixed registers can occur in cfi directives.
1015 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
1016 Parser.Lex(); // Eat percent token.
1018 const AsmToken &Tok = Parser.getTok();
1019 EndLoc = Tok.getEndLoc();
1021 if (Tok.isNot(AsmToken::Identifier)) {
1022 if (isParsingIntelSyntax()) return true;
1023 return Error(StartLoc, "invalid register name",
1024 SMRange(StartLoc, EndLoc));
1027 RegNo = MatchRegisterName(Tok.getString());
1029 // If the match failed, try the register name as lowercase.
1031 RegNo = MatchRegisterName(Tok.getString().lower());
1033 if (!is64BitMode()) {
1034 // FIXME: This should be done using Requires<In32BitMode> and
1035 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
1037 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
1039 if (RegNo == X86::RIZ ||
1040 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
1041 X86II::isX86_64NonExtLowByteReg(RegNo) ||
1042 X86II::isX86_64ExtendedReg(RegNo))
1043 return Error(StartLoc, "register %"
1044 + Tok.getString() + " is only available in 64-bit mode",
1045 SMRange(StartLoc, EndLoc));
1048 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
1049 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
1051 Parser.Lex(); // Eat 'st'
1053 // Check to see if we have '(4)' after %st.
1054 if (getLexer().isNot(AsmToken::LParen))
1059 const AsmToken &IntTok = Parser.getTok();
1060 if (IntTok.isNot(AsmToken::Integer))
1061 return Error(IntTok.getLoc(), "expected stack index");
1062 switch (IntTok.getIntVal()) {
1063 case 0: RegNo = X86::ST0; break;
1064 case 1: RegNo = X86::ST1; break;
1065 case 2: RegNo = X86::ST2; break;
1066 case 3: RegNo = X86::ST3; break;
1067 case 4: RegNo = X86::ST4; break;
1068 case 5: RegNo = X86::ST5; break;
1069 case 6: RegNo = X86::ST6; break;
1070 case 7: RegNo = X86::ST7; break;
1071 default: return Error(IntTok.getLoc(), "invalid stack index");
1074 if (getParser().Lex().isNot(AsmToken::RParen))
1075 return Error(Parser.getTok().getLoc(), "expected ')'");
1077 EndLoc = Parser.getTok().getEndLoc();
1078 Parser.Lex(); // Eat ')'
1082 EndLoc = Parser.getTok().getEndLoc();
1084 // If this is "db[0-7]", match it as an alias
1086 if (RegNo == 0 && Tok.getString().size() == 3 &&
1087 Tok.getString().startswith("db")) {
1088 switch (Tok.getString()[2]) {
1089 case '0': RegNo = X86::DR0; break;
1090 case '1': RegNo = X86::DR1; break;
1091 case '2': RegNo = X86::DR2; break;
1092 case '3': RegNo = X86::DR3; break;
1093 case '4': RegNo = X86::DR4; break;
1094 case '5': RegNo = X86::DR5; break;
1095 case '6': RegNo = X86::DR6; break;
1096 case '7': RegNo = X86::DR7; break;
1100 EndLoc = Parser.getTok().getEndLoc();
1101 Parser.Lex(); // Eat it.
1107 if (isParsingIntelSyntax()) return true;
1108 return Error(StartLoc, "invalid register name",
1109 SMRange(StartLoc, EndLoc));
1112 Parser.Lex(); // Eat identifier token.
1116 X86Operand *X86AsmParser::ParseOperand() {
1117 if (isParsingIntelSyntax())
1118 return ParseIntelOperand();
1119 return ParseATTOperand();
1122 /// getIntelMemOperandSize - Return intel memory operand size.
1123 static unsigned getIntelMemOperandSize(StringRef OpStr) {
1124 unsigned Size = StringSwitch<unsigned>(OpStr)
1125 .Cases("BYTE", "byte", 8)
1126 .Cases("WORD", "word", 16)
1127 .Cases("DWORD", "dword", 32)
1128 .Cases("QWORD", "qword", 64)
1129 .Cases("XWORD", "xword", 80)
1130 .Cases("XMMWORD", "xmmword", 128)
1131 .Cases("YMMWORD", "ymmword", 256)
1137 X86AsmParser::CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
1138 unsigned BaseReg, unsigned IndexReg,
1139 unsigned Scale, SMLoc Start, SMLoc End,
1140 unsigned Size, StringRef Identifier,
1141 InlineAsmIdentifierInfo &Info){
1142 if (isa<MCSymbolRefExpr>(Disp)) {
1143 // If this is not a VarDecl then assume it is a FuncDecl or some other label
1144 // reference. We need an 'r' constraint here, so we need to create register
1145 // operand to ensure proper matching. Just pick a GPR based on the size of
1147 if (!Info.IsVarDecl) {
1148 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1149 return X86Operand::CreateReg(RegNo, Start, End, /*AddressOf=*/true,
1150 SMLoc(), Identifier, Info.OpDecl);
1153 Size = Info.Type * 8; // Size is in terms of bits in this context.
1155 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_SizeDirective, Start,
1160 // When parsing inline assembly we set the base register to a non-zero value
1161 // if we don't know the actual value at this time. This is necessary to
1162 // get the matching correct in some cases.
1163 BaseReg = BaseReg ? BaseReg : 1;
1164 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1165 End, Size, Identifier, Info.OpDecl);
1169 RewriteIntelBracExpression(SmallVectorImpl<AsmRewrite> *AsmRewrites,
1170 StringRef SymName, int64_t ImmDisp,
1171 int64_t FinalImmDisp, SMLoc &BracLoc,
1172 SMLoc &StartInBrac, SMLoc &End) {
1173 // Remove the '[' and ']' from the IR string.
1174 AsmRewrites->push_back(AsmRewrite(AOK_Skip, BracLoc, 1));
1175 AsmRewrites->push_back(AsmRewrite(AOK_Skip, End, 1));
1177 // If ImmDisp is non-zero, then we parsed a displacement before the
1178 // bracketed expression (i.e., ImmDisp [ BaseReg + Scale*IndexReg + Disp])
1179 // If ImmDisp doesn't match the displacement computed by the state machine
1180 // then we have an additional displacement in the bracketed expression.
1181 if (ImmDisp != FinalImmDisp) {
1183 // We have an immediate displacement before the bracketed expression.
1184 // Adjust this to match the final immediate displacement.
1186 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1187 E = AsmRewrites->end(); I != E; ++I) {
1188 if ((*I).Loc.getPointer() > BracLoc.getPointer())
1190 if ((*I).Kind == AOK_ImmPrefix || (*I).Kind == AOK_Imm) {
1191 assert (!Found && "ImmDisp already rewritten.");
1192 (*I).Kind = AOK_Imm;
1193 (*I).Len = BracLoc.getPointer() - (*I).Loc.getPointer();
1194 (*I).Val = FinalImmDisp;
1199 assert (Found && "Unable to rewrite ImmDisp.");
1202 // We have a symbolic and an immediate displacement, but no displacement
1203 // before the bracketed expression. Put the immediate displacement
1204 // before the bracketed expression.
1205 AsmRewrites->push_back(AsmRewrite(AOK_Imm, BracLoc, 0, FinalImmDisp));
1208 // Remove all the ImmPrefix rewrites within the brackets.
1209 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1210 E = AsmRewrites->end(); I != E; ++I) {
1211 if ((*I).Loc.getPointer() < StartInBrac.getPointer())
1213 if ((*I).Kind == AOK_ImmPrefix)
1214 (*I).Kind = AOK_Delete;
1216 const char *SymLocPtr = SymName.data();
1217 // Skip everything before the symbol.
1218 if (unsigned Len = SymLocPtr - StartInBrac.getPointer()) {
1219 assert(Len > 0 && "Expected a non-negative length.");
1220 AsmRewrites->push_back(AsmRewrite(AOK_Skip, StartInBrac, Len));
1222 // Skip everything after the symbol.
1223 if (unsigned Len = End.getPointer() - (SymLocPtr + SymName.size())) {
1224 SMLoc Loc = SMLoc::getFromPointer(SymLocPtr + SymName.size());
1225 assert(Len > 0 && "Expected a non-negative length.");
1226 AsmRewrites->push_back(AsmRewrite(AOK_Skip, Loc, Len));
1231 X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) {
1232 const AsmToken &Tok = Parser.getTok();
1236 bool UpdateLocLex = true;
1238 // The period in the dot operator (e.g., [ebx].foo.bar) is parsed as an
1239 // identifier. Don't try an parse it as a register.
1240 if (Tok.getString().startswith("."))
1243 // If we're parsing an immediate expression, we don't expect a '['.
1244 if (SM.getStopOnLBrac() && getLexer().getKind() == AsmToken::LBrac)
1247 switch (getLexer().getKind()) {
1249 if (SM.isValidEndState()) {
1253 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1255 case AsmToken::EndOfStatement: {
1259 case AsmToken::Identifier: {
1260 // This could be a register or a symbolic displacement.
1263 SMLoc IdentLoc = Tok.getLoc();
1264 StringRef Identifier = Tok.getString();
1265 if(!ParseRegister(TmpReg, IdentLoc, End)) {
1266 SM.onRegister(TmpReg);
1267 UpdateLocLex = false;
1270 if (!isParsingInlineAsm()) {
1271 if (getParser().parsePrimaryExpr(Val, End))
1272 return ErrorOperand(Tok.getLoc(), "Unexpected identifier!");
1274 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1275 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info,
1276 /*Unevaluated*/ false, End))
1279 SM.onIdentifierExpr(Val, Identifier);
1280 UpdateLocLex = false;
1283 return ErrorOperand(Tok.getLoc(), "Unexpected identifier!");
1285 case AsmToken::Integer:
1286 if (isParsingInlineAsm() && SM.getAddImmPrefix())
1287 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1289 SM.onInteger(Tok.getIntVal());
1291 case AsmToken::Plus: SM.onPlus(); break;
1292 case AsmToken::Minus: SM.onMinus(); break;
1293 case AsmToken::Star: SM.onStar(); break;
1294 case AsmToken::Slash: SM.onDivide(); break;
1295 case AsmToken::LBrac: SM.onLBrac(); break;
1296 case AsmToken::RBrac: SM.onRBrac(); break;
1297 case AsmToken::LParen: SM.onLParen(); break;
1298 case AsmToken::RParen: SM.onRParen(); break;
1301 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1303 if (!Done && UpdateLocLex) {
1305 Parser.Lex(); // Consume the token.
1311 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
1314 const AsmToken &Tok = Parser.getTok();
1315 SMLoc BracLoc = Tok.getLoc(), End = Tok.getEndLoc();
1316 if (getLexer().isNot(AsmToken::LBrac))
1317 return ErrorOperand(BracLoc, "Expected '[' token!");
1318 Parser.Lex(); // Eat '['
1320 SMLoc StartInBrac = Tok.getLoc();
1321 // Parse [ Symbol + ImmDisp ] and [ BaseReg + Scale*IndexReg + ImmDisp ]. We
1322 // may have already parsed an immediate displacement before the bracketed
1324 IntelExprStateMachine SM(ImmDisp, /*StopOnLBrac=*/false, /*AddImmPrefix=*/true);
1325 if (X86Operand *Err = ParseIntelExpression(SM, End))
1329 if (const MCExpr *Sym = SM.getSym()) {
1330 // A symbolic displacement.
1332 if (isParsingInlineAsm())
1333 RewriteIntelBracExpression(InstInfo->AsmRewrites, SM.getSymName(),
1334 ImmDisp, SM.getImm(), BracLoc, StartInBrac,
1337 // An immediate displacement only.
1338 Disp = MCConstantExpr::Create(SM.getImm(), getContext());
1341 // Parse the dot operator (e.g., [ebx].foo.bar).
1342 if (Tok.getString().startswith(".")) {
1343 const MCExpr *NewDisp;
1344 if (X86Operand *Err = ParseIntelDotOperator(Disp, NewDisp))
1347 End = Tok.getEndLoc();
1348 Parser.Lex(); // Eat the field.
1352 int BaseReg = SM.getBaseReg();
1353 int IndexReg = SM.getIndexReg();
1354 int Scale = SM.getScale();
1355 if (!isParsingInlineAsm()) {
1357 if (!BaseReg && !IndexReg) {
1359 return X86Operand::CreateMem(Disp, Start, End, Size);
1361 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, Start, End, Size);
1363 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1367 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1368 return CreateMemForInlineAsm(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1369 End, Size, SM.getSymName(), Info);
1372 // Inline assembly may use variable names with namespace alias qualifiers.
1373 X86Operand *X86AsmParser::ParseIntelIdentifier(const MCExpr *&Val,
1374 StringRef &Identifier,
1375 InlineAsmIdentifierInfo &Info,
1376 bool IsUnevaluatedOperand,
1378 assert (isParsingInlineAsm() && "Expected to be parsing inline assembly.");
1381 StringRef LineBuf(Identifier.data());
1382 SemaCallback->LookupInlineAsmIdentifier(LineBuf, Info, IsUnevaluatedOperand);
1384 const AsmToken &Tok = Parser.getTok();
1386 // Advance the token stream until the end of the current token is
1387 // after the end of what the frontend claimed.
1388 const char *EndPtr = Tok.getLoc().getPointer() + LineBuf.size();
1390 End = Tok.getEndLoc();
1393 assert(End.getPointer() <= EndPtr && "frontend claimed part of a token?");
1394 if (End.getPointer() == EndPtr) break;
1397 // Create the symbol reference.
1398 Identifier = LineBuf;
1399 MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier);
1400 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1401 Val = MCSymbolRefExpr::Create(Sym, Variant, getParser().getContext());
1405 /// ParseIntelMemOperand - Parse intel style memory operand.
1406 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg,
1409 const AsmToken &Tok = Parser.getTok();
1412 unsigned Size = getIntelMemOperandSize(Tok.getString());
1414 Parser.Lex(); // Eat operand size (e.g., byte, word).
1415 if (Tok.getString() != "PTR" && Tok.getString() != "ptr")
1416 return ErrorOperand(Start, "Expected 'PTR' or 'ptr' token!");
1417 Parser.Lex(); // Eat ptr.
1420 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1421 if (getLexer().is(AsmToken::Integer)) {
1422 if (isParsingInlineAsm())
1423 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1425 int64_t ImmDisp = Tok.getIntVal();
1426 Parser.Lex(); // Eat the integer.
1427 if (getLexer().isNot(AsmToken::LBrac))
1428 return ErrorOperand(Start, "Expected '[' token!");
1429 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1432 if (getLexer().is(AsmToken::LBrac))
1433 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1435 if (!ParseRegister(SegReg, Start, End)) {
1436 // Handel SegReg : [ ... ]
1437 if (getLexer().isNot(AsmToken::Colon))
1438 return ErrorOperand(Start, "Expected ':' token!");
1439 Parser.Lex(); // Eat :
1440 if (getLexer().isNot(AsmToken::LBrac))
1441 return ErrorOperand(Start, "Expected '[' token!");
1442 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1446 if (!isParsingInlineAsm()) {
1447 if (getParser().parsePrimaryExpr(Val, End))
1448 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1450 return X86Operand::CreateMem(Val, Start, End, Size);
1453 InlineAsmIdentifierInfo Info;
1454 StringRef Identifier = Tok.getString();
1455 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info,
1456 /*Unevaluated*/ false, End))
1458 return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0,/*IndexReg=*/0,
1459 /*Scale=*/1, Start, End, Size, Identifier, Info);
1462 /// Parse the '.' operator.
1463 X86Operand *X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp,
1464 const MCExpr *&NewDisp) {
1465 const AsmToken &Tok = Parser.getTok();
1466 int64_t OrigDispVal, DotDispVal;
1468 // FIXME: Handle non-constant expressions.
1469 if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp))
1470 OrigDispVal = OrigDisp->getValue();
1472 return ErrorOperand(Tok.getLoc(), "Non-constant offsets are not supported!");
1475 StringRef DotDispStr = Tok.getString().drop_front(1);
1477 // .Imm gets lexed as a real.
1478 if (Tok.is(AsmToken::Real)) {
1480 DotDispStr.getAsInteger(10, DotDisp);
1481 DotDispVal = DotDisp.getZExtValue();
1482 } else if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1484 std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
1485 if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second,
1487 return ErrorOperand(Tok.getLoc(), "Unable to lookup field reference!");
1488 DotDispVal = DotDisp;
1490 return ErrorOperand(Tok.getLoc(), "Unexpected token type!");
1492 if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1493 SMLoc Loc = SMLoc::getFromPointer(DotDispStr.data());
1494 unsigned Len = DotDispStr.size();
1495 unsigned Val = OrigDispVal + DotDispVal;
1496 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_DotOperator, Loc, Len,
1500 NewDisp = MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext());
1504 /// Parse the 'offset' operator. This operator is used to specify the
1505 /// location rather then the content of a variable.
1506 X86Operand *X86AsmParser::ParseIntelOffsetOfOperator() {
1507 const AsmToken &Tok = Parser.getTok();
1508 SMLoc OffsetOfLoc = Tok.getLoc();
1509 Parser.Lex(); // Eat offset.
1512 InlineAsmIdentifierInfo Info;
1513 SMLoc Start = Tok.getLoc(), End;
1514 StringRef Identifier = Tok.getString();
1515 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info,
1516 /*Unevaluated*/ false, End))
1519 // Don't emit the offset operator.
1520 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Skip, OffsetOfLoc, 7));
1522 // The offset operator will have an 'r' constraint, thus we need to create
1523 // register operand to ensure proper matching. Just pick a GPR based on
1524 // the size of a pointer.
1525 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1526 return X86Operand::CreateReg(RegNo, Start, End, /*GetAddress=*/true,
1527 OffsetOfLoc, Identifier, Info.OpDecl);
1530 enum IntelOperatorKind {
1536 /// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators. The LENGTH operator
1537 /// returns the number of elements in an array. It returns the value 1 for
1538 /// non-array variables. The SIZE operator returns the size of a C or C++
1539 /// variable. A variable's size is the product of its LENGTH and TYPE. The
1540 /// TYPE operator returns the size of a C or C++ type or variable. If the
1541 /// variable is an array, TYPE returns the size of a single element.
1542 X86Operand *X86AsmParser::ParseIntelOperator(unsigned OpKind) {
1543 const AsmToken &Tok = Parser.getTok();
1544 SMLoc TypeLoc = Tok.getLoc();
1545 Parser.Lex(); // Eat operator.
1547 const MCExpr *Val = 0;
1548 InlineAsmIdentifierInfo Info;
1549 SMLoc Start = Tok.getLoc(), End;
1550 StringRef Identifier = Tok.getString();
1551 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info,
1552 /*Unevaluated*/ true, End))
1557 default: llvm_unreachable("Unexpected operand kind!");
1558 case IOK_LENGTH: CVal = Info.Length; break;
1559 case IOK_SIZE: CVal = Info.Size; break;
1560 case IOK_TYPE: CVal = Info.Type; break;
1563 // Rewrite the type operator and the C or C++ type or variable in terms of an
1564 // immediate. E.g. TYPE foo -> $$4
1565 unsigned Len = End.getPointer() - TypeLoc.getPointer();
1566 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, TypeLoc, Len, CVal));
1568 const MCExpr *Imm = MCConstantExpr::Create(CVal, getContext());
1569 return X86Operand::CreateImm(Imm, Start, End);
1572 X86Operand *X86AsmParser::ParseIntelOperand() {
1573 const AsmToken &Tok = Parser.getTok();
1574 SMLoc Start = Tok.getLoc(), End;
1576 // Offset, length, type and size operators.
1577 if (isParsingInlineAsm()) {
1578 StringRef AsmTokStr = Tok.getString();
1579 if (AsmTokStr == "offset" || AsmTokStr == "OFFSET")
1580 return ParseIntelOffsetOfOperator();
1581 if (AsmTokStr == "length" || AsmTokStr == "LENGTH")
1582 return ParseIntelOperator(IOK_LENGTH);
1583 if (AsmTokStr == "size" || AsmTokStr == "SIZE")
1584 return ParseIntelOperator(IOK_SIZE);
1585 if (AsmTokStr == "type" || AsmTokStr == "TYPE")
1586 return ParseIntelOperator(IOK_TYPE);
1590 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Minus) ||
1591 getLexer().is(AsmToken::LParen)) {
1592 AsmToken StartTok = Tok;
1593 IntelExprStateMachine SM(/*Imm=*/0, /*StopOnLBrac=*/true,
1594 /*AddImmPrefix=*/false);
1595 if (X86Operand *Err = ParseIntelExpression(SM, End))
1598 int64_t Imm = SM.getImm();
1599 if (isParsingInlineAsm()) {
1600 unsigned Len = Tok.getLoc().getPointer() - Start.getPointer();
1601 if (StartTok.getString().size() == Len)
1602 // Just add a prefix if this wasn't a complex immediate expression.
1603 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix, Start));
1605 // Otherwise, rewrite the complex expression as a single immediate.
1606 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, Start, Len, Imm));
1609 if (getLexer().isNot(AsmToken::LBrac)) {
1610 const MCExpr *ImmExpr = MCConstantExpr::Create(Imm, getContext());
1611 return X86Operand::CreateImm(ImmExpr, Start, End);
1614 // Only positive immediates are valid.
1616 return ErrorOperand(Start, "expected a positive immediate displacement "
1617 "before bracketed expr.");
1619 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1620 return ParseIntelMemOperand(/*SegReg=*/0, Imm, Start);
1625 if (!ParseRegister(RegNo, Start, End)) {
1626 // If this is a segment register followed by a ':', then this is the start
1627 // of a memory reference, otherwise this is a normal register reference.
1628 if (getLexer().isNot(AsmToken::Colon))
1629 return X86Operand::CreateReg(RegNo, Start, End);
1631 getParser().Lex(); // Eat the colon.
1632 return ParseIntelMemOperand(/*SegReg=*/RegNo, /*Disp=*/0, Start);
1636 return ParseIntelMemOperand(/*SegReg=*/0, /*Disp=*/0, Start);
1639 X86Operand *X86AsmParser::ParseATTOperand() {
1640 switch (getLexer().getKind()) {
1642 // Parse a memory operand with no segment register.
1643 return ParseMemOperand(0, Parser.getTok().getLoc());
1644 case AsmToken::Percent: {
1645 // Read the register.
1648 if (ParseRegister(RegNo, Start, End)) return 0;
1649 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
1650 Error(Start, "%eiz and %riz can only be used as index registers",
1651 SMRange(Start, End));
1655 // If this is a segment register followed by a ':', then this is the start
1656 // of a memory reference, otherwise this is a normal register reference.
1657 if (getLexer().isNot(AsmToken::Colon))
1658 return X86Operand::CreateReg(RegNo, Start, End);
1660 getParser().Lex(); // Eat the colon.
1661 return ParseMemOperand(RegNo, Start);
1663 case AsmToken::Dollar: {
1664 // $42 -> immediate.
1665 SMLoc Start = Parser.getTok().getLoc(), End;
1668 if (getParser().parseExpression(Val, End))
1670 return X86Operand::CreateImm(Val, Start, End);
1675 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
1676 /// has already been parsed if present.
1677 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
1679 // We have to disambiguate a parenthesized expression "(4+5)" from the start
1680 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
1681 // only way to do this without lookahead is to eat the '(' and see what is
1683 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
1684 if (getLexer().isNot(AsmToken::LParen)) {
1686 if (getParser().parseExpression(Disp, ExprEnd)) return 0;
1688 // After parsing the base expression we could either have a parenthesized
1689 // memory address or not. If not, return now. If so, eat the (.
1690 if (getLexer().isNot(AsmToken::LParen)) {
1691 // Unless we have a segment register, treat this as an immediate.
1693 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
1694 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1700 // Okay, we have a '('. We don't know if this is an expression or not, but
1701 // so we have to eat the ( to see beyond it.
1702 SMLoc LParenLoc = Parser.getTok().getLoc();
1703 Parser.Lex(); // Eat the '('.
1705 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
1706 // Nothing to do here, fall into the code below with the '(' part of the
1707 // memory operand consumed.
1711 // It must be an parenthesized expression, parse it now.
1712 if (getParser().parseParenExpression(Disp, ExprEnd))
1715 // After parsing the base expression we could either have a parenthesized
1716 // memory address or not. If not, return now. If so, eat the (.
1717 if (getLexer().isNot(AsmToken::LParen)) {
1718 // Unless we have a segment register, treat this as an immediate.
1720 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
1721 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1729 // If we reached here, then we just ate the ( of the memory operand. Process
1730 // the rest of the memory operand.
1731 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
1734 if (getLexer().is(AsmToken::Percent)) {
1735 SMLoc StartLoc, EndLoc;
1736 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
1737 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
1738 Error(StartLoc, "eiz and riz can only be used as index registers",
1739 SMRange(StartLoc, EndLoc));
1744 if (getLexer().is(AsmToken::Comma)) {
1745 Parser.Lex(); // Eat the comma.
1746 IndexLoc = Parser.getTok().getLoc();
1748 // Following the comma we should have either an index register, or a scale
1749 // value. We don't support the later form, but we want to parse it
1752 // Not that even though it would be completely consistent to support syntax
1753 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
1754 if (getLexer().is(AsmToken::Percent)) {
1756 if (ParseRegister(IndexReg, L, L)) return 0;
1758 if (getLexer().isNot(AsmToken::RParen)) {
1759 // Parse the scale amount:
1760 // ::= ',' [scale-expression]
1761 if (getLexer().isNot(AsmToken::Comma)) {
1762 Error(Parser.getTok().getLoc(),
1763 "expected comma in scale expression");
1766 Parser.Lex(); // Eat the comma.
1768 if (getLexer().isNot(AsmToken::RParen)) {
1769 SMLoc Loc = Parser.getTok().getLoc();
1772 if (getParser().parseAbsoluteExpression(ScaleVal)){
1773 Error(Loc, "expected scale expression");
1777 // Validate the scale amount.
1778 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
1779 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
1782 Scale = (unsigned)ScaleVal;
1785 } else if (getLexer().isNot(AsmToken::RParen)) {
1786 // A scale amount without an index is ignored.
1788 SMLoc Loc = Parser.getTok().getLoc();
1791 if (getParser().parseAbsoluteExpression(Value))
1795 Warning(Loc, "scale factor without index register is ignored");
1800 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1801 if (getLexer().isNot(AsmToken::RParen)) {
1802 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1805 SMLoc MemEnd = Parser.getTok().getEndLoc();
1806 Parser.Lex(); // Eat the ')'.
1808 // If we have both a base register and an index register make sure they are
1809 // both 64-bit or 32-bit registers.
1810 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1811 if (BaseReg != 0 && IndexReg != 0) {
1812 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1813 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1814 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1815 IndexReg != X86::RIZ) {
1816 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1819 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1820 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1821 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1822 IndexReg != X86::EIZ){
1823 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1828 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1833 ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
1834 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1836 StringRef PatchedName = Name;
1838 // FIXME: Hack to recognize setneb as setne.
1839 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1840 PatchedName != "setb" && PatchedName != "setnb")
1841 PatchedName = PatchedName.substr(0, Name.size()-1);
1843 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1844 const MCExpr *ExtraImmOp = 0;
1845 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1846 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1847 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1848 bool IsVCMP = PatchedName[0] == 'v';
1849 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1850 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1851 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1855 .Case("unord", 0x03)
1860 /* AVX only from here */
1861 .Case("eq_uq", 0x08)
1864 .Case("false", 0x0B)
1865 .Case("neq_oq", 0x0C)
1869 .Case("eq_os", 0x10)
1870 .Case("lt_oq", 0x11)
1871 .Case("le_oq", 0x12)
1872 .Case("unord_s", 0x13)
1873 .Case("neq_us", 0x14)
1874 .Case("nlt_uq", 0x15)
1875 .Case("nle_uq", 0x16)
1876 .Case("ord_s", 0x17)
1877 .Case("eq_us", 0x18)
1878 .Case("nge_uq", 0x19)
1879 .Case("ngt_uq", 0x1A)
1880 .Case("false_os", 0x1B)
1881 .Case("neq_os", 0x1C)
1882 .Case("ge_oq", 0x1D)
1883 .Case("gt_oq", 0x1E)
1884 .Case("true_us", 0x1F)
1886 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1887 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1888 getParser().getContext());
1889 if (PatchedName.endswith("ss")) {
1890 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1891 } else if (PatchedName.endswith("sd")) {
1892 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1893 } else if (PatchedName.endswith("ps")) {
1894 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1896 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1897 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1902 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1904 if (ExtraImmOp && !isParsingIntelSyntax())
1905 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1907 // Determine whether this is an instruction prefix.
1909 Name == "lock" || Name == "rep" ||
1910 Name == "repe" || Name == "repz" ||
1911 Name == "repne" || Name == "repnz" ||
1912 Name == "rex64" || Name == "data16";
1915 // This does the actual operand parsing. Don't parse any more if we have a
1916 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1917 // just want to parse the "lock" as the first instruction and the "incl" as
1919 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1921 // Parse '*' modifier.
1922 if (getLexer().is(AsmToken::Star)) {
1923 SMLoc Loc = Parser.getTok().getLoc();
1924 Operands.push_back(X86Operand::CreateToken("*", Loc));
1925 Parser.Lex(); // Eat the star.
1928 // Read the first operand.
1929 if (X86Operand *Op = ParseOperand())
1930 Operands.push_back(Op);
1932 Parser.eatToEndOfStatement();
1936 while (getLexer().is(AsmToken::Comma)) {
1937 Parser.Lex(); // Eat the comma.
1939 // Parse and remember the operand.
1940 if (X86Operand *Op = ParseOperand())
1941 Operands.push_back(Op);
1943 Parser.eatToEndOfStatement();
1948 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1949 SMLoc Loc = getLexer().getLoc();
1950 Parser.eatToEndOfStatement();
1951 return Error(Loc, "unexpected token in argument list");
1955 if (getLexer().is(AsmToken::EndOfStatement))
1956 Parser.Lex(); // Consume the EndOfStatement
1957 else if (isPrefix && getLexer().is(AsmToken::Slash))
1958 Parser.Lex(); // Consume the prefix separator Slash
1960 if (ExtraImmOp && isParsingIntelSyntax())
1961 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1963 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1964 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1965 // documented form in various unofficial manuals, so a lot of code uses it.
1966 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1967 Operands.size() == 3) {
1968 X86Operand &Op = *(X86Operand*)Operands.back();
1969 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1970 isa<MCConstantExpr>(Op.Mem.Disp) &&
1971 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1972 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1973 SMLoc Loc = Op.getEndLoc();
1974 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1978 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1979 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1980 Operands.size() == 3) {
1981 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1982 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1983 isa<MCConstantExpr>(Op.Mem.Disp) &&
1984 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1985 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1986 SMLoc Loc = Op.getEndLoc();
1987 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1991 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1992 if (Name.startswith("ins") && Operands.size() == 3 &&
1993 (Name == "insb" || Name == "insw" || Name == "insl")) {
1994 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1995 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1996 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1997 Operands.pop_back();
1998 Operands.pop_back();
2004 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
2005 if (Name.startswith("outs") && Operands.size() == 3 &&
2006 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
2007 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2008 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2009 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
2010 Operands.pop_back();
2011 Operands.pop_back();
2017 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
2018 if (Name.startswith("movs") && Operands.size() == 3 &&
2019 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
2020 (is64BitMode() && Name == "movsq"))) {
2021 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2022 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2023 if (isSrcOp(Op) && isDstOp(Op2)) {
2024 Operands.pop_back();
2025 Operands.pop_back();
2030 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
2031 if (Name.startswith("lods") && Operands.size() == 3 &&
2032 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
2033 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
2034 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2035 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2036 if (isSrcOp(*Op1) && Op2->isReg()) {
2038 unsigned reg = Op2->getReg();
2039 bool isLods = Name == "lods";
2040 if (reg == X86::AL && (isLods || Name == "lodsb"))
2042 else if (reg == X86::AX && (isLods || Name == "lodsw"))
2044 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
2046 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
2051 Operands.pop_back();
2052 Operands.pop_back();
2056 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2060 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
2061 if (Name.startswith("stos") && Operands.size() == 3 &&
2062 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
2063 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
2064 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2065 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2066 if (isDstOp(*Op2) && Op1->isReg()) {
2068 unsigned reg = Op1->getReg();
2069 bool isStos = Name == "stos";
2070 if (reg == X86::AL && (isStos || Name == "stosb"))
2072 else if (reg == X86::AX && (isStos || Name == "stosw"))
2074 else if (reg == X86::EAX && (isStos || Name == "stosl"))
2076 else if (reg == X86::RAX && (isStos || Name == "stosq"))
2081 Operands.pop_back();
2082 Operands.pop_back();
2086 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2091 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
2093 if ((Name.startswith("shr") || Name.startswith("sar") ||
2094 Name.startswith("shl") || Name.startswith("sal") ||
2095 Name.startswith("rcl") || Name.startswith("rcr") ||
2096 Name.startswith("rol") || Name.startswith("ror")) &&
2097 Operands.size() == 3) {
2098 if (isParsingIntelSyntax()) {
2100 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
2101 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2102 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2104 Operands.pop_back();
2107 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2108 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2109 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2111 Operands.erase(Operands.begin() + 1);
2116 // Transforms "int $3" into "int3" as a size optimization. We can't write an
2117 // instalias with an immediate operand yet.
2118 if (Name == "int" && Operands.size() == 2) {
2119 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2120 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2121 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
2123 Operands.erase(Operands.begin() + 1);
2124 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
2131 static bool convertToSExti8(MCInst &Inst, unsigned Opcode, unsigned Reg,
2134 TmpInst.setOpcode(Opcode);
2136 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2137 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2138 TmpInst.addOperand(Inst.getOperand(0));
2143 static bool convert16i16to16ri8(MCInst &Inst, unsigned Opcode,
2144 bool isCmp = false) {
2145 if (!Inst.getOperand(0).isImm() ||
2146 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
2149 return convertToSExti8(Inst, Opcode, X86::AX, isCmp);
2152 static bool convert32i32to32ri8(MCInst &Inst, unsigned Opcode,
2153 bool isCmp = false) {
2154 if (!Inst.getOperand(0).isImm() ||
2155 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
2158 return convertToSExti8(Inst, Opcode, X86::EAX, isCmp);
2161 static bool convert64i32to64ri8(MCInst &Inst, unsigned Opcode,
2162 bool isCmp = false) {
2163 if (!Inst.getOperand(0).isImm() ||
2164 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
2167 return convertToSExti8(Inst, Opcode, X86::RAX, isCmp);
2171 processInstruction(MCInst &Inst,
2172 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
2173 switch (Inst.getOpcode()) {
2174 default: return false;
2175 case X86::AND16i16: return convert16i16to16ri8(Inst, X86::AND16ri8);
2176 case X86::AND32i32: return convert32i32to32ri8(Inst, X86::AND32ri8);
2177 case X86::AND64i32: return convert64i32to64ri8(Inst, X86::AND64ri8);
2178 case X86::XOR16i16: return convert16i16to16ri8(Inst, X86::XOR16ri8);
2179 case X86::XOR32i32: return convert32i32to32ri8(Inst, X86::XOR32ri8);
2180 case X86::XOR64i32: return convert64i32to64ri8(Inst, X86::XOR64ri8);
2181 case X86::OR16i16: return convert16i16to16ri8(Inst, X86::OR16ri8);
2182 case X86::OR32i32: return convert32i32to32ri8(Inst, X86::OR32ri8);
2183 case X86::OR64i32: return convert64i32to64ri8(Inst, X86::OR64ri8);
2184 case X86::CMP16i16: return convert16i16to16ri8(Inst, X86::CMP16ri8, true);
2185 case X86::CMP32i32: return convert32i32to32ri8(Inst, X86::CMP32ri8, true);
2186 case X86::CMP64i32: return convert64i32to64ri8(Inst, X86::CMP64ri8, true);
2187 case X86::ADD16i16: return convert16i16to16ri8(Inst, X86::ADD16ri8);
2188 case X86::ADD32i32: return convert32i32to32ri8(Inst, X86::ADD32ri8);
2189 case X86::ADD64i32: return convert64i32to64ri8(Inst, X86::ADD64ri8);
2190 case X86::SUB16i16: return convert16i16to16ri8(Inst, X86::SUB16ri8);
2191 case X86::SUB32i32: return convert32i32to32ri8(Inst, X86::SUB32ri8);
2192 case X86::SUB64i32: return convert64i32to64ri8(Inst, X86::SUB64ri8);
2193 case X86::ADC16i16: return convert16i16to16ri8(Inst, X86::ADC16ri8);
2194 case X86::ADC32i32: return convert32i32to32ri8(Inst, X86::ADC32ri8);
2195 case X86::ADC64i32: return convert64i32to64ri8(Inst, X86::ADC64ri8);
2196 case X86::SBB16i16: return convert16i16to16ri8(Inst, X86::SBB16ri8);
2197 case X86::SBB32i32: return convert32i32to32ri8(Inst, X86::SBB32ri8);
2198 case X86::SBB64i32: return convert64i32to64ri8(Inst, X86::SBB64ri8);
2202 static const char *getSubtargetFeatureName(unsigned Val);
2204 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2205 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2206 MCStreamer &Out, unsigned &ErrorInfo,
2207 bool MatchingInlineAsm) {
2208 assert(!Operands.empty() && "Unexpect empty operand list!");
2209 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
2210 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
2211 ArrayRef<SMRange> EmptyRanges = None;
2213 // First, handle aliases that expand to multiple instructions.
2214 // FIXME: This should be replaced with a real .td file alias mechanism.
2215 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
2217 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
2218 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
2219 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
2220 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
2222 Inst.setOpcode(X86::WAIT);
2224 if (!MatchingInlineAsm)
2225 Out.EmitInstruction(Inst);
2228 StringSwitch<const char*>(Op->getToken())
2229 .Case("finit", "fninit")
2230 .Case("fsave", "fnsave")
2231 .Case("fstcw", "fnstcw")
2232 .Case("fstcww", "fnstcw")
2233 .Case("fstenv", "fnstenv")
2234 .Case("fstsw", "fnstsw")
2235 .Case("fstsww", "fnstsw")
2236 .Case("fclex", "fnclex")
2238 assert(Repl && "Unknown wait-prefixed instruction");
2240 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
2243 bool WasOriginallyInvalidOperand = false;
2246 // First, try a direct match.
2247 switch (MatchInstructionImpl(Operands, Inst,
2248 ErrorInfo, MatchingInlineAsm,
2249 isParsingIntelSyntax())) {
2252 // Some instructions need post-processing to, for example, tweak which
2253 // encoding is selected. Loop on it while changes happen so the
2254 // individual transformations can chain off each other.
2255 if (!MatchingInlineAsm)
2256 while (processInstruction(Inst, Operands))
2260 if (!MatchingInlineAsm)
2261 Out.EmitInstruction(Inst);
2262 Opcode = Inst.getOpcode();
2264 case Match_MissingFeature: {
2265 assert(ErrorInfo && "Unknown missing feature!");
2266 // Special case the error message for the very common case where only
2267 // a single subtarget feature is missing.
2268 std::string Msg = "instruction requires:";
2270 for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
2271 if (ErrorInfo & Mask) {
2273 Msg += getSubtargetFeatureName(ErrorInfo & Mask);
2277 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2279 case Match_InvalidOperand:
2280 WasOriginallyInvalidOperand = true;
2282 case Match_MnemonicFail:
2286 // FIXME: Ideally, we would only attempt suffix matches for things which are
2287 // valid prefixes, and we could just infer the right unambiguous
2288 // type. However, that requires substantially more matcher support than the
2291 // Change the operand to point to a temporary token.
2292 StringRef Base = Op->getToken();
2293 SmallString<16> Tmp;
2296 Op->setTokenValue(Tmp.str());
2298 // If this instruction starts with an 'f', then it is a floating point stack
2299 // instruction. These come in up to three forms for 32-bit, 64-bit, and
2300 // 80-bit floating point, which use the suffixes s,l,t respectively.
2302 // Otherwise, we assume that this may be an integer instruction, which comes
2303 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
2304 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
2306 // Check for the various suffix matches.
2307 Tmp[Base.size()] = Suffixes[0];
2308 unsigned ErrorInfoIgnore;
2309 unsigned ErrorInfoMissingFeature = 0; // Init suppresses compiler warnings.
2310 unsigned Match1, Match2, Match3, Match4;
2312 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2313 MatchingInlineAsm, isParsingIntelSyntax());
2314 // If this returned as a missing feature failure, remember that.
2315 if (Match1 == Match_MissingFeature)
2316 ErrorInfoMissingFeature = ErrorInfoIgnore;
2317 Tmp[Base.size()] = Suffixes[1];
2318 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2319 MatchingInlineAsm, isParsingIntelSyntax());
2320 // If this returned as a missing feature failure, remember that.
2321 if (Match2 == Match_MissingFeature)
2322 ErrorInfoMissingFeature = ErrorInfoIgnore;
2323 Tmp[Base.size()] = Suffixes[2];
2324 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2325 MatchingInlineAsm, isParsingIntelSyntax());
2326 // If this returned as a missing feature failure, remember that.
2327 if (Match3 == Match_MissingFeature)
2328 ErrorInfoMissingFeature = ErrorInfoIgnore;
2329 Tmp[Base.size()] = Suffixes[3];
2330 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2331 MatchingInlineAsm, isParsingIntelSyntax());
2332 // If this returned as a missing feature failure, remember that.
2333 if (Match4 == Match_MissingFeature)
2334 ErrorInfoMissingFeature = ErrorInfoIgnore;
2336 // Restore the old token.
2337 Op->setTokenValue(Base);
2339 // If exactly one matched, then we treat that as a successful match (and the
2340 // instruction will already have been filled in correctly, since the failing
2341 // matches won't have modified it).
2342 unsigned NumSuccessfulMatches =
2343 (Match1 == Match_Success) + (Match2 == Match_Success) +
2344 (Match3 == Match_Success) + (Match4 == Match_Success);
2345 if (NumSuccessfulMatches == 1) {
2347 if (!MatchingInlineAsm)
2348 Out.EmitInstruction(Inst);
2349 Opcode = Inst.getOpcode();
2353 // Otherwise, the match failed, try to produce a decent error message.
2355 // If we had multiple suffix matches, then identify this as an ambiguous
2357 if (NumSuccessfulMatches > 1) {
2359 unsigned NumMatches = 0;
2360 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
2361 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
2362 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
2363 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
2365 SmallString<126> Msg;
2366 raw_svector_ostream OS(Msg);
2367 OS << "ambiguous instructions require an explicit suffix (could be ";
2368 for (unsigned i = 0; i != NumMatches; ++i) {
2371 if (i + 1 == NumMatches)
2373 OS << "'" << Base << MatchChars[i] << "'";
2376 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
2380 // Okay, we know that none of the variants matched successfully.
2382 // If all of the instructions reported an invalid mnemonic, then the original
2383 // mnemonic was invalid.
2384 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
2385 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
2386 if (!WasOriginallyInvalidOperand) {
2387 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
2389 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
2390 Ranges, MatchingInlineAsm);
2393 // Recover location info for the operand if we know which was the problem.
2394 if (ErrorInfo != ~0U) {
2395 if (ErrorInfo >= Operands.size())
2396 return Error(IDLoc, "too few operands for instruction",
2397 EmptyRanges, MatchingInlineAsm);
2399 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
2400 if (Operand->getStartLoc().isValid()) {
2401 SMRange OperandRange = Operand->getLocRange();
2402 return Error(Operand->getStartLoc(), "invalid operand for instruction",
2403 OperandRange, MatchingInlineAsm);
2407 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2411 // If one instruction matched with a missing feature, report this as a
2413 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
2414 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
2415 std::string Msg = "instruction requires:";
2417 for (unsigned i = 0; i < (sizeof(ErrorInfoMissingFeature)*8-1); ++i) {
2418 if (ErrorInfoMissingFeature & Mask) {
2420 Msg += getSubtargetFeatureName(ErrorInfoMissingFeature & Mask);
2424 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2427 // If one instruction matched with an invalid operand, report this as an
2429 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
2430 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
2431 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2436 // If all of these were an outright failure, report it in a useless way.
2437 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
2438 EmptyRanges, MatchingInlineAsm);
2443 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
2444 StringRef IDVal = DirectiveID.getIdentifier();
2445 if (IDVal == ".word")
2446 return ParseDirectiveWord(2, DirectiveID.getLoc());
2447 else if (IDVal.startswith(".code"))
2448 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
2449 else if (IDVal.startswith(".att_syntax")) {
2450 getParser().setAssemblerDialect(0);
2452 } else if (IDVal.startswith(".intel_syntax")) {
2453 getParser().setAssemblerDialect(1);
2454 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2455 if(Parser.getTok().getString() == "noprefix") {
2456 // FIXME : Handle noprefix
2466 /// ParseDirectiveWord
2467 /// ::= .word [ expression (, expression)* ]
2468 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
2469 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2471 const MCExpr *Value;
2472 if (getParser().parseExpression(Value))
2475 getParser().getStreamer().EmitValue(Value, Size);
2477 if (getLexer().is(AsmToken::EndOfStatement))
2480 // FIXME: Improve diagnostic.
2481 if (getLexer().isNot(AsmToken::Comma))
2482 return Error(L, "unexpected token in directive");
2491 /// ParseDirectiveCode
2492 /// ::= .code32 | .code64
2493 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
2494 if (IDVal == ".code32") {
2496 if (is64BitMode()) {
2498 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
2500 } else if (IDVal == ".code64") {
2502 if (!is64BitMode()) {
2504 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
2507 return Error(L, "unexpected directive " + IDVal);
2513 // Force static initialization.
2514 extern "C" void LLVMInitializeX86AsmParser() {
2515 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
2516 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
2519 #define GET_REGISTER_MATCHER
2520 #define GET_MATCHER_IMPLEMENTATION
2521 #define GET_SUBTARGET_FEATURE_NAME
2522 #include "X86GenAsmMatcher.inc"