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(); }
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();
122 } else if (StackOp == IC_LPAREN) {
124 InfixOperatorStack.pop_back();
126 InfixOperatorStack.pop_back();
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;
834 bool isMemVZ32() const {
835 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
836 getMemIndexReg() >= X86::ZMM0 && getMemIndexReg() <= X86::ZMM31;
838 bool isMemVZ64() const {
839 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
840 getMemIndexReg() >= X86::ZMM0 && getMemIndexReg() <= X86::ZMM31;
843 bool isMem512() const {
844 return Kind == Memory && (!Mem.Size || Mem.Size == 512);
847 bool isAbsMem() const {
848 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
849 !getMemIndexReg() && getMemScale() == 1;
852 bool isMemOffs8() const {
853 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
854 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 8);
856 bool isMemOffs16() const {
857 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
858 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 16);
860 bool isMemOffs32() const {
861 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
862 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 32);
864 bool isMemOffs64() const {
865 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
866 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 64);
869 bool isReg() const { return Kind == Register; }
871 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
872 // Add as immediates when possible.
873 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
874 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
876 Inst.addOperand(MCOperand::CreateExpr(Expr));
879 void addRegOperands(MCInst &Inst, unsigned N) const {
880 assert(N == 1 && "Invalid number of operands!");
881 Inst.addOperand(MCOperand::CreateReg(getReg()));
884 void addImmOperands(MCInst &Inst, unsigned N) const {
885 assert(N == 1 && "Invalid number of operands!");
886 addExpr(Inst, getImm());
889 void addMem8Operands(MCInst &Inst, unsigned N) const {
890 addMemOperands(Inst, N);
892 void addMem16Operands(MCInst &Inst, unsigned N) const {
893 addMemOperands(Inst, N);
895 void addMem32Operands(MCInst &Inst, unsigned N) const {
896 addMemOperands(Inst, N);
898 void addMem64Operands(MCInst &Inst, unsigned N) const {
899 addMemOperands(Inst, N);
901 void addMem80Operands(MCInst &Inst, unsigned N) const {
902 addMemOperands(Inst, N);
904 void addMem128Operands(MCInst &Inst, unsigned N) const {
905 addMemOperands(Inst, N);
907 void addMem256Operands(MCInst &Inst, unsigned N) const {
908 addMemOperands(Inst, N);
910 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
911 addMemOperands(Inst, N);
913 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
914 addMemOperands(Inst, N);
916 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
917 addMemOperands(Inst, N);
919 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
920 addMemOperands(Inst, N);
923 void addMemVZ32Operands(MCInst &Inst, unsigned N) const {
924 addMemOperands(Inst, N);
926 void addMemVZ64Operands(MCInst &Inst, unsigned N) const {
927 addMemOperands(Inst, N);
929 void addMem512Operands(MCInst &Inst, unsigned N) const {
930 addMemOperands(Inst, N);
933 void addMemOperands(MCInst &Inst, unsigned N) const {
934 assert((N == 5) && "Invalid number of operands!");
935 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
936 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
937 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
938 addExpr(Inst, getMemDisp());
939 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
942 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
943 assert((N == 1) && "Invalid number of operands!");
944 // Add as immediates when possible.
945 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
946 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
948 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
951 void addMemOffs8Operands(MCInst &Inst, unsigned N) const {
952 addMemOffsOperands(Inst, N);
954 void addMemOffs16Operands(MCInst &Inst, unsigned N) const {
955 addMemOffsOperands(Inst, N);
957 void addMemOffs32Operands(MCInst &Inst, unsigned N) const {
958 addMemOffsOperands(Inst, N);
960 void addMemOffs64Operands(MCInst &Inst, unsigned N) const {
961 addMemOffsOperands(Inst, N);
964 void addMemOffsOperands(MCInst &Inst, unsigned N) const {
965 assert((N == 1) && "Invalid number of operands!");
966 // Add as immediates when possible.
967 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
968 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
970 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
973 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
974 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size());
975 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
976 Res->Tok.Data = Str.data();
977 Res->Tok.Length = Str.size();
981 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
982 bool AddressOf = false,
983 SMLoc OffsetOfLoc = SMLoc(),
984 StringRef SymName = StringRef(),
986 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
987 Res->Reg.RegNo = RegNo;
988 Res->AddressOf = AddressOf;
989 Res->OffsetOfLoc = OffsetOfLoc;
990 Res->SymName = SymName;
991 Res->OpDecl = OpDecl;
995 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
996 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
1001 /// Create an absolute memory operand.
1002 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc,
1003 unsigned Size = 0, StringRef SymName = StringRef(),
1005 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
1006 Res->Mem.SegReg = 0;
1007 Res->Mem.Disp = Disp;
1008 Res->Mem.BaseReg = 0;
1009 Res->Mem.IndexReg = 0;
1011 Res->Mem.Size = Size;
1012 Res->SymName = SymName;
1013 Res->OpDecl = OpDecl;
1014 Res->AddressOf = false;
1018 /// Create a generalized memory operand.
1019 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
1020 unsigned BaseReg, unsigned IndexReg,
1021 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
1023 StringRef SymName = StringRef(),
1025 // We should never just have a displacement, that should be parsed as an
1026 // absolute memory operand.
1027 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
1029 // The scale should always be one of {1,2,4,8}.
1030 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
1032 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
1033 Res->Mem.SegReg = SegReg;
1034 Res->Mem.Disp = Disp;
1035 Res->Mem.BaseReg = BaseReg;
1036 Res->Mem.IndexReg = IndexReg;
1037 Res->Mem.Scale = Scale;
1038 Res->Mem.Size = Size;
1039 Res->SymName = SymName;
1040 Res->OpDecl = OpDecl;
1041 Res->AddressOf = false;
1046 } // end anonymous namespace.
1048 bool X86AsmParser::isSrcOp(X86Operand &Op) {
1049 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
1051 return (Op.isMem() &&
1052 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
1053 isa<MCConstantExpr>(Op.Mem.Disp) &&
1054 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1055 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
1058 bool X86AsmParser::isDstOp(X86Operand &Op) {
1059 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
1061 return Op.isMem() &&
1062 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
1063 isa<MCConstantExpr>(Op.Mem.Disp) &&
1064 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1065 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
1068 bool X86AsmParser::ParseRegister(unsigned &RegNo,
1069 SMLoc &StartLoc, SMLoc &EndLoc) {
1071 const AsmToken &PercentTok = Parser.getTok();
1072 StartLoc = PercentTok.getLoc();
1074 // If we encounter a %, ignore it. This code handles registers with and
1075 // without the prefix, unprefixed registers can occur in cfi directives.
1076 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
1077 Parser.Lex(); // Eat percent token.
1079 const AsmToken &Tok = Parser.getTok();
1080 EndLoc = Tok.getEndLoc();
1082 if (Tok.isNot(AsmToken::Identifier)) {
1083 if (isParsingIntelSyntax()) return true;
1084 return Error(StartLoc, "invalid register name",
1085 SMRange(StartLoc, EndLoc));
1088 RegNo = MatchRegisterName(Tok.getString());
1090 // If the match failed, try the register name as lowercase.
1092 RegNo = MatchRegisterName(Tok.getString().lower());
1094 if (!is64BitMode()) {
1095 // FIXME: This should be done using Requires<In32BitMode> and
1096 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
1098 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
1100 if (RegNo == X86::RIZ ||
1101 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
1102 X86II::isX86_64NonExtLowByteReg(RegNo) ||
1103 X86II::isX86_64ExtendedReg(RegNo))
1104 return Error(StartLoc, "register %"
1105 + Tok.getString() + " is only available in 64-bit mode",
1106 SMRange(StartLoc, EndLoc));
1109 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
1110 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
1112 Parser.Lex(); // Eat 'st'
1114 // Check to see if we have '(4)' after %st.
1115 if (getLexer().isNot(AsmToken::LParen))
1120 const AsmToken &IntTok = Parser.getTok();
1121 if (IntTok.isNot(AsmToken::Integer))
1122 return Error(IntTok.getLoc(), "expected stack index");
1123 switch (IntTok.getIntVal()) {
1124 case 0: RegNo = X86::ST0; break;
1125 case 1: RegNo = X86::ST1; break;
1126 case 2: RegNo = X86::ST2; break;
1127 case 3: RegNo = X86::ST3; break;
1128 case 4: RegNo = X86::ST4; break;
1129 case 5: RegNo = X86::ST5; break;
1130 case 6: RegNo = X86::ST6; break;
1131 case 7: RegNo = X86::ST7; break;
1132 default: return Error(IntTok.getLoc(), "invalid stack index");
1135 if (getParser().Lex().isNot(AsmToken::RParen))
1136 return Error(Parser.getTok().getLoc(), "expected ')'");
1138 EndLoc = Parser.getTok().getEndLoc();
1139 Parser.Lex(); // Eat ')'
1143 EndLoc = Parser.getTok().getEndLoc();
1145 // If this is "db[0-7]", match it as an alias
1147 if (RegNo == 0 && Tok.getString().size() == 3 &&
1148 Tok.getString().startswith("db")) {
1149 switch (Tok.getString()[2]) {
1150 case '0': RegNo = X86::DR0; break;
1151 case '1': RegNo = X86::DR1; break;
1152 case '2': RegNo = X86::DR2; break;
1153 case '3': RegNo = X86::DR3; break;
1154 case '4': RegNo = X86::DR4; break;
1155 case '5': RegNo = X86::DR5; break;
1156 case '6': RegNo = X86::DR6; break;
1157 case '7': RegNo = X86::DR7; break;
1161 EndLoc = Parser.getTok().getEndLoc();
1162 Parser.Lex(); // Eat it.
1168 if (isParsingIntelSyntax()) return true;
1169 return Error(StartLoc, "invalid register name",
1170 SMRange(StartLoc, EndLoc));
1173 Parser.Lex(); // Eat identifier token.
1177 X86Operand *X86AsmParser::ParseOperand() {
1178 if (isParsingIntelSyntax())
1179 return ParseIntelOperand();
1180 return ParseATTOperand();
1183 /// getIntelMemOperandSize - Return intel memory operand size.
1184 static unsigned getIntelMemOperandSize(StringRef OpStr) {
1185 unsigned Size = StringSwitch<unsigned>(OpStr)
1186 .Cases("BYTE", "byte", 8)
1187 .Cases("WORD", "word", 16)
1188 .Cases("DWORD", "dword", 32)
1189 .Cases("QWORD", "qword", 64)
1190 .Cases("XWORD", "xword", 80)
1191 .Cases("XMMWORD", "xmmword", 128)
1192 .Cases("YMMWORD", "ymmword", 256)
1198 X86AsmParser::CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
1199 unsigned BaseReg, unsigned IndexReg,
1200 unsigned Scale, SMLoc Start, SMLoc End,
1201 unsigned Size, StringRef Identifier,
1202 InlineAsmIdentifierInfo &Info){
1203 if (isa<MCSymbolRefExpr>(Disp)) {
1204 // If this is not a VarDecl then assume it is a FuncDecl or some other label
1205 // reference. We need an 'r' constraint here, so we need to create register
1206 // operand to ensure proper matching. Just pick a GPR based on the size of
1208 if (!Info.IsVarDecl) {
1209 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1210 return X86Operand::CreateReg(RegNo, Start, End, /*AddressOf=*/true,
1211 SMLoc(), Identifier, Info.OpDecl);
1214 Size = Info.Type * 8; // Size is in terms of bits in this context.
1216 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_SizeDirective, Start,
1221 // When parsing inline assembly we set the base register to a non-zero value
1222 // if we don't know the actual value at this time. This is necessary to
1223 // get the matching correct in some cases.
1224 BaseReg = BaseReg ? BaseReg : 1;
1225 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1226 End, Size, Identifier, Info.OpDecl);
1230 RewriteIntelBracExpression(SmallVectorImpl<AsmRewrite> *AsmRewrites,
1231 StringRef SymName, int64_t ImmDisp,
1232 int64_t FinalImmDisp, SMLoc &BracLoc,
1233 SMLoc &StartInBrac, SMLoc &End) {
1234 // Remove the '[' and ']' from the IR string.
1235 AsmRewrites->push_back(AsmRewrite(AOK_Skip, BracLoc, 1));
1236 AsmRewrites->push_back(AsmRewrite(AOK_Skip, End, 1));
1238 // If ImmDisp is non-zero, then we parsed a displacement before the
1239 // bracketed expression (i.e., ImmDisp [ BaseReg + Scale*IndexReg + Disp])
1240 // If ImmDisp doesn't match the displacement computed by the state machine
1241 // then we have an additional displacement in the bracketed expression.
1242 if (ImmDisp != FinalImmDisp) {
1244 // We have an immediate displacement before the bracketed expression.
1245 // Adjust this to match the final immediate displacement.
1247 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1248 E = AsmRewrites->end(); I != E; ++I) {
1249 if ((*I).Loc.getPointer() > BracLoc.getPointer())
1251 if ((*I).Kind == AOK_ImmPrefix || (*I).Kind == AOK_Imm) {
1252 assert (!Found && "ImmDisp already rewritten.");
1253 (*I).Kind = AOK_Imm;
1254 (*I).Len = BracLoc.getPointer() - (*I).Loc.getPointer();
1255 (*I).Val = FinalImmDisp;
1260 assert (Found && "Unable to rewrite ImmDisp.");
1263 // We have a symbolic and an immediate displacement, but no displacement
1264 // before the bracketed expression. Put the immediate displacement
1265 // before the bracketed expression.
1266 AsmRewrites->push_back(AsmRewrite(AOK_Imm, BracLoc, 0, FinalImmDisp));
1269 // Remove all the ImmPrefix rewrites within the brackets.
1270 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1271 E = AsmRewrites->end(); I != E; ++I) {
1272 if ((*I).Loc.getPointer() < StartInBrac.getPointer())
1274 if ((*I).Kind == AOK_ImmPrefix)
1275 (*I).Kind = AOK_Delete;
1277 const char *SymLocPtr = SymName.data();
1278 // Skip everything before the symbol.
1279 if (unsigned Len = SymLocPtr - StartInBrac.getPointer()) {
1280 assert(Len > 0 && "Expected a non-negative length.");
1281 AsmRewrites->push_back(AsmRewrite(AOK_Skip, StartInBrac, Len));
1283 // Skip everything after the symbol.
1284 if (unsigned Len = End.getPointer() - (SymLocPtr + SymName.size())) {
1285 SMLoc Loc = SMLoc::getFromPointer(SymLocPtr + SymName.size());
1286 assert(Len > 0 && "Expected a non-negative length.");
1287 AsmRewrites->push_back(AsmRewrite(AOK_Skip, Loc, Len));
1292 X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) {
1293 const AsmToken &Tok = Parser.getTok();
1297 bool UpdateLocLex = true;
1299 // The period in the dot operator (e.g., [ebx].foo.bar) is parsed as an
1300 // identifier. Don't try an parse it as a register.
1301 if (Tok.getString().startswith("."))
1304 // If we're parsing an immediate expression, we don't expect a '['.
1305 if (SM.getStopOnLBrac() && getLexer().getKind() == AsmToken::LBrac)
1308 switch (getLexer().getKind()) {
1310 if (SM.isValidEndState()) {
1314 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1316 case AsmToken::EndOfStatement: {
1320 case AsmToken::Identifier: {
1321 // This could be a register or a symbolic displacement.
1324 SMLoc IdentLoc = Tok.getLoc();
1325 StringRef Identifier = Tok.getString();
1326 if(!ParseRegister(TmpReg, IdentLoc, End)) {
1327 SM.onRegister(TmpReg);
1328 UpdateLocLex = false;
1331 if (!isParsingInlineAsm()) {
1332 if (getParser().parsePrimaryExpr(Val, End))
1333 return ErrorOperand(Tok.getLoc(), "Unexpected identifier!");
1335 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1336 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info,
1337 /*Unevaluated*/ false, End))
1340 SM.onIdentifierExpr(Val, Identifier);
1341 UpdateLocLex = false;
1344 return ErrorOperand(Tok.getLoc(), "Unexpected identifier!");
1346 case AsmToken::Integer:
1347 if (isParsingInlineAsm() && SM.getAddImmPrefix())
1348 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1350 SM.onInteger(Tok.getIntVal());
1352 case AsmToken::Plus: SM.onPlus(); break;
1353 case AsmToken::Minus: SM.onMinus(); break;
1354 case AsmToken::Star: SM.onStar(); break;
1355 case AsmToken::Slash: SM.onDivide(); break;
1356 case AsmToken::LBrac: SM.onLBrac(); break;
1357 case AsmToken::RBrac: SM.onRBrac(); break;
1358 case AsmToken::LParen: SM.onLParen(); break;
1359 case AsmToken::RParen: SM.onRParen(); break;
1362 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1364 if (!Done && UpdateLocLex) {
1366 Parser.Lex(); // Consume the token.
1372 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
1375 const AsmToken &Tok = Parser.getTok();
1376 SMLoc BracLoc = Tok.getLoc(), End = Tok.getEndLoc();
1377 if (getLexer().isNot(AsmToken::LBrac))
1378 return ErrorOperand(BracLoc, "Expected '[' token!");
1379 Parser.Lex(); // Eat '['
1381 SMLoc StartInBrac = Tok.getLoc();
1382 // Parse [ Symbol + ImmDisp ] and [ BaseReg + Scale*IndexReg + ImmDisp ]. We
1383 // may have already parsed an immediate displacement before the bracketed
1385 IntelExprStateMachine SM(ImmDisp, /*StopOnLBrac=*/false, /*AddImmPrefix=*/true);
1386 if (X86Operand *Err = ParseIntelExpression(SM, End))
1390 if (const MCExpr *Sym = SM.getSym()) {
1391 // A symbolic displacement.
1393 if (isParsingInlineAsm())
1394 RewriteIntelBracExpression(InstInfo->AsmRewrites, SM.getSymName(),
1395 ImmDisp, SM.getImm(), BracLoc, StartInBrac,
1398 // An immediate displacement only.
1399 Disp = MCConstantExpr::Create(SM.getImm(), getContext());
1402 // Parse the dot operator (e.g., [ebx].foo.bar).
1403 if (Tok.getString().startswith(".")) {
1404 const MCExpr *NewDisp;
1405 if (X86Operand *Err = ParseIntelDotOperator(Disp, NewDisp))
1408 End = Tok.getEndLoc();
1409 Parser.Lex(); // Eat the field.
1413 int BaseReg = SM.getBaseReg();
1414 int IndexReg = SM.getIndexReg();
1415 int Scale = SM.getScale();
1416 if (!isParsingInlineAsm()) {
1418 if (!BaseReg && !IndexReg) {
1420 return X86Operand::CreateMem(Disp, Start, End, Size);
1422 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, Start, End, Size);
1424 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1428 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1429 return CreateMemForInlineAsm(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1430 End, Size, SM.getSymName(), Info);
1433 // Inline assembly may use variable names with namespace alias qualifiers.
1434 X86Operand *X86AsmParser::ParseIntelIdentifier(const MCExpr *&Val,
1435 StringRef &Identifier,
1436 InlineAsmIdentifierInfo &Info,
1437 bool IsUnevaluatedOperand,
1439 assert (isParsingInlineAsm() && "Expected to be parsing inline assembly.");
1442 StringRef LineBuf(Identifier.data());
1443 SemaCallback->LookupInlineAsmIdentifier(LineBuf, Info, IsUnevaluatedOperand);
1445 const AsmToken &Tok = Parser.getTok();
1447 // Advance the token stream until the end of the current token is
1448 // after the end of what the frontend claimed.
1449 const char *EndPtr = Tok.getLoc().getPointer() + LineBuf.size();
1451 End = Tok.getEndLoc();
1454 assert(End.getPointer() <= EndPtr && "frontend claimed part of a token?");
1455 if (End.getPointer() == EndPtr) break;
1458 // Create the symbol reference.
1459 Identifier = LineBuf;
1460 MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier);
1461 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1462 Val = MCSymbolRefExpr::Create(Sym, Variant, getParser().getContext());
1466 /// ParseIntelMemOperand - Parse intel style memory operand.
1467 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg,
1470 const AsmToken &Tok = Parser.getTok();
1473 unsigned Size = getIntelMemOperandSize(Tok.getString());
1475 Parser.Lex(); // Eat operand size (e.g., byte, word).
1476 if (Tok.getString() != "PTR" && Tok.getString() != "ptr")
1477 return ErrorOperand(Start, "Expected 'PTR' or 'ptr' token!");
1478 Parser.Lex(); // Eat ptr.
1481 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1482 if (getLexer().is(AsmToken::Integer)) {
1483 if (isParsingInlineAsm())
1484 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1486 int64_t ImmDisp = Tok.getIntVal();
1487 Parser.Lex(); // Eat the integer.
1488 if (getLexer().isNot(AsmToken::LBrac))
1489 return ErrorOperand(Start, "Expected '[' token!");
1490 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1493 if (getLexer().is(AsmToken::LBrac))
1494 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1496 if (!ParseRegister(SegReg, Start, End)) {
1497 // Handel SegReg : [ ... ]
1498 if (getLexer().isNot(AsmToken::Colon))
1499 return ErrorOperand(Start, "Expected ':' token!");
1500 Parser.Lex(); // Eat :
1501 if (getLexer().isNot(AsmToken::LBrac))
1502 return ErrorOperand(Start, "Expected '[' token!");
1503 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1507 if (!isParsingInlineAsm()) {
1508 if (getParser().parsePrimaryExpr(Val, End))
1509 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1511 return X86Operand::CreateMem(Val, Start, End, Size);
1514 InlineAsmIdentifierInfo Info;
1515 StringRef Identifier = Tok.getString();
1516 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info,
1517 /*Unevaluated*/ false, End))
1519 return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0,/*IndexReg=*/0,
1520 /*Scale=*/1, Start, End, Size, Identifier, Info);
1523 /// Parse the '.' operator.
1524 X86Operand *X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp,
1525 const MCExpr *&NewDisp) {
1526 const AsmToken &Tok = Parser.getTok();
1527 int64_t OrigDispVal, DotDispVal;
1529 // FIXME: Handle non-constant expressions.
1530 if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp))
1531 OrigDispVal = OrigDisp->getValue();
1533 return ErrorOperand(Tok.getLoc(), "Non-constant offsets are not supported!");
1536 StringRef DotDispStr = Tok.getString().drop_front(1);
1538 // .Imm gets lexed as a real.
1539 if (Tok.is(AsmToken::Real)) {
1541 DotDispStr.getAsInteger(10, DotDisp);
1542 DotDispVal = DotDisp.getZExtValue();
1543 } else if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1545 std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
1546 if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second,
1548 return ErrorOperand(Tok.getLoc(), "Unable to lookup field reference!");
1549 DotDispVal = DotDisp;
1551 return ErrorOperand(Tok.getLoc(), "Unexpected token type!");
1553 if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1554 SMLoc Loc = SMLoc::getFromPointer(DotDispStr.data());
1555 unsigned Len = DotDispStr.size();
1556 unsigned Val = OrigDispVal + DotDispVal;
1557 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_DotOperator, Loc, Len,
1561 NewDisp = MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext());
1565 /// Parse the 'offset' operator. This operator is used to specify the
1566 /// location rather then the content of a variable.
1567 X86Operand *X86AsmParser::ParseIntelOffsetOfOperator() {
1568 const AsmToken &Tok = Parser.getTok();
1569 SMLoc OffsetOfLoc = Tok.getLoc();
1570 Parser.Lex(); // Eat offset.
1573 InlineAsmIdentifierInfo Info;
1574 SMLoc Start = Tok.getLoc(), End;
1575 StringRef Identifier = Tok.getString();
1576 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info,
1577 /*Unevaluated*/ false, End))
1580 // Don't emit the offset operator.
1581 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Skip, OffsetOfLoc, 7));
1583 // The offset operator will have an 'r' constraint, thus we need to create
1584 // register operand to ensure proper matching. Just pick a GPR based on
1585 // the size of a pointer.
1586 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1587 return X86Operand::CreateReg(RegNo, Start, End, /*GetAddress=*/true,
1588 OffsetOfLoc, Identifier, Info.OpDecl);
1591 enum IntelOperatorKind {
1597 /// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators. The LENGTH operator
1598 /// returns the number of elements in an array. It returns the value 1 for
1599 /// non-array variables. The SIZE operator returns the size of a C or C++
1600 /// variable. A variable's size is the product of its LENGTH and TYPE. The
1601 /// TYPE operator returns the size of a C or C++ type or variable. If the
1602 /// variable is an array, TYPE returns the size of a single element.
1603 X86Operand *X86AsmParser::ParseIntelOperator(unsigned OpKind) {
1604 const AsmToken &Tok = Parser.getTok();
1605 SMLoc TypeLoc = Tok.getLoc();
1606 Parser.Lex(); // Eat operator.
1608 const MCExpr *Val = 0;
1609 InlineAsmIdentifierInfo Info;
1610 SMLoc Start = Tok.getLoc(), End;
1611 StringRef Identifier = Tok.getString();
1612 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info,
1613 /*Unevaluated*/ true, End))
1618 default: llvm_unreachable("Unexpected operand kind!");
1619 case IOK_LENGTH: CVal = Info.Length; break;
1620 case IOK_SIZE: CVal = Info.Size; break;
1621 case IOK_TYPE: CVal = Info.Type; break;
1624 // Rewrite the type operator and the C or C++ type or variable in terms of an
1625 // immediate. E.g. TYPE foo -> $$4
1626 unsigned Len = End.getPointer() - TypeLoc.getPointer();
1627 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, TypeLoc, Len, CVal));
1629 const MCExpr *Imm = MCConstantExpr::Create(CVal, getContext());
1630 return X86Operand::CreateImm(Imm, Start, End);
1633 X86Operand *X86AsmParser::ParseIntelOperand() {
1634 const AsmToken &Tok = Parser.getTok();
1635 SMLoc Start = Tok.getLoc(), End;
1637 // Offset, length, type and size operators.
1638 if (isParsingInlineAsm()) {
1639 StringRef AsmTokStr = Tok.getString();
1640 if (AsmTokStr == "offset" || AsmTokStr == "OFFSET")
1641 return ParseIntelOffsetOfOperator();
1642 if (AsmTokStr == "length" || AsmTokStr == "LENGTH")
1643 return ParseIntelOperator(IOK_LENGTH);
1644 if (AsmTokStr == "size" || AsmTokStr == "SIZE")
1645 return ParseIntelOperator(IOK_SIZE);
1646 if (AsmTokStr == "type" || AsmTokStr == "TYPE")
1647 return ParseIntelOperator(IOK_TYPE);
1651 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Minus) ||
1652 getLexer().is(AsmToken::LParen)) {
1653 AsmToken StartTok = Tok;
1654 IntelExprStateMachine SM(/*Imm=*/0, /*StopOnLBrac=*/true,
1655 /*AddImmPrefix=*/false);
1656 if (X86Operand *Err = ParseIntelExpression(SM, End))
1659 int64_t Imm = SM.getImm();
1660 if (isParsingInlineAsm()) {
1661 unsigned Len = Tok.getLoc().getPointer() - Start.getPointer();
1662 if (StartTok.getString().size() == Len)
1663 // Just add a prefix if this wasn't a complex immediate expression.
1664 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix, Start));
1666 // Otherwise, rewrite the complex expression as a single immediate.
1667 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, Start, Len, Imm));
1670 if (getLexer().isNot(AsmToken::LBrac)) {
1671 const MCExpr *ImmExpr = MCConstantExpr::Create(Imm, getContext());
1672 return X86Operand::CreateImm(ImmExpr, Start, End);
1675 // Only positive immediates are valid.
1677 return ErrorOperand(Start, "expected a positive immediate displacement "
1678 "before bracketed expr.");
1680 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1681 return ParseIntelMemOperand(/*SegReg=*/0, Imm, Start);
1686 if (!ParseRegister(RegNo, Start, End)) {
1687 // If this is a segment register followed by a ':', then this is the start
1688 // of a memory reference, otherwise this is a normal register reference.
1689 if (getLexer().isNot(AsmToken::Colon))
1690 return X86Operand::CreateReg(RegNo, Start, End);
1692 getParser().Lex(); // Eat the colon.
1693 return ParseIntelMemOperand(/*SegReg=*/RegNo, /*Disp=*/0, Start);
1697 return ParseIntelMemOperand(/*SegReg=*/0, /*Disp=*/0, Start);
1700 X86Operand *X86AsmParser::ParseATTOperand() {
1701 switch (getLexer().getKind()) {
1703 // Parse a memory operand with no segment register.
1704 return ParseMemOperand(0, Parser.getTok().getLoc());
1705 case AsmToken::Percent: {
1706 // Read the register.
1709 if (ParseRegister(RegNo, Start, End)) return 0;
1710 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
1711 Error(Start, "%eiz and %riz can only be used as index registers",
1712 SMRange(Start, End));
1716 // If this is a segment register followed by a ':', then this is the start
1717 // of a memory reference, otherwise this is a normal register reference.
1718 if (getLexer().isNot(AsmToken::Colon))
1719 return X86Operand::CreateReg(RegNo, Start, End);
1721 getParser().Lex(); // Eat the colon.
1722 return ParseMemOperand(RegNo, Start);
1724 case AsmToken::Dollar: {
1725 // $42 -> immediate.
1726 SMLoc Start = Parser.getTok().getLoc(), End;
1729 if (getParser().parseExpression(Val, End))
1731 return X86Operand::CreateImm(Val, Start, End);
1736 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
1737 /// has already been parsed if present.
1738 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
1740 // We have to disambiguate a parenthesized expression "(4+5)" from the start
1741 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
1742 // only way to do this without lookahead is to eat the '(' and see what is
1744 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
1745 if (getLexer().isNot(AsmToken::LParen)) {
1747 if (getParser().parseExpression(Disp, ExprEnd)) return 0;
1749 // After parsing the base expression we could either have a parenthesized
1750 // memory address or not. If not, return now. If so, eat the (.
1751 if (getLexer().isNot(AsmToken::LParen)) {
1752 // Unless we have a segment register, treat this as an immediate.
1754 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
1755 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1761 // Okay, we have a '('. We don't know if this is an expression or not, but
1762 // so we have to eat the ( to see beyond it.
1763 SMLoc LParenLoc = Parser.getTok().getLoc();
1764 Parser.Lex(); // Eat the '('.
1766 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
1767 // Nothing to do here, fall into the code below with the '(' part of the
1768 // memory operand consumed.
1772 // It must be an parenthesized expression, parse it now.
1773 if (getParser().parseParenExpression(Disp, ExprEnd))
1776 // After parsing the base expression we could either have a parenthesized
1777 // memory address or not. If not, return now. If so, eat the (.
1778 if (getLexer().isNot(AsmToken::LParen)) {
1779 // Unless we have a segment register, treat this as an immediate.
1781 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
1782 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1790 // If we reached here, then we just ate the ( of the memory operand. Process
1791 // the rest of the memory operand.
1792 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
1795 if (getLexer().is(AsmToken::Percent)) {
1796 SMLoc StartLoc, EndLoc;
1797 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
1798 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
1799 Error(StartLoc, "eiz and riz can only be used as index registers",
1800 SMRange(StartLoc, EndLoc));
1805 if (getLexer().is(AsmToken::Comma)) {
1806 Parser.Lex(); // Eat the comma.
1807 IndexLoc = Parser.getTok().getLoc();
1809 // Following the comma we should have either an index register, or a scale
1810 // value. We don't support the later form, but we want to parse it
1813 // Not that even though it would be completely consistent to support syntax
1814 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
1815 if (getLexer().is(AsmToken::Percent)) {
1817 if (ParseRegister(IndexReg, L, L)) return 0;
1819 if (getLexer().isNot(AsmToken::RParen)) {
1820 // Parse the scale amount:
1821 // ::= ',' [scale-expression]
1822 if (getLexer().isNot(AsmToken::Comma)) {
1823 Error(Parser.getTok().getLoc(),
1824 "expected comma in scale expression");
1827 Parser.Lex(); // Eat the comma.
1829 if (getLexer().isNot(AsmToken::RParen)) {
1830 SMLoc Loc = Parser.getTok().getLoc();
1833 if (getParser().parseAbsoluteExpression(ScaleVal)){
1834 Error(Loc, "expected scale expression");
1838 // Validate the scale amount.
1839 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
1840 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
1843 Scale = (unsigned)ScaleVal;
1846 } else if (getLexer().isNot(AsmToken::RParen)) {
1847 // A scale amount without an index is ignored.
1849 SMLoc Loc = Parser.getTok().getLoc();
1852 if (getParser().parseAbsoluteExpression(Value))
1856 Warning(Loc, "scale factor without index register is ignored");
1861 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1862 if (getLexer().isNot(AsmToken::RParen)) {
1863 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1866 SMLoc MemEnd = Parser.getTok().getEndLoc();
1867 Parser.Lex(); // Eat the ')'.
1869 // If we have both a base register and an index register make sure they are
1870 // both 64-bit or 32-bit registers.
1871 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1872 if (BaseReg != 0 && IndexReg != 0) {
1873 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1874 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1875 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1876 IndexReg != X86::RIZ) {
1877 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1880 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1881 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1882 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1883 IndexReg != X86::EIZ){
1884 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1889 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1894 ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
1895 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1897 StringRef PatchedName = Name;
1899 // FIXME: Hack to recognize setneb as setne.
1900 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1901 PatchedName != "setb" && PatchedName != "setnb")
1902 PatchedName = PatchedName.substr(0, Name.size()-1);
1904 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1905 const MCExpr *ExtraImmOp = 0;
1906 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1907 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1908 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1909 bool IsVCMP = PatchedName[0] == 'v';
1910 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1911 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1912 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1916 .Case("unord", 0x03)
1921 /* AVX only from here */
1922 .Case("eq_uq", 0x08)
1925 .Case("false", 0x0B)
1926 .Case("neq_oq", 0x0C)
1930 .Case("eq_os", 0x10)
1931 .Case("lt_oq", 0x11)
1932 .Case("le_oq", 0x12)
1933 .Case("unord_s", 0x13)
1934 .Case("neq_us", 0x14)
1935 .Case("nlt_uq", 0x15)
1936 .Case("nle_uq", 0x16)
1937 .Case("ord_s", 0x17)
1938 .Case("eq_us", 0x18)
1939 .Case("nge_uq", 0x19)
1940 .Case("ngt_uq", 0x1A)
1941 .Case("false_os", 0x1B)
1942 .Case("neq_os", 0x1C)
1943 .Case("ge_oq", 0x1D)
1944 .Case("gt_oq", 0x1E)
1945 .Case("true_us", 0x1F)
1947 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1948 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1949 getParser().getContext());
1950 if (PatchedName.endswith("ss")) {
1951 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1952 } else if (PatchedName.endswith("sd")) {
1953 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1954 } else if (PatchedName.endswith("ps")) {
1955 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1957 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1958 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1963 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1965 if (ExtraImmOp && !isParsingIntelSyntax())
1966 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1968 // Determine whether this is an instruction prefix.
1970 Name == "lock" || Name == "rep" ||
1971 Name == "repe" || Name == "repz" ||
1972 Name == "repne" || Name == "repnz" ||
1973 Name == "rex64" || Name == "data16";
1976 // This does the actual operand parsing. Don't parse any more if we have a
1977 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1978 // just want to parse the "lock" as the first instruction and the "incl" as
1980 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1982 // Parse '*' modifier.
1983 if (getLexer().is(AsmToken::Star)) {
1984 SMLoc Loc = Parser.getTok().getLoc();
1985 Operands.push_back(X86Operand::CreateToken("*", Loc));
1986 Parser.Lex(); // Eat the star.
1989 // Read the first operand.
1990 if (X86Operand *Op = ParseOperand())
1991 Operands.push_back(Op);
1993 Parser.eatToEndOfStatement();
1997 while (getLexer().is(AsmToken::Comma)) {
1998 Parser.Lex(); // Eat the comma.
2000 // Parse and remember the operand.
2001 if (X86Operand *Op = ParseOperand())
2002 Operands.push_back(Op);
2004 Parser.eatToEndOfStatement();
2009 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2010 SMLoc Loc = getLexer().getLoc();
2011 Parser.eatToEndOfStatement();
2012 return Error(Loc, "unexpected token in argument list");
2016 if (getLexer().is(AsmToken::EndOfStatement))
2017 Parser.Lex(); // Consume the EndOfStatement
2018 else if (isPrefix && getLexer().is(AsmToken::Slash))
2019 Parser.Lex(); // Consume the prefix separator Slash
2021 if (ExtraImmOp && isParsingIntelSyntax())
2022 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
2024 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
2025 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
2026 // documented form in various unofficial manuals, so a lot of code uses it.
2027 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
2028 Operands.size() == 3) {
2029 X86Operand &Op = *(X86Operand*)Operands.back();
2030 if (Op.isMem() && Op.Mem.SegReg == 0 &&
2031 isa<MCConstantExpr>(Op.Mem.Disp) &&
2032 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2033 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2034 SMLoc Loc = Op.getEndLoc();
2035 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
2039 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
2040 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
2041 Operands.size() == 3) {
2042 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2043 if (Op.isMem() && Op.Mem.SegReg == 0 &&
2044 isa<MCConstantExpr>(Op.Mem.Disp) &&
2045 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2046 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2047 SMLoc Loc = Op.getEndLoc();
2048 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
2052 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
2053 if (Name.startswith("ins") && Operands.size() == 3 &&
2054 (Name == "insb" || Name == "insw" || Name == "insl")) {
2055 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2056 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2057 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
2058 Operands.pop_back();
2059 Operands.pop_back();
2065 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
2066 if (Name.startswith("outs") && Operands.size() == 3 &&
2067 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
2068 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2069 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2070 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
2071 Operands.pop_back();
2072 Operands.pop_back();
2078 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
2079 if (Name.startswith("movs") && Operands.size() == 3 &&
2080 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
2081 (is64BitMode() && Name == "movsq"))) {
2082 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2083 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2084 if (isSrcOp(Op) && isDstOp(Op2)) {
2085 Operands.pop_back();
2086 Operands.pop_back();
2091 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
2092 if (Name.startswith("lods") && Operands.size() == 3 &&
2093 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
2094 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
2095 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2096 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2097 if (isSrcOp(*Op1) && Op2->isReg()) {
2099 unsigned reg = Op2->getReg();
2100 bool isLods = Name == "lods";
2101 if (reg == X86::AL && (isLods || Name == "lodsb"))
2103 else if (reg == X86::AX && (isLods || Name == "lodsw"))
2105 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
2107 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
2112 Operands.pop_back();
2113 Operands.pop_back();
2117 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2121 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
2122 if (Name.startswith("stos") && Operands.size() == 3 &&
2123 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
2124 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
2125 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2126 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2127 if (isDstOp(*Op2) && Op1->isReg()) {
2129 unsigned reg = Op1->getReg();
2130 bool isStos = Name == "stos";
2131 if (reg == X86::AL && (isStos || Name == "stosb"))
2133 else if (reg == X86::AX && (isStos || Name == "stosw"))
2135 else if (reg == X86::EAX && (isStos || Name == "stosl"))
2137 else if (reg == X86::RAX && (isStos || Name == "stosq"))
2142 Operands.pop_back();
2143 Operands.pop_back();
2147 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2152 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
2154 if ((Name.startswith("shr") || Name.startswith("sar") ||
2155 Name.startswith("shl") || Name.startswith("sal") ||
2156 Name.startswith("rcl") || Name.startswith("rcr") ||
2157 Name.startswith("rol") || Name.startswith("ror")) &&
2158 Operands.size() == 3) {
2159 if (isParsingIntelSyntax()) {
2161 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
2162 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2163 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2165 Operands.pop_back();
2168 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2169 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2170 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2172 Operands.erase(Operands.begin() + 1);
2177 // Transforms "int $3" into "int3" as a size optimization. We can't write an
2178 // instalias with an immediate operand yet.
2179 if (Name == "int" && Operands.size() == 2) {
2180 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2181 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2182 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
2184 Operands.erase(Operands.begin() + 1);
2185 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
2192 static bool convertToSExti8(MCInst &Inst, unsigned Opcode, unsigned Reg,
2195 TmpInst.setOpcode(Opcode);
2197 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2198 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2199 TmpInst.addOperand(Inst.getOperand(0));
2204 static bool convert16i16to16ri8(MCInst &Inst, unsigned Opcode,
2205 bool isCmp = false) {
2206 if (!Inst.getOperand(0).isImm() ||
2207 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
2210 return convertToSExti8(Inst, Opcode, X86::AX, isCmp);
2213 static bool convert32i32to32ri8(MCInst &Inst, unsigned Opcode,
2214 bool isCmp = false) {
2215 if (!Inst.getOperand(0).isImm() ||
2216 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
2219 return convertToSExti8(Inst, Opcode, X86::EAX, isCmp);
2222 static bool convert64i32to64ri8(MCInst &Inst, unsigned Opcode,
2223 bool isCmp = false) {
2224 if (!Inst.getOperand(0).isImm() ||
2225 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
2228 return convertToSExti8(Inst, Opcode, X86::RAX, isCmp);
2232 processInstruction(MCInst &Inst,
2233 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
2234 switch (Inst.getOpcode()) {
2235 default: return false;
2236 case X86::AND16i16: return convert16i16to16ri8(Inst, X86::AND16ri8);
2237 case X86::AND32i32: return convert32i32to32ri8(Inst, X86::AND32ri8);
2238 case X86::AND64i32: return convert64i32to64ri8(Inst, X86::AND64ri8);
2239 case X86::XOR16i16: return convert16i16to16ri8(Inst, X86::XOR16ri8);
2240 case X86::XOR32i32: return convert32i32to32ri8(Inst, X86::XOR32ri8);
2241 case X86::XOR64i32: return convert64i32to64ri8(Inst, X86::XOR64ri8);
2242 case X86::OR16i16: return convert16i16to16ri8(Inst, X86::OR16ri8);
2243 case X86::OR32i32: return convert32i32to32ri8(Inst, X86::OR32ri8);
2244 case X86::OR64i32: return convert64i32to64ri8(Inst, X86::OR64ri8);
2245 case X86::CMP16i16: return convert16i16to16ri8(Inst, X86::CMP16ri8, true);
2246 case X86::CMP32i32: return convert32i32to32ri8(Inst, X86::CMP32ri8, true);
2247 case X86::CMP64i32: return convert64i32to64ri8(Inst, X86::CMP64ri8, true);
2248 case X86::ADD16i16: return convert16i16to16ri8(Inst, X86::ADD16ri8);
2249 case X86::ADD32i32: return convert32i32to32ri8(Inst, X86::ADD32ri8);
2250 case X86::ADD64i32: return convert64i32to64ri8(Inst, X86::ADD64ri8);
2251 case X86::SUB16i16: return convert16i16to16ri8(Inst, X86::SUB16ri8);
2252 case X86::SUB32i32: return convert32i32to32ri8(Inst, X86::SUB32ri8);
2253 case X86::SUB64i32: return convert64i32to64ri8(Inst, X86::SUB64ri8);
2254 case X86::ADC16i16: return convert16i16to16ri8(Inst, X86::ADC16ri8);
2255 case X86::ADC32i32: return convert32i32to32ri8(Inst, X86::ADC32ri8);
2256 case X86::ADC64i32: return convert64i32to64ri8(Inst, X86::ADC64ri8);
2257 case X86::SBB16i16: return convert16i16to16ri8(Inst, X86::SBB16ri8);
2258 case X86::SBB32i32: return convert32i32to32ri8(Inst, X86::SBB32ri8);
2259 case X86::SBB64i32: return convert64i32to64ri8(Inst, X86::SBB64ri8);
2263 static const char *getSubtargetFeatureName(unsigned Val);
2265 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2266 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2267 MCStreamer &Out, unsigned &ErrorInfo,
2268 bool MatchingInlineAsm) {
2269 assert(!Operands.empty() && "Unexpect empty operand list!");
2270 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
2271 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
2272 ArrayRef<SMRange> EmptyRanges = None;
2274 // First, handle aliases that expand to multiple instructions.
2275 // FIXME: This should be replaced with a real .td file alias mechanism.
2276 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
2278 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
2279 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
2280 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
2281 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
2283 Inst.setOpcode(X86::WAIT);
2285 if (!MatchingInlineAsm)
2286 Out.EmitInstruction(Inst);
2289 StringSwitch<const char*>(Op->getToken())
2290 .Case("finit", "fninit")
2291 .Case("fsave", "fnsave")
2292 .Case("fstcw", "fnstcw")
2293 .Case("fstcww", "fnstcw")
2294 .Case("fstenv", "fnstenv")
2295 .Case("fstsw", "fnstsw")
2296 .Case("fstsww", "fnstsw")
2297 .Case("fclex", "fnclex")
2299 assert(Repl && "Unknown wait-prefixed instruction");
2301 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
2304 bool WasOriginallyInvalidOperand = false;
2307 // First, try a direct match.
2308 switch (MatchInstructionImpl(Operands, Inst,
2309 ErrorInfo, MatchingInlineAsm,
2310 isParsingIntelSyntax())) {
2313 // Some instructions need post-processing to, for example, tweak which
2314 // encoding is selected. Loop on it while changes happen so the
2315 // individual transformations can chain off each other.
2316 if (!MatchingInlineAsm)
2317 while (processInstruction(Inst, Operands))
2321 if (!MatchingInlineAsm)
2322 Out.EmitInstruction(Inst);
2323 Opcode = Inst.getOpcode();
2325 case Match_MissingFeature: {
2326 assert(ErrorInfo && "Unknown missing feature!");
2327 // Special case the error message for the very common case where only
2328 // a single subtarget feature is missing.
2329 std::string Msg = "instruction requires:";
2331 for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
2332 if (ErrorInfo & Mask) {
2334 Msg += getSubtargetFeatureName(ErrorInfo & Mask);
2338 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2340 case Match_InvalidOperand:
2341 WasOriginallyInvalidOperand = true;
2343 case Match_MnemonicFail:
2347 // FIXME: Ideally, we would only attempt suffix matches for things which are
2348 // valid prefixes, and we could just infer the right unambiguous
2349 // type. However, that requires substantially more matcher support than the
2352 // Change the operand to point to a temporary token.
2353 StringRef Base = Op->getToken();
2354 SmallString<16> Tmp;
2357 Op->setTokenValue(Tmp.str());
2359 // If this instruction starts with an 'f', then it is a floating point stack
2360 // instruction. These come in up to three forms for 32-bit, 64-bit, and
2361 // 80-bit floating point, which use the suffixes s,l,t respectively.
2363 // Otherwise, we assume that this may be an integer instruction, which comes
2364 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
2365 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
2367 // Check for the various suffix matches.
2368 Tmp[Base.size()] = Suffixes[0];
2369 unsigned ErrorInfoIgnore;
2370 unsigned ErrorInfoMissingFeature = 0; // Init suppresses compiler warnings.
2371 unsigned Match1, Match2, Match3, Match4;
2373 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2374 MatchingInlineAsm, isParsingIntelSyntax());
2375 // If this returned as a missing feature failure, remember that.
2376 if (Match1 == Match_MissingFeature)
2377 ErrorInfoMissingFeature = ErrorInfoIgnore;
2378 Tmp[Base.size()] = Suffixes[1];
2379 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2380 MatchingInlineAsm, isParsingIntelSyntax());
2381 // If this returned as a missing feature failure, remember that.
2382 if (Match2 == Match_MissingFeature)
2383 ErrorInfoMissingFeature = ErrorInfoIgnore;
2384 Tmp[Base.size()] = Suffixes[2];
2385 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2386 MatchingInlineAsm, isParsingIntelSyntax());
2387 // If this returned as a missing feature failure, remember that.
2388 if (Match3 == Match_MissingFeature)
2389 ErrorInfoMissingFeature = ErrorInfoIgnore;
2390 Tmp[Base.size()] = Suffixes[3];
2391 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2392 MatchingInlineAsm, isParsingIntelSyntax());
2393 // If this returned as a missing feature failure, remember that.
2394 if (Match4 == Match_MissingFeature)
2395 ErrorInfoMissingFeature = ErrorInfoIgnore;
2397 // Restore the old token.
2398 Op->setTokenValue(Base);
2400 // If exactly one matched, then we treat that as a successful match (and the
2401 // instruction will already have been filled in correctly, since the failing
2402 // matches won't have modified it).
2403 unsigned NumSuccessfulMatches =
2404 (Match1 == Match_Success) + (Match2 == Match_Success) +
2405 (Match3 == Match_Success) + (Match4 == Match_Success);
2406 if (NumSuccessfulMatches == 1) {
2408 if (!MatchingInlineAsm)
2409 Out.EmitInstruction(Inst);
2410 Opcode = Inst.getOpcode();
2414 // Otherwise, the match failed, try to produce a decent error message.
2416 // If we had multiple suffix matches, then identify this as an ambiguous
2418 if (NumSuccessfulMatches > 1) {
2420 unsigned NumMatches = 0;
2421 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
2422 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
2423 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
2424 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
2426 SmallString<126> Msg;
2427 raw_svector_ostream OS(Msg);
2428 OS << "ambiguous instructions require an explicit suffix (could be ";
2429 for (unsigned i = 0; i != NumMatches; ++i) {
2432 if (i + 1 == NumMatches)
2434 OS << "'" << Base << MatchChars[i] << "'";
2437 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
2441 // Okay, we know that none of the variants matched successfully.
2443 // If all of the instructions reported an invalid mnemonic, then the original
2444 // mnemonic was invalid.
2445 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
2446 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
2447 if (!WasOriginallyInvalidOperand) {
2448 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
2450 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
2451 Ranges, MatchingInlineAsm);
2454 // Recover location info for the operand if we know which was the problem.
2455 if (ErrorInfo != ~0U) {
2456 if (ErrorInfo >= Operands.size())
2457 return Error(IDLoc, "too few operands for instruction",
2458 EmptyRanges, MatchingInlineAsm);
2460 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
2461 if (Operand->getStartLoc().isValid()) {
2462 SMRange OperandRange = Operand->getLocRange();
2463 return Error(Operand->getStartLoc(), "invalid operand for instruction",
2464 OperandRange, MatchingInlineAsm);
2468 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2472 // If one instruction matched with a missing feature, report this as a
2474 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
2475 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
2476 std::string Msg = "instruction requires:";
2478 for (unsigned i = 0; i < (sizeof(ErrorInfoMissingFeature)*8-1); ++i) {
2479 if (ErrorInfoMissingFeature & Mask) {
2481 Msg += getSubtargetFeatureName(ErrorInfoMissingFeature & Mask);
2485 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2488 // If one instruction matched with an invalid operand, report this as an
2490 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
2491 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
2492 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2497 // If all of these were an outright failure, report it in a useless way.
2498 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
2499 EmptyRanges, MatchingInlineAsm);
2504 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
2505 StringRef IDVal = DirectiveID.getIdentifier();
2506 if (IDVal == ".word")
2507 return ParseDirectiveWord(2, DirectiveID.getLoc());
2508 else if (IDVal.startswith(".code"))
2509 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
2510 else if (IDVal.startswith(".att_syntax")) {
2511 getParser().setAssemblerDialect(0);
2513 } else if (IDVal.startswith(".intel_syntax")) {
2514 getParser().setAssemblerDialect(1);
2515 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2516 if(Parser.getTok().getString() == "noprefix") {
2517 // FIXME : Handle noprefix
2527 /// ParseDirectiveWord
2528 /// ::= .word [ expression (, expression)* ]
2529 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
2530 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2532 const MCExpr *Value;
2533 if (getParser().parseExpression(Value))
2536 getParser().getStreamer().EmitValue(Value, Size);
2538 if (getLexer().is(AsmToken::EndOfStatement))
2541 // FIXME: Improve diagnostic.
2542 if (getLexer().isNot(AsmToken::Comma))
2543 return Error(L, "unexpected token in directive");
2552 /// ParseDirectiveCode
2553 /// ::= .code32 | .code64
2554 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
2555 if (IDVal == ".code32") {
2557 if (is64BitMode()) {
2559 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
2561 } else if (IDVal == ".code64") {
2563 if (!is64BitMode()) {
2565 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
2568 return Error(L, "unexpected directive " + IDVal);
2574 // Force static initialization.
2575 extern "C" void LLVMInitializeX86AsmParser() {
2576 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
2577 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
2580 #define GET_REGISTER_MATCHER
2581 #define GET_MATCHER_IMPLEMENTATION
2582 #define GET_SUBTARGET_FEATURE_NAME
2583 #include "X86GenAsmMatcher.inc"