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/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/StringSwitch.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCInst.h"
19 #include "llvm/MC/MCParser/MCAsmLexer.h"
20 #include "llvm/MC/MCParser/MCAsmParser.h"
21 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/MC/MCSubtargetInfo.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCTargetAsmParser.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "llvm/Support/TargetRegistry.h"
29 #include "llvm/Support/raw_ostream.h"
36 static const char OpPrecedence[] = {
47 class X86AsmParser : public MCTargetAsmParser {
50 ParseInstructionInfo *InstInfo;
52 enum InfixCalculatorTok {
63 class InfixCalculator {
64 typedef std::pair< InfixCalculatorTok, int64_t > ICToken;
65 SmallVector<InfixCalculatorTok, 4> InfixOperatorStack;
66 SmallVector<ICToken, 4> PostfixStack;
69 int64_t popOperand() {
70 assert (!PostfixStack.empty() && "Poped an empty stack!");
71 ICToken Op = PostfixStack.pop_back_val();
72 assert ((Op.first == IC_IMM || Op.first == IC_REGISTER)
73 && "Expected and immediate or register!");
76 void pushOperand(InfixCalculatorTok Op, int64_t Val = 0) {
77 assert ((Op == IC_IMM || Op == IC_REGISTER) &&
78 "Unexpected operand!");
79 PostfixStack.push_back(std::make_pair(Op, Val));
82 void popOperator() { InfixOperatorStack.pop_back_val(); }
83 void pushOperator(InfixCalculatorTok Op) {
84 // Push the new operator if the stack is empty.
85 if (InfixOperatorStack.empty()) {
86 InfixOperatorStack.push_back(Op);
90 // Push the new operator if it has a higher precedence than the operator
91 // on the top of the stack or the operator on the top of the stack is a
93 unsigned Idx = InfixOperatorStack.size() - 1;
94 InfixCalculatorTok StackOp = InfixOperatorStack[Idx];
95 if (OpPrecedence[Op] > OpPrecedence[StackOp] || StackOp == IC_LPAREN) {
96 InfixOperatorStack.push_back(Op);
100 // The operator on the top of the stack has higher precedence than the
102 unsigned ParenCount = 0;
104 // Nothing to process.
105 if (InfixOperatorStack.empty())
108 Idx = InfixOperatorStack.size() - 1;
109 StackOp = InfixOperatorStack[Idx];
110 if (!(OpPrecedence[StackOp] >= OpPrecedence[Op] || ParenCount))
113 // If we have an even parentheses count and we see a left parentheses,
114 // then stop processing.
115 if (!ParenCount && StackOp == IC_LPAREN)
118 if (StackOp == IC_RPAREN) {
120 InfixOperatorStack.pop_back_val();
121 } else if (StackOp == IC_LPAREN) {
123 InfixOperatorStack.pop_back_val();
125 InfixOperatorStack.pop_back_val();
126 PostfixStack.push_back(std::make_pair(StackOp, 0));
129 // Push the new operator.
130 InfixOperatorStack.push_back(Op);
133 // Push any remaining operators onto the postfix stack.
134 while (!InfixOperatorStack.empty()) {
135 InfixCalculatorTok StackOp = InfixOperatorStack.pop_back_val();
136 if (StackOp != IC_LPAREN && StackOp != IC_RPAREN)
137 PostfixStack.push_back(std::make_pair(StackOp, 0));
140 if (PostfixStack.empty())
143 SmallVector<ICToken, 16> OperandStack;
144 for (unsigned i = 0, e = PostfixStack.size(); i != e; ++i) {
145 ICToken Op = PostfixStack[i];
146 if (Op.first == IC_IMM || Op.first == IC_REGISTER) {
147 OperandStack.push_back(Op);
149 assert (OperandStack.size() > 1 && "Too few operands.");
151 ICToken Op2 = OperandStack.pop_back_val();
152 ICToken Op1 = OperandStack.pop_back_val();
155 report_fatal_error("Unexpected operator!");
158 Val = Op1.second + Op2.second;
159 OperandStack.push_back(std::make_pair(IC_IMM, Val));
162 Val = Op1.second - Op2.second;
163 OperandStack.push_back(std::make_pair(IC_IMM, Val));
166 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
167 "Multiply operation with an immediate and a register!");
168 Val = Op1.second * Op2.second;
169 OperandStack.push_back(std::make_pair(IC_IMM, Val));
172 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
173 "Divide operation with an immediate and a register!");
174 assert (Op2.second != 0 && "Division by zero!");
175 Val = Op1.second / Op2.second;
176 OperandStack.push_back(std::make_pair(IC_IMM, Val));
181 assert (OperandStack.size() == 1 && "Expected a single result.");
182 return OperandStack.pop_back_val().second;
186 enum IntelExprState {
201 class IntelExprStateMachine {
202 IntelExprState State, PrevState;
203 unsigned BaseReg, IndexReg, TmpReg, Scale;
207 bool StopOnLBrac, AddImmPrefix;
210 IntelExprStateMachine(int64_t imm, bool stoponlbrac, bool addimmprefix) :
211 State(IES_PLUS), PrevState(IES_ERROR), BaseReg(0), IndexReg(0), TmpReg(0),
212 Scale(1), Imm(imm), Sym(0), StopOnLBrac(stoponlbrac),
213 AddImmPrefix(addimmprefix) {}
215 unsigned getBaseReg() { return BaseReg; }
216 unsigned getIndexReg() { return IndexReg; }
217 unsigned getScale() { return Scale; }
218 const MCExpr *getSym() { return Sym; }
219 StringRef getSymName() { return SymName; }
220 int64_t getImm() { return Imm + IC.execute(); }
221 bool isValidEndState() { return State == IES_RBRAC; }
222 bool getStopOnLBrac() { return StopOnLBrac; }
223 bool getAddImmPrefix() { return AddImmPrefix; }
224 bool hadError() { return State == IES_ERROR; }
227 IntelExprState CurrState = State;
236 IC.pushOperator(IC_PLUS);
237 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
238 // If we already have a BaseReg, then assume this is the IndexReg with
243 assert (!IndexReg && "BaseReg/IndexReg already set!");
250 PrevState = CurrState;
253 IntelExprState CurrState = State;
268 // Only push the minus operator if it is not a unary operator.
269 if (!(CurrState == IES_PLUS || CurrState == IES_MINUS ||
270 CurrState == IES_MULTIPLY || CurrState == IES_DIVIDE ||
271 CurrState == IES_LPAREN || CurrState == IES_LBRAC))
272 IC.pushOperator(IC_MINUS);
273 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
274 // If we already have a BaseReg, then assume this is the IndexReg with
279 assert (!IndexReg && "BaseReg/IndexReg already set!");
286 PrevState = CurrState;
288 void onRegister(unsigned Reg) {
289 IntelExprState CurrState = State;
296 State = IES_REGISTER;
298 IC.pushOperand(IC_REGISTER);
301 // Index Register - Scale * Register
302 if (PrevState == IES_INTEGER) {
303 assert (!IndexReg && "IndexReg already set!");
304 State = IES_REGISTER;
306 // Get the scale and replace the 'Scale * Register' with '0'.
307 Scale = IC.popOperand();
308 IC.pushOperand(IC_IMM);
315 PrevState = CurrState;
317 void onDispExpr(const MCExpr *SymRef, StringRef SymRefName) {
327 SymName = SymRefName;
328 IC.pushOperand(IC_IMM);
332 void onInteger(int64_t TmpInt) {
333 IntelExprState CurrState = State;
344 if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) {
345 // Index Register - Register * Scale
346 assert (!IndexReg && "IndexReg already set!");
349 // Get the scale and replace the 'Register * Scale' with '0'.
351 } else if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
352 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
353 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
354 CurrState == IES_MINUS) {
355 // Unary minus. No need to pop the minus operand because it was never
357 IC.pushOperand(IC_IMM, -TmpInt); // Push -Imm.
359 IC.pushOperand(IC_IMM, TmpInt);
363 PrevState = CurrState;
374 State = IES_MULTIPLY;
375 IC.pushOperator(IC_MULTIPLY);
388 IC.pushOperator(IC_DIVIDE);
400 IC.pushOperator(IC_PLUS);
405 IntelExprState CurrState = State;
414 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
415 // If we already have a BaseReg, then assume this is the IndexReg with
420 assert (!IndexReg && "BaseReg/IndexReg already set!");
427 PrevState = CurrState;
430 IntelExprState CurrState = State;
440 // FIXME: We don't handle this type of unary minus, yet.
441 if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
442 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
443 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
444 CurrState == IES_MINUS) {
449 IC.pushOperator(IC_LPAREN);
452 PrevState = CurrState;
464 IC.pushOperator(IC_RPAREN);
470 MCAsmParser &getParser() const { return Parser; }
472 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
474 bool Error(SMLoc L, const Twine &Msg,
475 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>(),
476 bool MatchingInlineAsm = false) {
477 if (MatchingInlineAsm) return true;
478 return Parser.Error(L, Msg, Ranges);
481 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
486 X86Operand *ParseOperand();
487 X86Operand *ParseATTOperand();
488 X86Operand *ParseIntelOperand();
489 X86Operand *ParseIntelOffsetOfOperator();
490 X86Operand *ParseIntelOperator(unsigned OpKind);
491 X86Operand *ParseIntelMemOperand(unsigned SegReg, int64_t ImmDisp,
493 X86Operand *ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End);
494 X86Operand *ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
495 int64_t ImmDisp, unsigned Size);
496 X86Operand *ParseIntelVarWithQualifier(const MCExpr *&Disp,
497 StringRef &Identifier);
498 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
500 X86Operand *CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
501 unsigned BaseReg, unsigned IndexReg,
502 unsigned Scale, SMLoc Start, SMLoc End,
503 unsigned Size, StringRef SymName);
505 bool ParseIntelDotOperator(const MCExpr *Disp, const MCExpr **NewDisp,
506 SmallString<64> &Err);
508 bool ParseDirectiveWord(unsigned Size, SMLoc L);
509 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
511 bool processInstruction(MCInst &Inst,
512 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
514 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
515 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
516 MCStreamer &Out, unsigned &ErrorInfo,
517 bool MatchingInlineAsm);
519 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
520 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
521 bool isSrcOp(X86Operand &Op);
523 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
524 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
525 bool isDstOp(X86Operand &Op);
527 bool is64BitMode() const {
528 // FIXME: Can tablegen auto-generate this?
529 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
532 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
533 setAvailableFeatures(FB);
536 bool isParsingIntelSyntax() {
537 return getParser().getAssemblerDialect();
540 /// @name Auto-generated Matcher Functions
543 #define GET_ASSEMBLER_HEADER
544 #include "X86GenAsmMatcher.inc"
549 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
550 : MCTargetAsmParser(), STI(sti), Parser(parser), InstInfo(0) {
552 // Initialize the set of available features.
553 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
555 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
557 virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
559 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
561 virtual bool ParseDirective(AsmToken DirectiveID);
563 } // end anonymous namespace
565 /// @name Auto-generated Match Functions
568 static unsigned MatchRegisterName(StringRef Name);
572 static bool isImmSExti16i8Value(uint64_t Value) {
573 return (( Value <= 0x000000000000007FULL)||
574 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
575 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
578 static bool isImmSExti32i8Value(uint64_t Value) {
579 return (( Value <= 0x000000000000007FULL)||
580 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
581 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
584 static bool isImmZExtu32u8Value(uint64_t Value) {
585 return (Value <= 0x00000000000000FFULL);
588 static bool isImmSExti64i8Value(uint64_t Value) {
589 return (( Value <= 0x000000000000007FULL)||
590 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
593 static bool isImmSExti64i32Value(uint64_t Value) {
594 return (( Value <= 0x000000007FFFFFFFULL)||
595 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
599 /// X86Operand - Instances of this class represent a parsed X86 machine
601 struct X86Operand : public MCParsedAsmOperand {
609 SMLoc StartLoc, EndLoc;
643 X86Operand(KindTy K, SMLoc Start, SMLoc End)
644 : Kind(K), StartLoc(Start), EndLoc(End) {}
646 StringRef getSymName() { return SymName; }
648 /// getStartLoc - Get the location of the first token of this operand.
649 SMLoc getStartLoc() const { return StartLoc; }
650 /// getEndLoc - Get the location of the last token of this operand.
651 SMLoc getEndLoc() const { return EndLoc; }
652 /// getLocRange - Get the range between the first and last token of this
654 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
655 /// getOffsetOfLoc - Get the location of the offset operator.
656 SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
658 virtual void print(raw_ostream &OS) const {}
660 StringRef getToken() const {
661 assert(Kind == Token && "Invalid access!");
662 return StringRef(Tok.Data, Tok.Length);
664 void setTokenValue(StringRef Value) {
665 assert(Kind == Token && "Invalid access!");
666 Tok.Data = Value.data();
667 Tok.Length = Value.size();
670 unsigned getReg() const {
671 assert(Kind == Register && "Invalid access!");
675 const MCExpr *getImm() const {
676 assert(Kind == Immediate && "Invalid access!");
680 const MCExpr *getMemDisp() const {
681 assert(Kind == Memory && "Invalid access!");
684 unsigned getMemSegReg() const {
685 assert(Kind == Memory && "Invalid access!");
688 unsigned getMemBaseReg() const {
689 assert(Kind == Memory && "Invalid access!");
692 unsigned getMemIndexReg() const {
693 assert(Kind == Memory && "Invalid access!");
696 unsigned getMemScale() const {
697 assert(Kind == Memory && "Invalid access!");
701 bool isToken() const {return Kind == Token; }
703 bool isImm() const { return Kind == Immediate; }
705 bool isImmSExti16i8() const {
709 // If this isn't a constant expr, just assume it fits and let relaxation
711 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
715 // Otherwise, check the value is in a range that makes sense for this
717 return isImmSExti16i8Value(CE->getValue());
719 bool isImmSExti32i8() const {
723 // If this isn't a constant expr, just assume it fits and let relaxation
725 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
729 // Otherwise, check the value is in a range that makes sense for this
731 return isImmSExti32i8Value(CE->getValue());
733 bool isImmZExtu32u8() const {
737 // If this isn't a constant expr, just assume it fits and let relaxation
739 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
743 // Otherwise, check the value is in a range that makes sense for this
745 return isImmZExtu32u8Value(CE->getValue());
747 bool isImmSExti64i8() const {
751 // If this isn't a constant expr, just assume it fits and let relaxation
753 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
757 // Otherwise, check the value is in a range that makes sense for this
759 return isImmSExti64i8Value(CE->getValue());
761 bool isImmSExti64i32() const {
765 // If this isn't a constant expr, just assume it fits and let relaxation
767 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
771 // Otherwise, check the value is in a range that makes sense for this
773 return isImmSExti64i32Value(CE->getValue());
776 bool isOffsetOf() const {
777 return OffsetOfLoc.getPointer();
780 bool needAddressOf() const {
784 bool isMem() const { return Kind == Memory; }
785 bool isMem8() const {
786 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
788 bool isMem16() const {
789 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
791 bool isMem32() const {
792 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
794 bool isMem64() const {
795 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
797 bool isMem80() const {
798 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
800 bool isMem128() const {
801 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
803 bool isMem256() const {
804 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
807 bool isMemVX32() const {
808 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
809 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
811 bool isMemVY32() const {
812 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
813 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
815 bool isMemVX64() const {
816 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
817 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
819 bool isMemVY64() const {
820 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
821 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
824 bool isAbsMem() const {
825 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
826 !getMemIndexReg() && getMemScale() == 1;
829 bool isReg() const { return Kind == Register; }
831 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
832 // Add as immediates when possible.
833 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
834 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
836 Inst.addOperand(MCOperand::CreateExpr(Expr));
839 void addRegOperands(MCInst &Inst, unsigned N) const {
840 assert(N == 1 && "Invalid number of operands!");
841 Inst.addOperand(MCOperand::CreateReg(getReg()));
844 void addImmOperands(MCInst &Inst, unsigned N) const {
845 assert(N == 1 && "Invalid number of operands!");
846 addExpr(Inst, getImm());
849 void addMem8Operands(MCInst &Inst, unsigned N) const {
850 addMemOperands(Inst, N);
852 void addMem16Operands(MCInst &Inst, unsigned N) const {
853 addMemOperands(Inst, N);
855 void addMem32Operands(MCInst &Inst, unsigned N) const {
856 addMemOperands(Inst, N);
858 void addMem64Operands(MCInst &Inst, unsigned N) const {
859 addMemOperands(Inst, N);
861 void addMem80Operands(MCInst &Inst, unsigned N) const {
862 addMemOperands(Inst, N);
864 void addMem128Operands(MCInst &Inst, unsigned N) const {
865 addMemOperands(Inst, N);
867 void addMem256Operands(MCInst &Inst, unsigned N) const {
868 addMemOperands(Inst, N);
870 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
871 addMemOperands(Inst, N);
873 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
874 addMemOperands(Inst, N);
876 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
877 addMemOperands(Inst, N);
879 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
880 addMemOperands(Inst, N);
883 void addMemOperands(MCInst &Inst, unsigned N) const {
884 assert((N == 5) && "Invalid number of operands!");
885 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
886 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
887 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
888 addExpr(Inst, getMemDisp());
889 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
892 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
893 assert((N == 1) && "Invalid number of operands!");
894 // Add as immediates when possible.
895 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
896 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
898 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
901 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
902 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size());
903 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
904 Res->Tok.Data = Str.data();
905 Res->Tok.Length = Str.size();
909 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
910 bool AddressOf = false,
911 SMLoc OffsetOfLoc = SMLoc(),
912 StringRef SymName = StringRef()) {
913 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
914 Res->Reg.RegNo = RegNo;
915 Res->AddressOf = AddressOf;
916 Res->OffsetOfLoc = OffsetOfLoc;
917 Res->SymName = SymName;
921 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
922 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
927 /// Create an absolute memory operand.
928 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc,
930 StringRef SymName = StringRef()) {
931 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
933 Res->Mem.Disp = Disp;
934 Res->Mem.BaseReg = 0;
935 Res->Mem.IndexReg = 0;
937 Res->Mem.Size = Size;
938 Res->SymName = SymName;
939 Res->AddressOf = false;
943 /// Create a generalized memory operand.
944 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
945 unsigned BaseReg, unsigned IndexReg,
946 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
948 StringRef SymName = StringRef()) {
949 // We should never just have a displacement, that should be parsed as an
950 // absolute memory operand.
951 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
953 // The scale should always be one of {1,2,4,8}.
954 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
956 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
957 Res->Mem.SegReg = SegReg;
958 Res->Mem.Disp = Disp;
959 Res->Mem.BaseReg = BaseReg;
960 Res->Mem.IndexReg = IndexReg;
961 Res->Mem.Scale = Scale;
962 Res->Mem.Size = Size;
963 Res->SymName = SymName;
964 Res->AddressOf = false;
969 } // end anonymous namespace.
971 bool X86AsmParser::isSrcOp(X86Operand &Op) {
972 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
974 return (Op.isMem() &&
975 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
976 isa<MCConstantExpr>(Op.Mem.Disp) &&
977 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
978 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
981 bool X86AsmParser::isDstOp(X86Operand &Op) {
982 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
985 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
986 isa<MCConstantExpr>(Op.Mem.Disp) &&
987 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
988 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
991 bool X86AsmParser::ParseRegister(unsigned &RegNo,
992 SMLoc &StartLoc, SMLoc &EndLoc) {
994 const AsmToken &PercentTok = Parser.getTok();
995 StartLoc = PercentTok.getLoc();
997 // If we encounter a %, ignore it. This code handles registers with and
998 // without the prefix, unprefixed registers can occur in cfi directives.
999 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
1000 Parser.Lex(); // Eat percent token.
1002 const AsmToken &Tok = Parser.getTok();
1003 EndLoc = Tok.getEndLoc();
1005 if (Tok.isNot(AsmToken::Identifier)) {
1006 if (isParsingIntelSyntax()) return true;
1007 return Error(StartLoc, "invalid register name",
1008 SMRange(StartLoc, EndLoc));
1011 RegNo = MatchRegisterName(Tok.getString());
1013 // If the match failed, try the register name as lowercase.
1015 RegNo = MatchRegisterName(Tok.getString().lower());
1017 if (!is64BitMode()) {
1018 // FIXME: This should be done using Requires<In32BitMode> and
1019 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
1021 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
1023 if (RegNo == X86::RIZ ||
1024 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
1025 X86II::isX86_64NonExtLowByteReg(RegNo) ||
1026 X86II::isX86_64ExtendedReg(RegNo))
1027 return Error(StartLoc, "register %"
1028 + Tok.getString() + " is only available in 64-bit mode",
1029 SMRange(StartLoc, EndLoc));
1032 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
1033 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
1035 Parser.Lex(); // Eat 'st'
1037 // Check to see if we have '(4)' after %st.
1038 if (getLexer().isNot(AsmToken::LParen))
1043 const AsmToken &IntTok = Parser.getTok();
1044 if (IntTok.isNot(AsmToken::Integer))
1045 return Error(IntTok.getLoc(), "expected stack index");
1046 switch (IntTok.getIntVal()) {
1047 case 0: RegNo = X86::ST0; break;
1048 case 1: RegNo = X86::ST1; break;
1049 case 2: RegNo = X86::ST2; break;
1050 case 3: RegNo = X86::ST3; break;
1051 case 4: RegNo = X86::ST4; break;
1052 case 5: RegNo = X86::ST5; break;
1053 case 6: RegNo = X86::ST6; break;
1054 case 7: RegNo = X86::ST7; break;
1055 default: return Error(IntTok.getLoc(), "invalid stack index");
1058 if (getParser().Lex().isNot(AsmToken::RParen))
1059 return Error(Parser.getTok().getLoc(), "expected ')'");
1061 EndLoc = Parser.getTok().getEndLoc();
1062 Parser.Lex(); // Eat ')'
1066 EndLoc = Parser.getTok().getEndLoc();
1068 // If this is "db[0-7]", match it as an alias
1070 if (RegNo == 0 && Tok.getString().size() == 3 &&
1071 Tok.getString().startswith("db")) {
1072 switch (Tok.getString()[2]) {
1073 case '0': RegNo = X86::DR0; break;
1074 case '1': RegNo = X86::DR1; break;
1075 case '2': RegNo = X86::DR2; break;
1076 case '3': RegNo = X86::DR3; break;
1077 case '4': RegNo = X86::DR4; break;
1078 case '5': RegNo = X86::DR5; break;
1079 case '6': RegNo = X86::DR6; break;
1080 case '7': RegNo = X86::DR7; break;
1084 EndLoc = Parser.getTok().getEndLoc();
1085 Parser.Lex(); // Eat it.
1091 if (isParsingIntelSyntax()) return true;
1092 return Error(StartLoc, "invalid register name",
1093 SMRange(StartLoc, EndLoc));
1096 Parser.Lex(); // Eat identifier token.
1100 X86Operand *X86AsmParser::ParseOperand() {
1101 if (isParsingIntelSyntax())
1102 return ParseIntelOperand();
1103 return ParseATTOperand();
1106 /// getIntelMemOperandSize - Return intel memory operand size.
1107 static unsigned getIntelMemOperandSize(StringRef OpStr) {
1108 unsigned Size = StringSwitch<unsigned>(OpStr)
1109 .Cases("BYTE", "byte", 8)
1110 .Cases("WORD", "word", 16)
1111 .Cases("DWORD", "dword", 32)
1112 .Cases("QWORD", "qword", 64)
1113 .Cases("XWORD", "xword", 80)
1114 .Cases("XMMWORD", "xmmword", 128)
1115 .Cases("YMMWORD", "ymmword", 256)
1121 X86AsmParser::CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
1122 unsigned BaseReg, unsigned IndexReg,
1123 unsigned Scale, SMLoc Start, SMLoc End,
1124 unsigned Size, StringRef SymName) {
1125 bool NeedSizeDir = false;
1126 if (const MCSymbolRefExpr *SymRef = dyn_cast<MCSymbolRefExpr>(Disp)) {
1127 const MCSymbol &Sym = SymRef->getSymbol();
1128 // FIXME: The SemaLookup will fail if the name is anything other then an
1130 // FIXME: Pass a valid SMLoc.
1131 bool IsVarDecl = false;
1132 unsigned tLength, tSize, tType;
1133 SemaCallback->LookupInlineAsmIdentifier(Sym.getName(), NULL, tLength, tSize,
1136 Size = tType * 8; // Size is in terms of bits in this context.
1137 NeedSizeDir = Size > 0;
1139 // If this is not a VarDecl then assume it is a FuncDecl or some other label
1140 // reference. We need an 'r' constraint here, so we need to create register
1141 // operand to ensure proper matching. Just pick a GPR based on the size of
1144 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1145 return X86Operand::CreateReg(RegNo, Start, End, /*AddressOf=*/true,
1151 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_SizeDirective, Start,
1154 // When parsing inline assembly we set the base register to a non-zero value
1155 // if we don't know the actual value at this time. This is necessary to
1156 // get the matching correct in some cases.
1157 BaseReg = BaseReg ? BaseReg : 1;
1158 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1159 End, Size, SymName);
1163 RewriteIntelBracExpression(SmallVectorImpl<AsmRewrite> *AsmRewrites,
1164 StringRef SymName, int64_t ImmDisp,
1165 int64_t FinalImmDisp, SMLoc &BracLoc,
1166 SMLoc &StartInBrac, SMLoc &End) {
1167 // Remove the '[' and ']' from the IR string.
1168 AsmRewrites->push_back(AsmRewrite(AOK_Skip, BracLoc, 1));
1169 AsmRewrites->push_back(AsmRewrite(AOK_Skip, End, 1));
1171 // If ImmDisp is non-zero, then we parsed a displacement before the
1172 // bracketed expression (i.e., ImmDisp [ BaseReg + Scale*IndexReg + Disp])
1173 // If ImmDisp doesn't match the displacement computed by the state machine
1174 // then we have an additional displacement in the bracketed expression.
1175 if (ImmDisp != FinalImmDisp) {
1177 // We have an immediate displacement before the bracketed expression.
1178 // Adjust this to match the final immediate displacement.
1180 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1181 E = AsmRewrites->end(); I != E; ++I) {
1182 if ((*I).Loc.getPointer() > BracLoc.getPointer())
1184 if ((*I).Kind == AOK_ImmPrefix || (*I).Kind == AOK_Imm) {
1185 assert (!Found && "ImmDisp already rewritten.");
1186 (*I).Kind = AOK_Imm;
1187 (*I).Len = BracLoc.getPointer() - (*I).Loc.getPointer();
1188 (*I).Val = FinalImmDisp;
1193 assert (Found && "Unable to rewrite ImmDisp.");
1195 // We have a symbolic and an immediate displacement, but no displacement
1196 // before the bracketed expression. Put the immediate displacement
1197 // before the bracketed expression.
1198 AsmRewrites->push_back(AsmRewrite(AOK_Imm, BracLoc, 0, FinalImmDisp));
1201 // Remove all the ImmPrefix rewrites within the brackets.
1202 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1203 E = AsmRewrites->end(); I != E; ++I) {
1204 if ((*I).Loc.getPointer() < StartInBrac.getPointer())
1206 if ((*I).Kind == AOK_ImmPrefix)
1207 (*I).Kind = AOK_Delete;
1209 const char *SymLocPtr = SymName.data();
1210 // Skip everything before the symbol.
1211 if (unsigned Len = SymLocPtr - StartInBrac.getPointer()) {
1212 assert(Len > 0 && "Expected a non-negative length.");
1213 AsmRewrites->push_back(AsmRewrite(AOK_Skip, StartInBrac, Len));
1215 // Skip everything after the symbol.
1216 if (unsigned Len = End.getPointer() - (SymLocPtr + SymName.size())) {
1217 SMLoc Loc = SMLoc::getFromPointer(SymLocPtr + SymName.size());
1218 assert(Len > 0 && "Expected a non-negative length.");
1219 AsmRewrites->push_back(AsmRewrite(AOK_Skip, Loc, Len));
1224 X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) {
1225 const AsmToken &Tok = Parser.getTok();
1229 bool UpdateLocLex = true;
1231 // The period in the dot operator (e.g., [ebx].foo.bar) is parsed as an
1232 // identifier. Don't try an parse it as a register.
1233 if (Tok.getString().startswith("."))
1236 // If we're parsing an immediate expression, we don't expect a '['.
1237 if (SM.getStopOnLBrac() && getLexer().getKind() == AsmToken::LBrac)
1240 switch (getLexer().getKind()) {
1242 if (SM.isValidEndState()) {
1246 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1248 case AsmToken::EndOfStatement: {
1252 case AsmToken::Identifier: {
1253 // This could be a register or a symbolic displacement.
1255 const MCExpr *Disp = 0;
1256 SMLoc IdentLoc = Tok.getLoc();
1257 StringRef Identifier = Tok.getString();
1258 if(!ParseRegister(TmpReg, IdentLoc, End)) {
1259 SM.onRegister(TmpReg);
1260 UpdateLocLex = false;
1262 } else if (!getParser().parsePrimaryExpr(Disp, End)) {
1263 if (X86Operand *Err = ParseIntelVarWithQualifier(Disp, Identifier))
1266 SM.onDispExpr(Disp, Identifier);
1267 UpdateLocLex = false;
1270 return ErrorOperand(Tok.getLoc(), "Unexpected identifier!");
1272 case AsmToken::Integer:
1273 if (isParsingInlineAsm() && SM.getAddImmPrefix())
1274 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1276 SM.onInteger(Tok.getIntVal());
1278 case AsmToken::Plus: SM.onPlus(); break;
1279 case AsmToken::Minus: SM.onMinus(); break;
1280 case AsmToken::Star: SM.onStar(); break;
1281 case AsmToken::Slash: SM.onDivide(); break;
1282 case AsmToken::LBrac: SM.onLBrac(); break;
1283 case AsmToken::RBrac: SM.onRBrac(); break;
1284 case AsmToken::LParen: SM.onLParen(); break;
1285 case AsmToken::RParen: SM.onRParen(); break;
1288 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1290 if (!Done && UpdateLocLex) {
1292 Parser.Lex(); // Consume the token.
1298 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
1301 const AsmToken &Tok = Parser.getTok();
1302 SMLoc BracLoc = Tok.getLoc(), End = Tok.getEndLoc();
1303 if (getLexer().isNot(AsmToken::LBrac))
1304 return ErrorOperand(BracLoc, "Expected '[' token!");
1305 Parser.Lex(); // Eat '['
1307 SMLoc StartInBrac = Tok.getLoc();
1308 // Parse [ Symbol + ImmDisp ] and [ BaseReg + Scale*IndexReg + ImmDisp ]. We
1309 // may have already parsed an immediate displacement before the bracketed
1311 IntelExprStateMachine SM(ImmDisp, /*StopOnLBrac=*/false, /*AddImmPrefix=*/true);
1312 if (X86Operand *Err = ParseIntelExpression(SM, End))
1316 if (const MCExpr *Sym = SM.getSym()) {
1317 // A symbolic displacement.
1319 if (isParsingInlineAsm())
1320 RewriteIntelBracExpression(InstInfo->AsmRewrites, SM.getSymName(),
1321 ImmDisp, SM.getImm(), BracLoc, StartInBrac,
1324 // An immediate displacement only.
1325 Disp = MCConstantExpr::Create(SM.getImm(), getContext());
1328 // Parse the dot operator (e.g., [ebx].foo.bar).
1329 if (Tok.getString().startswith(".")) {
1330 SmallString<64> Err;
1331 const MCExpr *NewDisp;
1332 if (ParseIntelDotOperator(Disp, &NewDisp, Err))
1333 return ErrorOperand(Tok.getLoc(), Err);
1335 End = Tok.getEndLoc();
1336 Parser.Lex(); // Eat the field.
1340 int BaseReg = SM.getBaseReg();
1341 int IndexReg = SM.getIndexReg();
1342 int Scale = SM.getScale();
1344 if (isParsingInlineAsm())
1345 return CreateMemForInlineAsm(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1346 End, Size, SM.getSymName());
1349 if (!BaseReg && !IndexReg) {
1351 return X86Operand::CreateMem(Disp, Start, End, Size);
1353 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, Start, End, Size);
1355 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1359 // Inline assembly may use variable names with namespace alias qualifiers.
1360 X86Operand *X86AsmParser::ParseIntelVarWithQualifier(const MCExpr *&Disp,
1361 StringRef &Identifier) {
1362 // We should only see Foo::Bar if we're parsing inline assembly.
1363 if (!isParsingInlineAsm())
1366 // If we don't see a ':' then there can't be a qualifier.
1367 if (getLexer().isNot(AsmToken::Colon))
1371 const AsmToken &Tok = Parser.getTok();
1372 AsmToken IdentEnd = Tok;
1374 switch (getLexer().getKind()) {
1378 case AsmToken::Colon:
1379 getLexer().Lex(); // Consume ':'.
1380 if (getLexer().isNot(AsmToken::Colon))
1381 return ErrorOperand(Tok.getLoc(), "Expected ':' token!");
1382 getLexer().Lex(); // Consume second ':'.
1383 if (getLexer().isNot(AsmToken::Identifier))
1384 return ErrorOperand(Tok.getLoc(), "Expected an identifier token!");
1386 case AsmToken::Identifier:
1388 getLexer().Lex(); // Consume the identifier.
1393 unsigned Len = IdentEnd.getLoc().getPointer() - Identifier.data();
1394 Identifier = StringRef(Identifier.data(), Len + IdentEnd.getString().size());
1395 MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier);
1396 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1397 Disp = MCSymbolRefExpr::Create(Sym, Variant, getParser().getContext());
1401 /// ParseIntelMemOperand - Parse intel style memory operand.
1402 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg,
1405 const AsmToken &Tok = Parser.getTok();
1408 unsigned Size = getIntelMemOperandSize(Tok.getString());
1411 assert ((Tok.getString() == "PTR" || Tok.getString() == "ptr") &&
1412 "Unexpected token!");
1416 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1417 if (getLexer().is(AsmToken::Integer)) {
1418 if (isParsingInlineAsm())
1419 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1421 int64_t ImmDisp = Tok.getIntVal();
1422 Parser.Lex(); // Eat the integer.
1423 if (getLexer().isNot(AsmToken::LBrac))
1424 return ErrorOperand(Start, "Expected '[' token!");
1425 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1428 if (getLexer().is(AsmToken::LBrac))
1429 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1431 if (!ParseRegister(SegReg, Start, End)) {
1432 // Handel SegReg : [ ... ]
1433 if (getLexer().isNot(AsmToken::Colon))
1434 return ErrorOperand(Start, "Expected ':' token!");
1435 Parser.Lex(); // Eat :
1436 if (getLexer().isNot(AsmToken::LBrac))
1437 return ErrorOperand(Start, "Expected '[' token!");
1438 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1441 const MCExpr *Disp = 0;
1442 StringRef Identifier = Tok.getString();
1443 if (getParser().parsePrimaryExpr(Disp, End))
1446 if (!isParsingInlineAsm())
1447 return X86Operand::CreateMem(Disp, Start, End, Size);
1449 if (X86Operand *Err = ParseIntelVarWithQualifier(Disp, Identifier))
1452 return CreateMemForInlineAsm(/*SegReg=*/0, Disp, /*BaseReg=*/0,/*IndexReg=*/0,
1453 /*Scale=*/1, Start, End, Size, Identifier);
1456 /// Parse the '.' operator.
1457 bool X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp,
1458 const MCExpr **NewDisp,
1459 SmallString<64> &Err) {
1460 const AsmToken &Tok = Parser.getTok();
1461 int64_t OrigDispVal, DotDispVal;
1463 // FIXME: Handle non-constant expressions.
1464 if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp)) {
1465 OrigDispVal = OrigDisp->getValue();
1467 Err = "Non-constant offsets are not supported!";
1472 StringRef DotDispStr = Tok.getString().drop_front(1);
1474 // .Imm gets lexed as a real.
1475 if (Tok.is(AsmToken::Real)) {
1477 DotDispStr.getAsInteger(10, DotDisp);
1478 DotDispVal = DotDisp.getZExtValue();
1479 } else if (Tok.is(AsmToken::Identifier)) {
1480 // We should only see an identifier when parsing the original inline asm.
1481 // The front-end should rewrite this in terms of immediates.
1482 assert (isParsingInlineAsm() && "Unexpected field name!");
1485 std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
1486 if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second,
1488 Err = "Unable to lookup field reference!";
1491 DotDispVal = DotDisp;
1493 Err = "Unexpected token type!";
1497 if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1498 SMLoc Loc = SMLoc::getFromPointer(DotDispStr.data());
1499 unsigned Len = DotDispStr.size();
1500 unsigned Val = OrigDispVal + DotDispVal;
1501 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_DotOperator, Loc, Len,
1505 *NewDisp = MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext());
1509 /// Parse the 'offset' operator. This operator is used to specify the
1510 /// location rather then the content of a variable.
1511 X86Operand *X86AsmParser::ParseIntelOffsetOfOperator() {
1512 const AsmToken &Tok = Parser.getTok();
1513 SMLoc OffsetOfLoc = Tok.getLoc();
1514 Parser.Lex(); // Eat offset.
1515 assert (Tok.is(AsmToken::Identifier) && "Expected an identifier");
1518 SMLoc Start = Tok.getLoc(), End;
1519 StringRef Identifier = Tok.getString();
1520 if (getParser().parsePrimaryExpr(Val, End))
1521 return ErrorOperand(Start, "Unable to parse expression!");
1523 const MCExpr *Disp = 0;
1524 if (X86Operand *Err = ParseIntelVarWithQualifier(Disp, Identifier))
1527 // Don't emit the offset operator.
1528 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Skip, OffsetOfLoc, 7));
1530 // The offset operator will have an 'r' constraint, thus we need to create
1531 // register operand to ensure proper matching. Just pick a GPR based on
1532 // the size of a pointer.
1533 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1534 return X86Operand::CreateReg(RegNo, Start, End, /*GetAddress=*/true,
1535 OffsetOfLoc, Identifier);
1538 enum IntelOperatorKind {
1544 /// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators. The LENGTH operator
1545 /// returns the number of elements in an array. It returns the value 1 for
1546 /// non-array variables. The SIZE operator returns the size of a C or C++
1547 /// variable. A variable's size is the product of its LENGTH and TYPE. The
1548 /// TYPE operator returns the size of a C or C++ type or variable. If the
1549 /// variable is an array, TYPE returns the size of a single element.
1550 X86Operand *X86AsmParser::ParseIntelOperator(unsigned OpKind) {
1551 const AsmToken &Tok = Parser.getTok();
1552 SMLoc TypeLoc = Tok.getLoc();
1553 Parser.Lex(); // Eat operator.
1554 assert (Tok.is(AsmToken::Identifier) && "Expected an identifier");
1557 AsmToken StartTok = Tok;
1558 SMLoc Start = Tok.getLoc(), End;
1559 StringRef Identifier = Tok.getString();
1560 if (getParser().parsePrimaryExpr(Val, End))
1561 return ErrorOperand(Start, "Unable to parse expression!");
1563 const MCExpr *Disp = 0;
1564 if (X86Operand *Err = ParseIntelVarWithQualifier(Disp, Identifier))
1567 unsigned Length = 0, Size = 0, Type = 0;
1568 if (const MCSymbolRefExpr *SymRef = dyn_cast<MCSymbolRefExpr>(Val)) {
1569 const MCSymbol &Sym = SymRef->getSymbol();
1570 // FIXME: The SemaLookup will fail if the name is anything other then an
1572 // FIXME: Pass a valid SMLoc.
1574 if (!SemaCallback->LookupInlineAsmIdentifier(Sym.getName(), NULL, Length,
1575 Size, Type, IsVarDecl))
1576 // FIXME: We don't warn on variables with namespace alias qualifiers
1577 // because support still needs to be added in the frontend.
1578 if (Identifier.equals(StartTok.getString()))
1579 return ErrorOperand(Start, "Unable to lookup expr!");
1583 default: llvm_unreachable("Unexpected operand kind!");
1584 case IOK_LENGTH: CVal = Length; break;
1585 case IOK_SIZE: CVal = Size; break;
1586 case IOK_TYPE: CVal = Type; break;
1589 // Rewrite the type operator and the C or C++ type or variable in terms of an
1590 // immediate. E.g. TYPE foo -> $$4
1591 unsigned Len = End.getPointer() - TypeLoc.getPointer();
1592 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, TypeLoc, Len, CVal));
1594 const MCExpr *Imm = MCConstantExpr::Create(CVal, getContext());
1595 return X86Operand::CreateImm(Imm, Start, End);
1598 X86Operand *X86AsmParser::ParseIntelOperand() {
1599 const AsmToken &Tok = Parser.getTok();
1600 SMLoc Start = Tok.getLoc(), End;
1601 StringRef AsmTokStr = Tok.getString();
1603 // Offset, length, type and size operators.
1604 if (isParsingInlineAsm()) {
1605 if (AsmTokStr == "offset" || AsmTokStr == "OFFSET")
1606 return ParseIntelOffsetOfOperator();
1607 if (AsmTokStr == "length" || AsmTokStr == "LENGTH")
1608 return ParseIntelOperator(IOK_LENGTH);
1609 if (AsmTokStr == "size" || AsmTokStr == "SIZE")
1610 return ParseIntelOperator(IOK_SIZE);
1611 if (AsmTokStr == "type" || AsmTokStr == "TYPE")
1612 return ParseIntelOperator(IOK_TYPE);
1616 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Minus) ||
1617 getLexer().is(AsmToken::LParen)) {
1618 AsmToken StartTok = Tok;
1619 IntelExprStateMachine SM(/*Imm=*/0, /*StopOnLBrac=*/true,
1620 /*AddImmPrefix=*/false);
1621 if (X86Operand *Err = ParseIntelExpression(SM, End))
1624 int64_t Imm = SM.getImm();
1625 if (isParsingInlineAsm()) {
1626 unsigned Len = Tok.getLoc().getPointer() - Start.getPointer();
1627 if (StartTok.getString().size() == Len)
1628 // Just add a prefix if this wasn't a complex immediate expression.
1629 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix, Start));
1631 // Otherwise, rewrite the complex expression as a single immediate.
1632 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, Start, Len, Imm));
1635 if (getLexer().isNot(AsmToken::LBrac)) {
1636 const MCExpr *ImmExpr = MCConstantExpr::Create(Imm, getContext());
1637 return X86Operand::CreateImm(ImmExpr, Start, End);
1640 // Only positive immediates are valid.
1642 return ErrorOperand(Start, "expected a positive immediate displacement "
1643 "before bracketed expr.");
1645 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1646 return ParseIntelMemOperand(/*SegReg=*/0, Imm, Start);
1651 if (!ParseRegister(RegNo, Start, End)) {
1652 // If this is a segment register followed by a ':', then this is the start
1653 // of a memory reference, otherwise this is a normal register reference.
1654 if (getLexer().isNot(AsmToken::Colon))
1655 return X86Operand::CreateReg(RegNo, Start, End);
1657 getParser().Lex(); // Eat the colon.
1658 return ParseIntelMemOperand(/*SegReg=*/RegNo, /*Disp=*/0, Start);
1662 return ParseIntelMemOperand(/*SegReg=*/0, /*Disp=*/0, Start);
1665 X86Operand *X86AsmParser::ParseATTOperand() {
1666 switch (getLexer().getKind()) {
1668 // Parse a memory operand with no segment register.
1669 return ParseMemOperand(0, Parser.getTok().getLoc());
1670 case AsmToken::Percent: {
1671 // Read the register.
1674 if (ParseRegister(RegNo, Start, End)) return 0;
1675 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
1676 Error(Start, "%eiz and %riz can only be used as index registers",
1677 SMRange(Start, End));
1681 // If this is a segment register followed by a ':', then this is the start
1682 // of a memory reference, otherwise this is a normal register reference.
1683 if (getLexer().isNot(AsmToken::Colon))
1684 return X86Operand::CreateReg(RegNo, Start, End);
1686 getParser().Lex(); // Eat the colon.
1687 return ParseMemOperand(RegNo, Start);
1689 case AsmToken::Dollar: {
1690 // $42 -> immediate.
1691 SMLoc Start = Parser.getTok().getLoc(), End;
1694 if (getParser().parseExpression(Val, End))
1696 return X86Operand::CreateImm(Val, Start, End);
1701 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
1702 /// has already been parsed if present.
1703 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
1705 // We have to disambiguate a parenthesized expression "(4+5)" from the start
1706 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
1707 // only way to do this without lookahead is to eat the '(' and see what is
1709 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
1710 if (getLexer().isNot(AsmToken::LParen)) {
1712 if (getParser().parseExpression(Disp, ExprEnd)) return 0;
1714 // After parsing the base expression we could either have a parenthesized
1715 // memory address or not. If not, return now. If so, eat the (.
1716 if (getLexer().isNot(AsmToken::LParen)) {
1717 // Unless we have a segment register, treat this as an immediate.
1719 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
1720 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1726 // Okay, we have a '('. We don't know if this is an expression or not, but
1727 // so we have to eat the ( to see beyond it.
1728 SMLoc LParenLoc = Parser.getTok().getLoc();
1729 Parser.Lex(); // Eat the '('.
1731 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
1732 // Nothing to do here, fall into the code below with the '(' part of the
1733 // memory operand consumed.
1737 // It must be an parenthesized expression, parse it now.
1738 if (getParser().parseParenExpression(Disp, ExprEnd))
1741 // After parsing the base expression we could either have a parenthesized
1742 // memory address or not. If not, return now. If so, eat the (.
1743 if (getLexer().isNot(AsmToken::LParen)) {
1744 // Unless we have a segment register, treat this as an immediate.
1746 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
1747 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1755 // If we reached here, then we just ate the ( of the memory operand. Process
1756 // the rest of the memory operand.
1757 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
1760 if (getLexer().is(AsmToken::Percent)) {
1761 SMLoc StartLoc, EndLoc;
1762 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
1763 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
1764 Error(StartLoc, "eiz and riz can only be used as index registers",
1765 SMRange(StartLoc, EndLoc));
1770 if (getLexer().is(AsmToken::Comma)) {
1771 Parser.Lex(); // Eat the comma.
1772 IndexLoc = Parser.getTok().getLoc();
1774 // Following the comma we should have either an index register, or a scale
1775 // value. We don't support the later form, but we want to parse it
1778 // Not that even though it would be completely consistent to support syntax
1779 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
1780 if (getLexer().is(AsmToken::Percent)) {
1782 if (ParseRegister(IndexReg, L, L)) return 0;
1784 if (getLexer().isNot(AsmToken::RParen)) {
1785 // Parse the scale amount:
1786 // ::= ',' [scale-expression]
1787 if (getLexer().isNot(AsmToken::Comma)) {
1788 Error(Parser.getTok().getLoc(),
1789 "expected comma in scale expression");
1792 Parser.Lex(); // Eat the comma.
1794 if (getLexer().isNot(AsmToken::RParen)) {
1795 SMLoc Loc = Parser.getTok().getLoc();
1798 if (getParser().parseAbsoluteExpression(ScaleVal)){
1799 Error(Loc, "expected scale expression");
1803 // Validate the scale amount.
1804 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
1805 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
1808 Scale = (unsigned)ScaleVal;
1811 } else if (getLexer().isNot(AsmToken::RParen)) {
1812 // A scale amount without an index is ignored.
1814 SMLoc Loc = Parser.getTok().getLoc();
1817 if (getParser().parseAbsoluteExpression(Value))
1821 Warning(Loc, "scale factor without index register is ignored");
1826 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1827 if (getLexer().isNot(AsmToken::RParen)) {
1828 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1831 SMLoc MemEnd = Parser.getTok().getEndLoc();
1832 Parser.Lex(); // Eat the ')'.
1834 // If we have both a base register and an index register make sure they are
1835 // both 64-bit or 32-bit registers.
1836 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1837 if (BaseReg != 0 && IndexReg != 0) {
1838 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1839 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1840 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1841 IndexReg != X86::RIZ) {
1842 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1845 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1846 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1847 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1848 IndexReg != X86::EIZ){
1849 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1854 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1859 ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
1860 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1862 StringRef PatchedName = Name;
1864 // FIXME: Hack to recognize setneb as setne.
1865 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1866 PatchedName != "setb" && PatchedName != "setnb")
1867 PatchedName = PatchedName.substr(0, Name.size()-1);
1869 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1870 const MCExpr *ExtraImmOp = 0;
1871 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1872 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1873 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1874 bool IsVCMP = PatchedName[0] == 'v';
1875 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1876 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1877 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1881 .Case("unord", 0x03)
1886 /* AVX only from here */
1887 .Case("eq_uq", 0x08)
1890 .Case("false", 0x0B)
1891 .Case("neq_oq", 0x0C)
1895 .Case("eq_os", 0x10)
1896 .Case("lt_oq", 0x11)
1897 .Case("le_oq", 0x12)
1898 .Case("unord_s", 0x13)
1899 .Case("neq_us", 0x14)
1900 .Case("nlt_uq", 0x15)
1901 .Case("nle_uq", 0x16)
1902 .Case("ord_s", 0x17)
1903 .Case("eq_us", 0x18)
1904 .Case("nge_uq", 0x19)
1905 .Case("ngt_uq", 0x1A)
1906 .Case("false_os", 0x1B)
1907 .Case("neq_os", 0x1C)
1908 .Case("ge_oq", 0x1D)
1909 .Case("gt_oq", 0x1E)
1910 .Case("true_us", 0x1F)
1912 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1913 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1914 getParser().getContext());
1915 if (PatchedName.endswith("ss")) {
1916 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1917 } else if (PatchedName.endswith("sd")) {
1918 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1919 } else if (PatchedName.endswith("ps")) {
1920 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1922 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1923 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1928 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1930 if (ExtraImmOp && !isParsingIntelSyntax())
1931 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1933 // Determine whether this is an instruction prefix.
1935 Name == "lock" || Name == "rep" ||
1936 Name == "repe" || Name == "repz" ||
1937 Name == "repne" || Name == "repnz" ||
1938 Name == "rex64" || Name == "data16";
1941 // This does the actual operand parsing. Don't parse any more if we have a
1942 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1943 // just want to parse the "lock" as the first instruction and the "incl" as
1945 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1947 // Parse '*' modifier.
1948 if (getLexer().is(AsmToken::Star)) {
1949 SMLoc Loc = Parser.getTok().getLoc();
1950 Operands.push_back(X86Operand::CreateToken("*", Loc));
1951 Parser.Lex(); // Eat the star.
1954 // Read the first operand.
1955 if (X86Operand *Op = ParseOperand())
1956 Operands.push_back(Op);
1958 Parser.eatToEndOfStatement();
1962 while (getLexer().is(AsmToken::Comma)) {
1963 Parser.Lex(); // Eat the comma.
1965 // Parse and remember the operand.
1966 if (X86Operand *Op = ParseOperand())
1967 Operands.push_back(Op);
1969 Parser.eatToEndOfStatement();
1974 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1975 SMLoc Loc = getLexer().getLoc();
1976 Parser.eatToEndOfStatement();
1977 return Error(Loc, "unexpected token in argument list");
1981 if (getLexer().is(AsmToken::EndOfStatement))
1982 Parser.Lex(); // Consume the EndOfStatement
1983 else if (isPrefix && getLexer().is(AsmToken::Slash))
1984 Parser.Lex(); // Consume the prefix separator Slash
1986 if (ExtraImmOp && isParsingIntelSyntax())
1987 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1989 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1990 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1991 // documented form in various unofficial manuals, so a lot of code uses it.
1992 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1993 Operands.size() == 3) {
1994 X86Operand &Op = *(X86Operand*)Operands.back();
1995 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1996 isa<MCConstantExpr>(Op.Mem.Disp) &&
1997 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1998 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1999 SMLoc Loc = Op.getEndLoc();
2000 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
2004 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
2005 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
2006 Operands.size() == 3) {
2007 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2008 if (Op.isMem() && Op.Mem.SegReg == 0 &&
2009 isa<MCConstantExpr>(Op.Mem.Disp) &&
2010 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2011 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2012 SMLoc Loc = Op.getEndLoc();
2013 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
2017 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
2018 if (Name.startswith("ins") && Operands.size() == 3 &&
2019 (Name == "insb" || Name == "insw" || Name == "insl")) {
2020 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2021 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2022 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
2023 Operands.pop_back();
2024 Operands.pop_back();
2030 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
2031 if (Name.startswith("outs") && Operands.size() == 3 &&
2032 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
2033 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2034 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2035 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
2036 Operands.pop_back();
2037 Operands.pop_back();
2043 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
2044 if (Name.startswith("movs") && Operands.size() == 3 &&
2045 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
2046 (is64BitMode() && Name == "movsq"))) {
2047 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2048 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2049 if (isSrcOp(Op) && isDstOp(Op2)) {
2050 Operands.pop_back();
2051 Operands.pop_back();
2056 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
2057 if (Name.startswith("lods") && Operands.size() == 3 &&
2058 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
2059 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
2060 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2061 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2062 if (isSrcOp(*Op1) && Op2->isReg()) {
2064 unsigned reg = Op2->getReg();
2065 bool isLods = Name == "lods";
2066 if (reg == X86::AL && (isLods || Name == "lodsb"))
2068 else if (reg == X86::AX && (isLods || Name == "lodsw"))
2070 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
2072 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
2077 Operands.pop_back();
2078 Operands.pop_back();
2082 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2086 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
2087 if (Name.startswith("stos") && Operands.size() == 3 &&
2088 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
2089 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
2090 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2091 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2092 if (isDstOp(*Op2) && Op1->isReg()) {
2094 unsigned reg = Op1->getReg();
2095 bool isStos = Name == "stos";
2096 if (reg == X86::AL && (isStos || Name == "stosb"))
2098 else if (reg == X86::AX && (isStos || Name == "stosw"))
2100 else if (reg == X86::EAX && (isStos || Name == "stosl"))
2102 else if (reg == X86::RAX && (isStos || Name == "stosq"))
2107 Operands.pop_back();
2108 Operands.pop_back();
2112 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2117 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
2119 if ((Name.startswith("shr") || Name.startswith("sar") ||
2120 Name.startswith("shl") || Name.startswith("sal") ||
2121 Name.startswith("rcl") || Name.startswith("rcr") ||
2122 Name.startswith("rol") || Name.startswith("ror")) &&
2123 Operands.size() == 3) {
2124 if (isParsingIntelSyntax()) {
2126 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
2127 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2128 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2130 Operands.pop_back();
2133 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2134 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2135 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2137 Operands.erase(Operands.begin() + 1);
2142 // Transforms "int $3" into "int3" as a size optimization. We can't write an
2143 // instalias with an immediate operand yet.
2144 if (Name == "int" && Operands.size() == 2) {
2145 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2146 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2147 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
2149 Operands.erase(Operands.begin() + 1);
2150 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
2157 static bool convertToSExti8(MCInst &Inst, unsigned Opcode, unsigned Reg,
2160 TmpInst.setOpcode(Opcode);
2162 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2163 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2164 TmpInst.addOperand(Inst.getOperand(0));
2169 static bool convert16i16to16ri8(MCInst &Inst, unsigned Opcode,
2170 bool isCmp = false) {
2171 if (!Inst.getOperand(0).isImm() ||
2172 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
2175 return convertToSExti8(Inst, Opcode, X86::AX, isCmp);
2178 static bool convert32i32to32ri8(MCInst &Inst, unsigned Opcode,
2179 bool isCmp = false) {
2180 if (!Inst.getOperand(0).isImm() ||
2181 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
2184 return convertToSExti8(Inst, Opcode, X86::EAX, isCmp);
2187 static bool convert64i32to64ri8(MCInst &Inst, unsigned Opcode,
2188 bool isCmp = false) {
2189 if (!Inst.getOperand(0).isImm() ||
2190 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
2193 return convertToSExti8(Inst, Opcode, X86::RAX, isCmp);
2197 processInstruction(MCInst &Inst,
2198 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
2199 switch (Inst.getOpcode()) {
2200 default: return false;
2201 case X86::AND16i16: return convert16i16to16ri8(Inst, X86::AND16ri8);
2202 case X86::AND32i32: return convert32i32to32ri8(Inst, X86::AND32ri8);
2203 case X86::AND64i32: return convert64i32to64ri8(Inst, X86::AND64ri8);
2204 case X86::XOR16i16: return convert16i16to16ri8(Inst, X86::XOR16ri8);
2205 case X86::XOR32i32: return convert32i32to32ri8(Inst, X86::XOR32ri8);
2206 case X86::XOR64i32: return convert64i32to64ri8(Inst, X86::XOR64ri8);
2207 case X86::OR16i16: return convert16i16to16ri8(Inst, X86::OR16ri8);
2208 case X86::OR32i32: return convert32i32to32ri8(Inst, X86::OR32ri8);
2209 case X86::OR64i32: return convert64i32to64ri8(Inst, X86::OR64ri8);
2210 case X86::CMP16i16: return convert16i16to16ri8(Inst, X86::CMP16ri8, true);
2211 case X86::CMP32i32: return convert32i32to32ri8(Inst, X86::CMP32ri8, true);
2212 case X86::CMP64i32: return convert64i32to64ri8(Inst, X86::CMP64ri8, true);
2213 case X86::ADD16i16: return convert16i16to16ri8(Inst, X86::ADD16ri8);
2214 case X86::ADD32i32: return convert32i32to32ri8(Inst, X86::ADD32ri8);
2215 case X86::ADD64i32: return convert64i32to64ri8(Inst, X86::ADD64ri8);
2216 case X86::SUB16i16: return convert16i16to16ri8(Inst, X86::SUB16ri8);
2217 case X86::SUB32i32: return convert32i32to32ri8(Inst, X86::SUB32ri8);
2218 case X86::SUB64i32: return convert64i32to64ri8(Inst, X86::SUB64ri8);
2219 case X86::ADC16i16: return convert16i16to16ri8(Inst, X86::ADC16ri8);
2220 case X86::ADC32i32: return convert32i32to32ri8(Inst, X86::ADC32ri8);
2221 case X86::ADC64i32: return convert64i32to64ri8(Inst, X86::ADC64ri8);
2222 case X86::SBB16i16: return convert16i16to16ri8(Inst, X86::SBB16ri8);
2223 case X86::SBB32i32: return convert32i32to32ri8(Inst, X86::SBB32ri8);
2224 case X86::SBB64i32: return convert64i32to64ri8(Inst, X86::SBB64ri8);
2228 static const char *getSubtargetFeatureName(unsigned Val);
2230 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2231 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2232 MCStreamer &Out, unsigned &ErrorInfo,
2233 bool MatchingInlineAsm) {
2234 assert(!Operands.empty() && "Unexpect empty operand list!");
2235 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
2236 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
2237 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
2239 // First, handle aliases that expand to multiple instructions.
2240 // FIXME: This should be replaced with a real .td file alias mechanism.
2241 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
2243 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
2244 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
2245 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
2246 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
2248 Inst.setOpcode(X86::WAIT);
2250 if (!MatchingInlineAsm)
2251 Out.EmitInstruction(Inst);
2254 StringSwitch<const char*>(Op->getToken())
2255 .Case("finit", "fninit")
2256 .Case("fsave", "fnsave")
2257 .Case("fstcw", "fnstcw")
2258 .Case("fstcww", "fnstcw")
2259 .Case("fstenv", "fnstenv")
2260 .Case("fstsw", "fnstsw")
2261 .Case("fstsww", "fnstsw")
2262 .Case("fclex", "fnclex")
2264 assert(Repl && "Unknown wait-prefixed instruction");
2266 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
2269 bool WasOriginallyInvalidOperand = false;
2272 // First, try a direct match.
2273 switch (MatchInstructionImpl(Operands, Inst,
2274 ErrorInfo, MatchingInlineAsm,
2275 isParsingIntelSyntax())) {
2278 // Some instructions need post-processing to, for example, tweak which
2279 // encoding is selected. Loop on it while changes happen so the
2280 // individual transformations can chain off each other.
2281 if (!MatchingInlineAsm)
2282 while (processInstruction(Inst, Operands))
2286 if (!MatchingInlineAsm)
2287 Out.EmitInstruction(Inst);
2288 Opcode = Inst.getOpcode();
2290 case Match_MissingFeature: {
2291 assert(ErrorInfo && "Unknown missing feature!");
2292 // Special case the error message for the very common case where only
2293 // a single subtarget feature is missing.
2294 std::string Msg = "instruction requires:";
2296 for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
2297 if (ErrorInfo & Mask) {
2299 Msg += getSubtargetFeatureName(ErrorInfo & Mask);
2303 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2305 case Match_InvalidOperand:
2306 WasOriginallyInvalidOperand = true;
2308 case Match_MnemonicFail:
2312 // FIXME: Ideally, we would only attempt suffix matches for things which are
2313 // valid prefixes, and we could just infer the right unambiguous
2314 // type. However, that requires substantially more matcher support than the
2317 // Change the operand to point to a temporary token.
2318 StringRef Base = Op->getToken();
2319 SmallString<16> Tmp;
2322 Op->setTokenValue(Tmp.str());
2324 // If this instruction starts with an 'f', then it is a floating point stack
2325 // instruction. These come in up to three forms for 32-bit, 64-bit, and
2326 // 80-bit floating point, which use the suffixes s,l,t respectively.
2328 // Otherwise, we assume that this may be an integer instruction, which comes
2329 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
2330 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
2332 // Check for the various suffix matches.
2333 Tmp[Base.size()] = Suffixes[0];
2334 unsigned ErrorInfoIgnore;
2335 unsigned ErrorInfoMissingFeature = 0; // Init suppresses compiler warnings.
2336 unsigned Match1, Match2, Match3, Match4;
2338 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2339 isParsingIntelSyntax());
2340 // If this returned as a missing feature failure, remember that.
2341 if (Match1 == Match_MissingFeature)
2342 ErrorInfoMissingFeature = ErrorInfoIgnore;
2343 Tmp[Base.size()] = Suffixes[1];
2344 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2345 isParsingIntelSyntax());
2346 // If this returned as a missing feature failure, remember that.
2347 if (Match2 == Match_MissingFeature)
2348 ErrorInfoMissingFeature = ErrorInfoIgnore;
2349 Tmp[Base.size()] = Suffixes[2];
2350 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2351 isParsingIntelSyntax());
2352 // If this returned as a missing feature failure, remember that.
2353 if (Match3 == Match_MissingFeature)
2354 ErrorInfoMissingFeature = ErrorInfoIgnore;
2355 Tmp[Base.size()] = Suffixes[3];
2356 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2357 isParsingIntelSyntax());
2358 // If this returned as a missing feature failure, remember that.
2359 if (Match4 == Match_MissingFeature)
2360 ErrorInfoMissingFeature = ErrorInfoIgnore;
2362 // Restore the old token.
2363 Op->setTokenValue(Base);
2365 // If exactly one matched, then we treat that as a successful match (and the
2366 // instruction will already have been filled in correctly, since the failing
2367 // matches won't have modified it).
2368 unsigned NumSuccessfulMatches =
2369 (Match1 == Match_Success) + (Match2 == Match_Success) +
2370 (Match3 == Match_Success) + (Match4 == Match_Success);
2371 if (NumSuccessfulMatches == 1) {
2373 if (!MatchingInlineAsm)
2374 Out.EmitInstruction(Inst);
2375 Opcode = Inst.getOpcode();
2379 // Otherwise, the match failed, try to produce a decent error message.
2381 // If we had multiple suffix matches, then identify this as an ambiguous
2383 if (NumSuccessfulMatches > 1) {
2385 unsigned NumMatches = 0;
2386 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
2387 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
2388 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
2389 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
2391 SmallString<126> Msg;
2392 raw_svector_ostream OS(Msg);
2393 OS << "ambiguous instructions require an explicit suffix (could be ";
2394 for (unsigned i = 0; i != NumMatches; ++i) {
2397 if (i + 1 == NumMatches)
2399 OS << "'" << Base << MatchChars[i] << "'";
2402 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
2406 // Okay, we know that none of the variants matched successfully.
2408 // If all of the instructions reported an invalid mnemonic, then the original
2409 // mnemonic was invalid.
2410 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
2411 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
2412 if (!WasOriginallyInvalidOperand) {
2413 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
2415 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
2416 Ranges, MatchingInlineAsm);
2419 // Recover location info for the operand if we know which was the problem.
2420 if (ErrorInfo != ~0U) {
2421 if (ErrorInfo >= Operands.size())
2422 return Error(IDLoc, "too few operands for instruction",
2423 EmptyRanges, MatchingInlineAsm);
2425 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
2426 if (Operand->getStartLoc().isValid()) {
2427 SMRange OperandRange = Operand->getLocRange();
2428 return Error(Operand->getStartLoc(), "invalid operand for instruction",
2429 OperandRange, MatchingInlineAsm);
2433 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2437 // If one instruction matched with a missing feature, report this as a
2439 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
2440 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
2441 std::string Msg = "instruction requires:";
2443 for (unsigned i = 0; i < (sizeof(ErrorInfoMissingFeature)*8-1); ++i) {
2444 if (ErrorInfoMissingFeature & Mask) {
2446 Msg += getSubtargetFeatureName(ErrorInfoMissingFeature & Mask);
2450 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2453 // If one instruction matched with an invalid operand, report this as an
2455 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
2456 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
2457 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2462 // If all of these were an outright failure, report it in a useless way.
2463 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
2464 EmptyRanges, MatchingInlineAsm);
2469 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
2470 StringRef IDVal = DirectiveID.getIdentifier();
2471 if (IDVal == ".word")
2472 return ParseDirectiveWord(2, DirectiveID.getLoc());
2473 else if (IDVal.startswith(".code"))
2474 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
2475 else if (IDVal.startswith(".att_syntax")) {
2476 getParser().setAssemblerDialect(0);
2478 } else if (IDVal.startswith(".intel_syntax")) {
2479 getParser().setAssemblerDialect(1);
2480 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2481 if(Parser.getTok().getString() == "noprefix") {
2482 // FIXME : Handle noprefix
2492 /// ParseDirectiveWord
2493 /// ::= .word [ expression (, expression)* ]
2494 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
2495 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2497 const MCExpr *Value;
2498 if (getParser().parseExpression(Value))
2501 getParser().getStreamer().EmitValue(Value, Size);
2503 if (getLexer().is(AsmToken::EndOfStatement))
2506 // FIXME: Improve diagnostic.
2507 if (getLexer().isNot(AsmToken::Comma))
2508 return Error(L, "unexpected token in directive");
2517 /// ParseDirectiveCode
2518 /// ::= .code32 | .code64
2519 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
2520 if (IDVal == ".code32") {
2522 if (is64BitMode()) {
2524 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
2526 } else if (IDVal == ".code64") {
2528 if (!is64BitMode()) {
2530 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
2533 return Error(L, "unexpected directive " + IDVal);
2539 // Force static initialization.
2540 extern "C" void LLVMInitializeX86AsmParser() {
2541 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
2542 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
2545 #define GET_REGISTER_MATCHER
2546 #define GET_MATCHER_IMPLEMENTATION
2547 #define GET_SUBTARGET_FEATURE_NAME
2548 #include "X86GenAsmMatcher.inc"