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 SMLoc consumeToken() {
54 SMLoc Result = Parser.getTok().getLoc();
59 enum InfixCalculatorTok {
70 class InfixCalculator {
71 typedef std::pair< InfixCalculatorTok, int64_t > ICToken;
72 SmallVector<InfixCalculatorTok, 4> InfixOperatorStack;
73 SmallVector<ICToken, 4> PostfixStack;
76 int64_t popOperand() {
77 assert (!PostfixStack.empty() && "Poped an empty stack!");
78 ICToken Op = PostfixStack.pop_back_val();
79 assert ((Op.first == IC_IMM || Op.first == IC_REGISTER)
80 && "Expected and immediate or register!");
83 void pushOperand(InfixCalculatorTok Op, int64_t Val = 0) {
84 assert ((Op == IC_IMM || Op == IC_REGISTER) &&
85 "Unexpected operand!");
86 PostfixStack.push_back(std::make_pair(Op, Val));
89 void popOperator() { InfixOperatorStack.pop_back(); }
90 void pushOperator(InfixCalculatorTok Op) {
91 // Push the new operator if the stack is empty.
92 if (InfixOperatorStack.empty()) {
93 InfixOperatorStack.push_back(Op);
97 // Push the new operator if it has a higher precedence than the operator
98 // on the top of the stack or the operator on the top of the stack is a
100 unsigned Idx = InfixOperatorStack.size() - 1;
101 InfixCalculatorTok StackOp = InfixOperatorStack[Idx];
102 if (OpPrecedence[Op] > OpPrecedence[StackOp] || StackOp == IC_LPAREN) {
103 InfixOperatorStack.push_back(Op);
107 // The operator on the top of the stack has higher precedence than the
109 unsigned ParenCount = 0;
111 // Nothing to process.
112 if (InfixOperatorStack.empty())
115 Idx = InfixOperatorStack.size() - 1;
116 StackOp = InfixOperatorStack[Idx];
117 if (!(OpPrecedence[StackOp] >= OpPrecedence[Op] || ParenCount))
120 // If we have an even parentheses count and we see a left parentheses,
121 // then stop processing.
122 if (!ParenCount && StackOp == IC_LPAREN)
125 if (StackOp == IC_RPAREN) {
127 InfixOperatorStack.pop_back();
128 } else if (StackOp == IC_LPAREN) {
130 InfixOperatorStack.pop_back();
132 InfixOperatorStack.pop_back();
133 PostfixStack.push_back(std::make_pair(StackOp, 0));
136 // Push the new operator.
137 InfixOperatorStack.push_back(Op);
140 // Push any remaining operators onto the postfix stack.
141 while (!InfixOperatorStack.empty()) {
142 InfixCalculatorTok StackOp = InfixOperatorStack.pop_back_val();
143 if (StackOp != IC_LPAREN && StackOp != IC_RPAREN)
144 PostfixStack.push_back(std::make_pair(StackOp, 0));
147 if (PostfixStack.empty())
150 SmallVector<ICToken, 16> OperandStack;
151 for (unsigned i = 0, e = PostfixStack.size(); i != e; ++i) {
152 ICToken Op = PostfixStack[i];
153 if (Op.first == IC_IMM || Op.first == IC_REGISTER) {
154 OperandStack.push_back(Op);
156 assert (OperandStack.size() > 1 && "Too few operands.");
158 ICToken Op2 = OperandStack.pop_back_val();
159 ICToken Op1 = OperandStack.pop_back_val();
162 report_fatal_error("Unexpected operator!");
165 Val = Op1.second + Op2.second;
166 OperandStack.push_back(std::make_pair(IC_IMM, Val));
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 "Multiply operation with an immediate and a register!");
175 Val = Op1.second * Op2.second;
176 OperandStack.push_back(std::make_pair(IC_IMM, Val));
179 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
180 "Divide operation with an immediate and a register!");
181 assert (Op2.second != 0 && "Division by zero!");
182 Val = Op1.second / Op2.second;
183 OperandStack.push_back(std::make_pair(IC_IMM, Val));
188 assert (OperandStack.size() == 1 && "Expected a single result.");
189 return OperandStack.pop_back_val().second;
193 enum IntelExprState {
208 class IntelExprStateMachine {
209 IntelExprState State, PrevState;
210 unsigned BaseReg, IndexReg, TmpReg, Scale;
214 bool StopOnLBrac, AddImmPrefix;
216 InlineAsmIdentifierInfo Info;
218 IntelExprStateMachine(int64_t imm, bool stoponlbrac, bool addimmprefix) :
219 State(IES_PLUS), PrevState(IES_ERROR), BaseReg(0), IndexReg(0), TmpReg(0),
220 Scale(1), Imm(imm), Sym(0), StopOnLBrac(stoponlbrac),
221 AddImmPrefix(addimmprefix) { Info.clear(); }
223 unsigned getBaseReg() { return BaseReg; }
224 unsigned getIndexReg() { return IndexReg; }
225 unsigned getScale() { return Scale; }
226 const MCExpr *getSym() { return Sym; }
227 StringRef getSymName() { return SymName; }
228 int64_t getImm() { return Imm + IC.execute(); }
229 bool isValidEndState() {
230 return State == IES_RBRAC || State == IES_INTEGER;
232 bool getStopOnLBrac() { return StopOnLBrac; }
233 bool getAddImmPrefix() { return AddImmPrefix; }
234 bool hadError() { return State == IES_ERROR; }
236 InlineAsmIdentifierInfo &getIdentifierInfo() {
241 IntelExprState CurrState = State;
250 IC.pushOperator(IC_PLUS);
251 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
252 // If we already have a BaseReg, then assume this is the IndexReg with
257 assert (!IndexReg && "BaseReg/IndexReg already set!");
264 PrevState = CurrState;
267 IntelExprState CurrState = State;
282 // Only push the minus operator if it is not a unary operator.
283 if (!(CurrState == IES_PLUS || CurrState == IES_MINUS ||
284 CurrState == IES_MULTIPLY || CurrState == IES_DIVIDE ||
285 CurrState == IES_LPAREN || CurrState == IES_LBRAC))
286 IC.pushOperator(IC_MINUS);
287 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
288 // If we already have a BaseReg, then assume this is the IndexReg with
293 assert (!IndexReg && "BaseReg/IndexReg already set!");
300 PrevState = CurrState;
302 void onRegister(unsigned Reg) {
303 IntelExprState CurrState = State;
310 State = IES_REGISTER;
312 IC.pushOperand(IC_REGISTER);
315 // Index Register - Scale * Register
316 if (PrevState == IES_INTEGER) {
317 assert (!IndexReg && "IndexReg already set!");
318 State = IES_REGISTER;
320 // Get the scale and replace the 'Scale * Register' with '0'.
321 Scale = IC.popOperand();
322 IC.pushOperand(IC_IMM);
329 PrevState = CurrState;
331 void onIdentifierExpr(const MCExpr *SymRef, StringRef SymRefName) {
341 SymName = SymRefName;
342 IC.pushOperand(IC_IMM);
346 void onInteger(int64_t TmpInt) {
347 IntelExprState CurrState = State;
358 if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) {
359 // Index Register - Register * Scale
360 assert (!IndexReg && "IndexReg already set!");
363 // Get the scale and replace the 'Register * Scale' with '0'.
365 } else if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
366 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
367 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
368 CurrState == IES_MINUS) {
369 // Unary minus. No need to pop the minus operand because it was never
371 IC.pushOperand(IC_IMM, -TmpInt); // Push -Imm.
373 IC.pushOperand(IC_IMM, TmpInt);
377 PrevState = CurrState;
388 State = IES_MULTIPLY;
389 IC.pushOperator(IC_MULTIPLY);
402 IC.pushOperator(IC_DIVIDE);
414 IC.pushOperator(IC_PLUS);
419 IntelExprState CurrState = State;
428 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
429 // If we already have a BaseReg, then assume this is the IndexReg with
434 assert (!IndexReg && "BaseReg/IndexReg already set!");
441 PrevState = CurrState;
444 IntelExprState CurrState = State;
454 // FIXME: We don't handle this type of unary minus, yet.
455 if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
456 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
457 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
458 CurrState == IES_MINUS) {
463 IC.pushOperator(IC_LPAREN);
466 PrevState = CurrState;
478 IC.pushOperator(IC_RPAREN);
484 MCAsmParser &getParser() const { return Parser; }
486 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
488 bool Error(SMLoc L, const Twine &Msg,
489 ArrayRef<SMRange> Ranges = None,
490 bool MatchingInlineAsm = false) {
491 if (MatchingInlineAsm) return true;
492 return Parser.Error(L, Msg, Ranges);
495 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
500 X86Operand *ParseOperand();
501 X86Operand *ParseATTOperand();
502 X86Operand *ParseIntelOperand();
503 X86Operand *ParseIntelOffsetOfOperator();
504 bool ParseIntelDotOperator(const MCExpr *Disp, const MCExpr *&NewDisp);
505 X86Operand *ParseIntelOperator(unsigned OpKind);
506 X86Operand *ParseIntelSegmentOverride(unsigned SegReg, SMLoc Start, unsigned Size);
507 X86Operand *ParseIntelMemOperand(int64_t ImmDisp, SMLoc StartLoc,
509 bool ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End);
510 X86Operand *ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
511 int64_t ImmDisp, unsigned Size);
512 bool ParseIntelIdentifier(const MCExpr *&Val, StringRef &Identifier,
513 InlineAsmIdentifierInfo &Info,
514 bool IsUnevaluatedOperand, SMLoc &End);
516 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
518 X86Operand *CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
519 unsigned BaseReg, unsigned IndexReg,
520 unsigned Scale, SMLoc Start, SMLoc End,
521 unsigned Size, StringRef Identifier,
522 InlineAsmIdentifierInfo &Info);
524 bool ParseDirectiveWord(unsigned Size, SMLoc L);
525 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
527 bool processInstruction(MCInst &Inst,
528 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
530 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
531 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
532 MCStreamer &Out, unsigned &ErrorInfo,
533 bool MatchingInlineAsm);
535 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
536 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
537 bool isSrcOp(X86Operand &Op);
539 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
540 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
541 bool isDstOp(X86Operand &Op);
543 bool is64BitMode() const {
544 // FIXME: Can tablegen auto-generate this?
545 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
547 bool is32BitMode() const {
548 // FIXME: Can tablegen auto-generate this?
549 return (STI.getFeatureBits() & X86::Mode32Bit) != 0;
551 bool is16BitMode() const {
552 // FIXME: Can tablegen auto-generate this?
553 return (STI.getFeatureBits() & X86::Mode16Bit) != 0;
555 void SwitchMode(uint64_t mode) {
556 uint64_t oldMode = STI.getFeatureBits() &
557 (X86::Mode64Bit | X86::Mode32Bit | X86::Mode16Bit);
558 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(oldMode | mode));
559 setAvailableFeatures(FB);
560 assert(mode == (STI.getFeatureBits() &
561 (X86::Mode64Bit | X86::Mode32Bit | X86::Mode16Bit)));
564 bool isParsingIntelSyntax() {
565 return getParser().getAssemblerDialect();
568 /// @name Auto-generated Matcher Functions
571 #define GET_ASSEMBLER_HEADER
572 #include "X86GenAsmMatcher.inc"
577 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser,
578 const MCInstrInfo &MII)
579 : MCTargetAsmParser(), STI(sti), Parser(parser), InstInfo(0) {
581 // Initialize the set of available features.
582 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
584 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
586 virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
588 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
590 virtual bool ParseDirective(AsmToken DirectiveID);
592 } // end anonymous namespace
594 /// @name Auto-generated Match Functions
597 static unsigned MatchRegisterName(StringRef Name);
601 static bool isImmSExti16i8Value(uint64_t Value) {
602 return (( Value <= 0x000000000000007FULL)||
603 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
604 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
607 static bool isImmSExti32i8Value(uint64_t Value) {
608 return (( Value <= 0x000000000000007FULL)||
609 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
610 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
613 static bool isImmZExtu32u8Value(uint64_t Value) {
614 return (Value <= 0x00000000000000FFULL);
617 static bool isImmSExti64i8Value(uint64_t Value) {
618 return (( Value <= 0x000000000000007FULL)||
619 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
622 static bool isImmSExti64i32Value(uint64_t Value) {
623 return (( Value <= 0x000000007FFFFFFFULL)||
624 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
628 /// X86Operand - Instances of this class represent a parsed X86 machine
630 struct X86Operand : public MCParsedAsmOperand {
638 SMLoc StartLoc, EndLoc;
673 X86Operand(KindTy K, SMLoc Start, SMLoc End)
674 : Kind(K), StartLoc(Start), EndLoc(End) {}
676 StringRef getSymName() { return SymName; }
677 void *getOpDecl() { return OpDecl; }
679 /// getStartLoc - Get the location of the first token of this operand.
680 SMLoc getStartLoc() const { return StartLoc; }
681 /// getEndLoc - Get the location of the last token of this operand.
682 SMLoc getEndLoc() const { return EndLoc; }
683 /// getLocRange - Get the range between the first and last token of this
685 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
686 /// getOffsetOfLoc - Get the location of the offset operator.
687 SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
689 virtual void print(raw_ostream &OS) const {}
691 StringRef getToken() const {
692 assert(Kind == Token && "Invalid access!");
693 return StringRef(Tok.Data, Tok.Length);
695 void setTokenValue(StringRef Value) {
696 assert(Kind == Token && "Invalid access!");
697 Tok.Data = Value.data();
698 Tok.Length = Value.size();
701 unsigned getReg() const {
702 assert(Kind == Register && "Invalid access!");
706 const MCExpr *getImm() const {
707 assert(Kind == Immediate && "Invalid access!");
711 const MCExpr *getMemDisp() const {
712 assert(Kind == Memory && "Invalid access!");
715 unsigned getMemSegReg() const {
716 assert(Kind == Memory && "Invalid access!");
719 unsigned getMemBaseReg() const {
720 assert(Kind == Memory && "Invalid access!");
723 unsigned getMemIndexReg() const {
724 assert(Kind == Memory && "Invalid access!");
727 unsigned getMemScale() const {
728 assert(Kind == Memory && "Invalid access!");
732 bool isToken() const {return Kind == Token; }
734 bool isImm() const { return Kind == Immediate; }
736 bool isImmSExti16i8() const {
740 // If this isn't a constant expr, just assume it fits and let relaxation
742 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
746 // Otherwise, check the value is in a range that makes sense for this
748 return isImmSExti16i8Value(CE->getValue());
750 bool isImmSExti32i8() const {
754 // If this isn't a constant expr, just assume it fits and let relaxation
756 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
760 // Otherwise, check the value is in a range that makes sense for this
762 return isImmSExti32i8Value(CE->getValue());
764 bool isImmZExtu32u8() const {
768 // If this isn't a constant expr, just assume it fits and let relaxation
770 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
774 // Otherwise, check the value is in a range that makes sense for this
776 return isImmZExtu32u8Value(CE->getValue());
778 bool isImmSExti64i8() const {
782 // If this isn't a constant expr, just assume it fits and let relaxation
784 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
788 // Otherwise, check the value is in a range that makes sense for this
790 return isImmSExti64i8Value(CE->getValue());
792 bool isImmSExti64i32() const {
796 // If this isn't a constant expr, just assume it fits and let relaxation
798 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
802 // Otherwise, check the value is in a range that makes sense for this
804 return isImmSExti64i32Value(CE->getValue());
807 bool isOffsetOf() const {
808 return OffsetOfLoc.getPointer();
811 bool needAddressOf() const {
815 bool isMem() const { return Kind == Memory; }
816 bool isMem8() const {
817 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
819 bool isMem16() const {
820 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
822 bool isMem32() const {
823 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
825 bool isMem64() const {
826 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
828 bool isMem80() const {
829 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
831 bool isMem128() const {
832 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
834 bool isMem256() const {
835 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
837 bool isMem512() const {
838 return Kind == Memory && (!Mem.Size || Mem.Size == 512);
841 bool isMemVX32() const {
842 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
843 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
845 bool isMemVY32() const {
846 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
847 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
849 bool isMemVX64() const {
850 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
851 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
853 bool isMemVY64() const {
854 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
855 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
857 bool isMemVZ32() const {
858 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
859 getMemIndexReg() >= X86::ZMM0 && getMemIndexReg() <= X86::ZMM31;
861 bool isMemVZ64() const {
862 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
863 getMemIndexReg() >= X86::ZMM0 && getMemIndexReg() <= X86::ZMM31;
866 bool isAbsMem() const {
867 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
868 !getMemIndexReg() && getMemScale() == 1;
871 bool isMemOffs8() const {
872 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
873 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 8);
875 bool isMemOffs16() const {
876 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
877 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 16);
879 bool isMemOffs32() const {
880 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
881 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 32);
883 bool isMemOffs64() const {
884 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
885 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 64);
888 bool isReg() const { return Kind == Register; }
890 bool isGR32orGR64() const {
891 return Kind == Register &&
892 (X86MCRegisterClasses[X86::GR32RegClassID].contains(getReg()) ||
893 X86MCRegisterClasses[X86::GR64RegClassID].contains(getReg()));
896 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
897 // Add as immediates when possible.
898 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
899 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
901 Inst.addOperand(MCOperand::CreateExpr(Expr));
904 void addRegOperands(MCInst &Inst, unsigned N) const {
905 assert(N == 1 && "Invalid number of operands!");
906 Inst.addOperand(MCOperand::CreateReg(getReg()));
909 static unsigned getGR32FromGR64(unsigned RegNo) {
911 default: llvm_unreachable("Unexpected register");
912 case X86::RAX: return X86::EAX;
913 case X86::RCX: return X86::ECX;
914 case X86::RDX: return X86::EDX;
915 case X86::RBX: return X86::EBX;
916 case X86::RBP: return X86::EBP;
917 case X86::RSP: return X86::ESP;
918 case X86::RSI: return X86::ESI;
919 case X86::RDI: return X86::EDI;
920 case X86::R8: return X86::R8D;
921 case X86::R9: return X86::R9D;
922 case X86::R10: return X86::R10D;
923 case X86::R11: return X86::R11D;
924 case X86::R12: return X86::R12D;
925 case X86::R13: return X86::R13D;
926 case X86::R14: return X86::R14D;
927 case X86::R15: return X86::R15D;
928 case X86::RIP: return X86::EIP;
932 void addGR32orGR64Operands(MCInst &Inst, unsigned N) const {
933 assert(N == 1 && "Invalid number of operands!");
934 unsigned RegNo = getReg();
935 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo))
936 RegNo = getGR32FromGR64(RegNo);
937 Inst.addOperand(MCOperand::CreateReg(RegNo));
940 void addImmOperands(MCInst &Inst, unsigned N) const {
941 assert(N == 1 && "Invalid number of operands!");
942 addExpr(Inst, getImm());
945 void addMemOperands(MCInst &Inst, unsigned N) const {
946 assert((N == 5) && "Invalid number of operands!");
947 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
948 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
949 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
950 addExpr(Inst, getMemDisp());
951 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
954 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
955 assert((N == 1) && "Invalid number of operands!");
956 // Add as immediates when possible.
957 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
958 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
960 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
963 void addMemOffsOperands(MCInst &Inst, unsigned N) const {
964 assert((N == 1) && "Invalid number of operands!");
965 // Add as immediates when possible.
966 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
967 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
969 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
972 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
973 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size());
974 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
975 Res->Tok.Data = Str.data();
976 Res->Tok.Length = Str.size();
980 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
981 bool AddressOf = false,
982 SMLoc OffsetOfLoc = SMLoc(),
983 StringRef SymName = StringRef(),
985 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
986 Res->Reg.RegNo = RegNo;
987 Res->AddressOf = AddressOf;
988 Res->OffsetOfLoc = OffsetOfLoc;
989 Res->SymName = SymName;
990 Res->OpDecl = OpDecl;
994 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
995 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
1000 /// Create an absolute memory operand.
1001 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc,
1002 unsigned Size = 0, StringRef SymName = StringRef(),
1004 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
1005 Res->Mem.SegReg = 0;
1006 Res->Mem.Disp = Disp;
1007 Res->Mem.BaseReg = 0;
1008 Res->Mem.IndexReg = 0;
1010 Res->Mem.Size = Size;
1011 Res->SymName = SymName;
1012 Res->OpDecl = OpDecl;
1013 Res->AddressOf = false;
1017 /// Create a generalized memory operand.
1018 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
1019 unsigned BaseReg, unsigned IndexReg,
1020 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
1022 StringRef SymName = StringRef(),
1024 // We should never just have a displacement, that should be parsed as an
1025 // absolute memory operand.
1026 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
1028 // The scale should always be one of {1,2,4,8}.
1029 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
1031 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
1032 Res->Mem.SegReg = SegReg;
1033 Res->Mem.Disp = Disp;
1034 Res->Mem.BaseReg = BaseReg;
1035 Res->Mem.IndexReg = IndexReg;
1036 Res->Mem.Scale = Scale;
1037 Res->Mem.Size = Size;
1038 Res->SymName = SymName;
1039 Res->OpDecl = OpDecl;
1040 Res->AddressOf = false;
1045 } // end anonymous namespace.
1047 bool X86AsmParser::isSrcOp(X86Operand &Op) {
1049 is64BitMode() ? X86::RSI : (is32BitMode() ? X86::ESI : X86::SI);
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) {
1060 is64BitMode() ? X86::RDI : (is32BitMode() ? X86::EDI : X86::DI);
1062 return Op.isMem() &&
1063 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
1064 isa<MCConstantExpr>(Op.Mem.Disp) &&
1065 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1066 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
1069 bool X86AsmParser::ParseRegister(unsigned &RegNo,
1070 SMLoc &StartLoc, SMLoc &EndLoc) {
1072 const AsmToken &PercentTok = Parser.getTok();
1073 StartLoc = PercentTok.getLoc();
1075 // If we encounter a %, ignore it. This code handles registers with and
1076 // without the prefix, unprefixed registers can occur in cfi directives.
1077 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
1078 Parser.Lex(); // Eat percent token.
1080 const AsmToken &Tok = Parser.getTok();
1081 EndLoc = Tok.getEndLoc();
1083 if (Tok.isNot(AsmToken::Identifier)) {
1084 if (isParsingIntelSyntax()) return true;
1085 return Error(StartLoc, "invalid register name",
1086 SMRange(StartLoc, EndLoc));
1089 RegNo = MatchRegisterName(Tok.getString());
1091 // If the match failed, try the register name as lowercase.
1093 RegNo = MatchRegisterName(Tok.getString().lower());
1095 if (!is64BitMode()) {
1096 // FIXME: This should be done using Requires<Not64BitMode> and
1097 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
1099 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
1101 if (RegNo == X86::RIZ ||
1102 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
1103 X86II::isX86_64NonExtLowByteReg(RegNo) ||
1104 X86II::isX86_64ExtendedReg(RegNo))
1105 return Error(StartLoc, "register %"
1106 + Tok.getString() + " is only available in 64-bit mode",
1107 SMRange(StartLoc, EndLoc));
1110 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
1111 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
1113 Parser.Lex(); // Eat 'st'
1115 // Check to see if we have '(4)' after %st.
1116 if (getLexer().isNot(AsmToken::LParen))
1121 const AsmToken &IntTok = Parser.getTok();
1122 if (IntTok.isNot(AsmToken::Integer))
1123 return Error(IntTok.getLoc(), "expected stack index");
1124 switch (IntTok.getIntVal()) {
1125 case 0: RegNo = X86::ST0; break;
1126 case 1: RegNo = X86::ST1; break;
1127 case 2: RegNo = X86::ST2; break;
1128 case 3: RegNo = X86::ST3; break;
1129 case 4: RegNo = X86::ST4; break;
1130 case 5: RegNo = X86::ST5; break;
1131 case 6: RegNo = X86::ST6; break;
1132 case 7: RegNo = X86::ST7; break;
1133 default: return Error(IntTok.getLoc(), "invalid stack index");
1136 if (getParser().Lex().isNot(AsmToken::RParen))
1137 return Error(Parser.getTok().getLoc(), "expected ')'");
1139 EndLoc = Parser.getTok().getEndLoc();
1140 Parser.Lex(); // Eat ')'
1144 EndLoc = Parser.getTok().getEndLoc();
1146 // If this is "db[0-7]", match it as an alias
1148 if (RegNo == 0 && Tok.getString().size() == 3 &&
1149 Tok.getString().startswith("db")) {
1150 switch (Tok.getString()[2]) {
1151 case '0': RegNo = X86::DR0; break;
1152 case '1': RegNo = X86::DR1; break;
1153 case '2': RegNo = X86::DR2; break;
1154 case '3': RegNo = X86::DR3; break;
1155 case '4': RegNo = X86::DR4; break;
1156 case '5': RegNo = X86::DR5; break;
1157 case '6': RegNo = X86::DR6; break;
1158 case '7': RegNo = X86::DR7; break;
1162 EndLoc = Parser.getTok().getEndLoc();
1163 Parser.Lex(); // Eat it.
1169 if (isParsingIntelSyntax()) return true;
1170 return Error(StartLoc, "invalid register name",
1171 SMRange(StartLoc, EndLoc));
1174 Parser.Lex(); // Eat identifier token.
1178 X86Operand *X86AsmParser::ParseOperand() {
1179 if (isParsingIntelSyntax())
1180 return ParseIntelOperand();
1181 return ParseATTOperand();
1184 /// getIntelMemOperandSize - Return intel memory operand size.
1185 static unsigned getIntelMemOperandSize(StringRef OpStr) {
1186 unsigned Size = StringSwitch<unsigned>(OpStr)
1187 .Cases("BYTE", "byte", 8)
1188 .Cases("WORD", "word", 16)
1189 .Cases("DWORD", "dword", 32)
1190 .Cases("QWORD", "qword", 64)
1191 .Cases("XWORD", "xword", 80)
1192 .Cases("XMMWORD", "xmmword", 128)
1193 .Cases("YMMWORD", "ymmword", 256)
1199 X86AsmParser::CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
1200 unsigned BaseReg, unsigned IndexReg,
1201 unsigned Scale, SMLoc Start, SMLoc End,
1202 unsigned Size, StringRef Identifier,
1203 InlineAsmIdentifierInfo &Info){
1204 if (isa<MCSymbolRefExpr>(Disp)) {
1205 // If this is not a VarDecl then assume it is a FuncDecl or some other label
1206 // reference. We need an 'r' constraint here, so we need to create register
1207 // operand to ensure proper matching. Just pick a GPR based on the size of
1209 if (!Info.IsVarDecl) {
1211 is64BitMode() ? X86::RBX : (is32BitMode() ? X86::EBX : X86::BX);
1212 return X86Operand::CreateReg(RegNo, Start, End, /*AddressOf=*/true,
1213 SMLoc(), Identifier, Info.OpDecl);
1216 Size = Info.Type * 8; // Size is in terms of bits in this context.
1218 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_SizeDirective, Start,
1223 // When parsing inline assembly we set the base register to a non-zero value
1224 // if we don't know the actual value at this time. This is necessary to
1225 // get the matching correct in some cases.
1226 BaseReg = BaseReg ? BaseReg : 1;
1227 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1228 End, Size, Identifier, Info.OpDecl);
1232 RewriteIntelBracExpression(SmallVectorImpl<AsmRewrite> *AsmRewrites,
1233 StringRef SymName, int64_t ImmDisp,
1234 int64_t FinalImmDisp, SMLoc &BracLoc,
1235 SMLoc &StartInBrac, SMLoc &End) {
1236 // Remove the '[' and ']' from the IR string.
1237 AsmRewrites->push_back(AsmRewrite(AOK_Skip, BracLoc, 1));
1238 AsmRewrites->push_back(AsmRewrite(AOK_Skip, End, 1));
1240 // If ImmDisp is non-zero, then we parsed a displacement before the
1241 // bracketed expression (i.e., ImmDisp [ BaseReg + Scale*IndexReg + Disp])
1242 // If ImmDisp doesn't match the displacement computed by the state machine
1243 // then we have an additional displacement in the bracketed expression.
1244 if (ImmDisp != FinalImmDisp) {
1246 // We have an immediate displacement before the bracketed expression.
1247 // Adjust this to match the final immediate displacement.
1249 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1250 E = AsmRewrites->end(); I != E; ++I) {
1251 if ((*I).Loc.getPointer() > BracLoc.getPointer())
1253 if ((*I).Kind == AOK_ImmPrefix || (*I).Kind == AOK_Imm) {
1254 assert (!Found && "ImmDisp already rewritten.");
1255 (*I).Kind = AOK_Imm;
1256 (*I).Len = BracLoc.getPointer() - (*I).Loc.getPointer();
1257 (*I).Val = FinalImmDisp;
1262 assert (Found && "Unable to rewrite ImmDisp.");
1265 // We have a symbolic and an immediate displacement, but no displacement
1266 // before the bracketed expression. Put the immediate displacement
1267 // before the bracketed expression.
1268 AsmRewrites->push_back(AsmRewrite(AOK_Imm, BracLoc, 0, FinalImmDisp));
1271 // Remove all the ImmPrefix rewrites within the brackets.
1272 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1273 E = AsmRewrites->end(); I != E; ++I) {
1274 if ((*I).Loc.getPointer() < StartInBrac.getPointer())
1276 if ((*I).Kind == AOK_ImmPrefix)
1277 (*I).Kind = AOK_Delete;
1279 const char *SymLocPtr = SymName.data();
1280 // Skip everything before the symbol.
1281 if (unsigned Len = SymLocPtr - StartInBrac.getPointer()) {
1282 assert(Len > 0 && "Expected a non-negative length.");
1283 AsmRewrites->push_back(AsmRewrite(AOK_Skip, StartInBrac, Len));
1285 // Skip everything after the symbol.
1286 if (unsigned Len = End.getPointer() - (SymLocPtr + SymName.size())) {
1287 SMLoc Loc = SMLoc::getFromPointer(SymLocPtr + SymName.size());
1288 assert(Len > 0 && "Expected a non-negative length.");
1289 AsmRewrites->push_back(AsmRewrite(AOK_Skip, Loc, Len));
1293 bool X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) {
1294 const AsmToken &Tok = Parser.getTok();
1298 bool UpdateLocLex = true;
1300 // The period in the dot operator (e.g., [ebx].foo.bar) is parsed as an
1301 // identifier. Don't try an parse it as a register.
1302 if (Tok.getString().startswith("."))
1305 // If we're parsing an immediate expression, we don't expect a '['.
1306 if (SM.getStopOnLBrac() && getLexer().getKind() == AsmToken::LBrac)
1309 switch (getLexer().getKind()) {
1311 if (SM.isValidEndState()) {
1315 return Error(Tok.getLoc(), "unknown token in expression");
1317 case AsmToken::EndOfStatement: {
1321 case AsmToken::Identifier: {
1322 // This could be a register or a symbolic displacement.
1325 SMLoc IdentLoc = Tok.getLoc();
1326 StringRef Identifier = Tok.getString();
1327 if(!ParseRegister(TmpReg, IdentLoc, End)) {
1328 SM.onRegister(TmpReg);
1329 UpdateLocLex = false;
1332 if (!isParsingInlineAsm()) {
1333 if (getParser().parsePrimaryExpr(Val, End))
1334 return Error(Tok.getLoc(), "Unexpected identifier!");
1336 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1337 if (ParseIntelIdentifier(Val, Identifier, Info,
1338 /*Unevaluated=*/false, End))
1341 SM.onIdentifierExpr(Val, Identifier);
1342 UpdateLocLex = false;
1345 return Error(Tok.getLoc(), "Unexpected identifier!");
1347 case AsmToken::Integer: {
1348 if (isParsingInlineAsm() && SM.getAddImmPrefix())
1349 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1351 // Look for 'b' or 'f' following an Integer as a directional label
1352 SMLoc Loc = getTok().getLoc();
1353 int64_t IntVal = getTok().getIntVal();
1354 End = consumeToken();
1355 UpdateLocLex = false;
1356 if (getLexer().getKind() == AsmToken::Identifier) {
1357 StringRef IDVal = getTok().getString();
1358 if (IDVal == "f" || IDVal == "b") {
1360 getContext().GetDirectionalLocalSymbol(IntVal,
1361 IDVal == "f" ? 1 : 0);
1362 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1364 MCSymbolRefExpr::Create(Sym, Variant, getContext());
1365 if (IDVal == "b" && Sym->isUndefined())
1366 return Error(Loc, "invalid reference to undefined symbol");
1367 StringRef Identifier = Sym->getName();
1368 SM.onIdentifierExpr(Val, Identifier);
1369 End = consumeToken();
1371 SM.onInteger(IntVal);
1374 SM.onInteger(IntVal);
1378 case AsmToken::Plus: SM.onPlus(); break;
1379 case AsmToken::Minus: SM.onMinus(); break;
1380 case AsmToken::Star: SM.onStar(); break;
1381 case AsmToken::Slash: SM.onDivide(); break;
1382 case AsmToken::LBrac: SM.onLBrac(); break;
1383 case AsmToken::RBrac: SM.onRBrac(); break;
1384 case AsmToken::LParen: SM.onLParen(); break;
1385 case AsmToken::RParen: SM.onRParen(); break;
1388 return Error(Tok.getLoc(), "unknown token in expression");
1390 if (!Done && UpdateLocLex)
1391 End = consumeToken();
1396 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
1399 const AsmToken &Tok = Parser.getTok();
1400 SMLoc BracLoc = Tok.getLoc(), End = Tok.getEndLoc();
1401 if (getLexer().isNot(AsmToken::LBrac))
1402 return ErrorOperand(BracLoc, "Expected '[' token!");
1403 Parser.Lex(); // Eat '['
1405 SMLoc StartInBrac = Tok.getLoc();
1406 // Parse [ Symbol + ImmDisp ] and [ BaseReg + Scale*IndexReg + ImmDisp ]. We
1407 // may have already parsed an immediate displacement before the bracketed
1409 IntelExprStateMachine SM(ImmDisp, /*StopOnLBrac=*/false, /*AddImmPrefix=*/true);
1410 if (ParseIntelExpression(SM, End))
1414 if (const MCExpr *Sym = SM.getSym()) {
1415 // A symbolic displacement.
1417 if (isParsingInlineAsm())
1418 RewriteIntelBracExpression(InstInfo->AsmRewrites, SM.getSymName(),
1419 ImmDisp, SM.getImm(), BracLoc, StartInBrac,
1422 // An immediate displacement only.
1423 Disp = MCConstantExpr::Create(SM.getImm(), getContext());
1426 // Parse the dot operator (e.g., [ebx].foo.bar).
1427 if (Tok.getString().startswith(".")) {
1428 const MCExpr *NewDisp;
1429 if (ParseIntelDotOperator(Disp, NewDisp))
1432 End = Tok.getEndLoc();
1433 Parser.Lex(); // Eat the field.
1437 int BaseReg = SM.getBaseReg();
1438 int IndexReg = SM.getIndexReg();
1439 int Scale = SM.getScale();
1440 if (!isParsingInlineAsm()) {
1442 if (!BaseReg && !IndexReg) {
1444 return X86Operand::CreateMem(Disp, Start, End, Size);
1446 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, Start, End, Size);
1448 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1452 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1453 return CreateMemForInlineAsm(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1454 End, Size, SM.getSymName(), Info);
1457 // Inline assembly may use variable names with namespace alias qualifiers.
1458 bool X86AsmParser::ParseIntelIdentifier(const MCExpr *&Val,
1459 StringRef &Identifier,
1460 InlineAsmIdentifierInfo &Info,
1461 bool IsUnevaluatedOperand, SMLoc &End) {
1462 assert (isParsingInlineAsm() && "Expected to be parsing inline assembly.");
1465 StringRef LineBuf(Identifier.data());
1466 SemaCallback->LookupInlineAsmIdentifier(LineBuf, Info, IsUnevaluatedOperand);
1468 const AsmToken &Tok = Parser.getTok();
1470 // Advance the token stream until the end of the current token is
1471 // after the end of what the frontend claimed.
1472 const char *EndPtr = Tok.getLoc().getPointer() + LineBuf.size();
1474 End = Tok.getEndLoc();
1477 assert(End.getPointer() <= EndPtr && "frontend claimed part of a token?");
1478 if (End.getPointer() == EndPtr) break;
1481 // Create the symbol reference.
1482 Identifier = LineBuf;
1483 MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier);
1484 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1485 Val = MCSymbolRefExpr::Create(Sym, Variant, getParser().getContext());
1489 /// \brief Parse intel style segment override.
1490 X86Operand *X86AsmParser::ParseIntelSegmentOverride(unsigned SegReg,
1493 assert(SegReg != 0 && "Tried to parse a segment override without a segment!");
1494 const AsmToken &Tok = Parser.getTok(); // Eat colon.
1495 if (Tok.isNot(AsmToken::Colon))
1496 return ErrorOperand(Tok.getLoc(), "Expected ':' token!");
1497 Parser.Lex(); // Eat ':'
1499 int64_t ImmDisp = 0;
1500 if (getLexer().is(AsmToken::Integer)) {
1501 ImmDisp = Tok.getIntVal();
1502 AsmToken ImmDispToken = Parser.Lex(); // Eat the integer.
1504 if (isParsingInlineAsm())
1505 InstInfo->AsmRewrites->push_back(
1506 AsmRewrite(AOK_ImmPrefix, ImmDispToken.getLoc()));
1508 if (getLexer().isNot(AsmToken::LBrac)) {
1509 // An immediate following a 'segment register', 'colon' token sequence can
1510 // be followed by a bracketed expression. If it isn't we know we have our
1511 // final segment override.
1512 const MCExpr *Disp = MCConstantExpr::Create(ImmDisp, getContext());
1513 return X86Operand::CreateMem(SegReg, Disp, /*BaseReg=*/0, /*IndexReg=*/0,
1514 /*Scale=*/1, Start, ImmDispToken.getEndLoc(),
1519 if (getLexer().is(AsmToken::LBrac))
1520 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1524 if (!isParsingInlineAsm()) {
1525 if (getParser().parsePrimaryExpr(Val, End))
1526 return ErrorOperand(Tok.getLoc(), "unknown token in expression");
1528 return X86Operand::CreateMem(Val, Start, End, Size);
1531 InlineAsmIdentifierInfo Info;
1532 StringRef Identifier = Tok.getString();
1533 if (ParseIntelIdentifier(Val, Identifier, Info,
1534 /*Unevaluated=*/false, End))
1536 return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0,/*IndexReg=*/0,
1537 /*Scale=*/1, Start, End, Size, Identifier, Info);
1540 /// ParseIntelMemOperand - Parse intel style memory operand.
1541 X86Operand *X86AsmParser::ParseIntelMemOperand(int64_t ImmDisp, SMLoc Start,
1543 const AsmToken &Tok = Parser.getTok();
1546 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1547 if (getLexer().is(AsmToken::LBrac))
1548 return ParseIntelBracExpression(/*SegReg=*/0, Start, ImmDisp, Size);
1551 if (!isParsingInlineAsm()) {
1552 if (getParser().parsePrimaryExpr(Val, End))
1553 return ErrorOperand(Tok.getLoc(), "unknown token in expression");
1555 return X86Operand::CreateMem(Val, Start, End, Size);
1558 InlineAsmIdentifierInfo Info;
1559 StringRef Identifier = Tok.getString();
1560 if (ParseIntelIdentifier(Val, Identifier, Info,
1561 /*Unevaluated=*/false, End))
1563 return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0, /*IndexReg=*/0,
1564 /*Scale=*/1, Start, End, Size, Identifier, Info);
1567 /// Parse the '.' operator.
1568 bool X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp,
1569 const MCExpr *&NewDisp) {
1570 const AsmToken &Tok = Parser.getTok();
1571 int64_t OrigDispVal, DotDispVal;
1573 // FIXME: Handle non-constant expressions.
1574 if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp))
1575 OrigDispVal = OrigDisp->getValue();
1577 return Error(Tok.getLoc(), "Non-constant offsets are not supported!");
1580 StringRef DotDispStr = Tok.getString().drop_front(1);
1582 // .Imm gets lexed as a real.
1583 if (Tok.is(AsmToken::Real)) {
1585 DotDispStr.getAsInteger(10, DotDisp);
1586 DotDispVal = DotDisp.getZExtValue();
1587 } else if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1589 std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
1590 if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second,
1592 return Error(Tok.getLoc(), "Unable to lookup field reference!");
1593 DotDispVal = DotDisp;
1595 return Error(Tok.getLoc(), "Unexpected token type!");
1597 if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1598 SMLoc Loc = SMLoc::getFromPointer(DotDispStr.data());
1599 unsigned Len = DotDispStr.size();
1600 unsigned Val = OrigDispVal + DotDispVal;
1601 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_DotOperator, Loc, Len,
1605 NewDisp = MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext());
1609 /// Parse the 'offset' operator. This operator is used to specify the
1610 /// location rather then the content of a variable.
1611 X86Operand *X86AsmParser::ParseIntelOffsetOfOperator() {
1612 const AsmToken &Tok = Parser.getTok();
1613 SMLoc OffsetOfLoc = Tok.getLoc();
1614 Parser.Lex(); // Eat offset.
1617 InlineAsmIdentifierInfo Info;
1618 SMLoc Start = Tok.getLoc(), End;
1619 StringRef Identifier = Tok.getString();
1620 if (ParseIntelIdentifier(Val, Identifier, Info,
1621 /*Unevaluated=*/false, End))
1624 // Don't emit the offset operator.
1625 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Skip, OffsetOfLoc, 7));
1627 // The offset operator will have an 'r' constraint, thus we need to create
1628 // register operand to ensure proper matching. Just pick a GPR based on
1629 // the size of a pointer.
1631 is64BitMode() ? X86::RBX : (is32BitMode() ? X86::EBX : X86::BX);
1632 return X86Operand::CreateReg(RegNo, Start, End, /*GetAddress=*/true,
1633 OffsetOfLoc, Identifier, Info.OpDecl);
1636 enum IntelOperatorKind {
1642 /// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators. The LENGTH operator
1643 /// returns the number of elements in an array. It returns the value 1 for
1644 /// non-array variables. The SIZE operator returns the size of a C or C++
1645 /// variable. A variable's size is the product of its LENGTH and TYPE. The
1646 /// TYPE operator returns the size of a C or C++ type or variable. If the
1647 /// variable is an array, TYPE returns the size of a single element.
1648 X86Operand *X86AsmParser::ParseIntelOperator(unsigned OpKind) {
1649 const AsmToken &Tok = Parser.getTok();
1650 SMLoc TypeLoc = Tok.getLoc();
1651 Parser.Lex(); // Eat operator.
1653 const MCExpr *Val = 0;
1654 InlineAsmIdentifierInfo Info;
1655 SMLoc Start = Tok.getLoc(), End;
1656 StringRef Identifier = Tok.getString();
1657 if (ParseIntelIdentifier(Val, Identifier, Info,
1658 /*Unevaluated=*/true, End))
1662 return ErrorOperand(Start, "unable to lookup expression");
1666 default: llvm_unreachable("Unexpected operand kind!");
1667 case IOK_LENGTH: CVal = Info.Length; break;
1668 case IOK_SIZE: CVal = Info.Size; break;
1669 case IOK_TYPE: CVal = Info.Type; break;
1672 // Rewrite the type operator and the C or C++ type or variable in terms of an
1673 // immediate. E.g. TYPE foo -> $$4
1674 unsigned Len = End.getPointer() - TypeLoc.getPointer();
1675 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, TypeLoc, Len, CVal));
1677 const MCExpr *Imm = MCConstantExpr::Create(CVal, getContext());
1678 return X86Operand::CreateImm(Imm, Start, End);
1681 X86Operand *X86AsmParser::ParseIntelOperand() {
1682 const AsmToken &Tok = Parser.getTok();
1685 // Offset, length, type and size operators.
1686 if (isParsingInlineAsm()) {
1687 StringRef AsmTokStr = Tok.getString();
1688 if (AsmTokStr == "offset" || AsmTokStr == "OFFSET")
1689 return ParseIntelOffsetOfOperator();
1690 if (AsmTokStr == "length" || AsmTokStr == "LENGTH")
1691 return ParseIntelOperator(IOK_LENGTH);
1692 if (AsmTokStr == "size" || AsmTokStr == "SIZE")
1693 return ParseIntelOperator(IOK_SIZE);
1694 if (AsmTokStr == "type" || AsmTokStr == "TYPE")
1695 return ParseIntelOperator(IOK_TYPE);
1698 unsigned Size = getIntelMemOperandSize(Tok.getString());
1700 Parser.Lex(); // Eat operand size (e.g., byte, word).
1701 if (Tok.getString() != "PTR" && Tok.getString() != "ptr")
1702 return ErrorOperand(Start, "Expected 'PTR' or 'ptr' token!");
1703 Parser.Lex(); // Eat ptr.
1705 Start = Tok.getLoc();
1708 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Minus) ||
1709 getLexer().is(AsmToken::LParen)) {
1710 AsmToken StartTok = Tok;
1711 IntelExprStateMachine SM(/*Imm=*/0, /*StopOnLBrac=*/true,
1712 /*AddImmPrefix=*/false);
1713 if (ParseIntelExpression(SM, End))
1716 int64_t Imm = SM.getImm();
1717 if (isParsingInlineAsm()) {
1718 unsigned Len = Tok.getLoc().getPointer() - Start.getPointer();
1719 if (StartTok.getString().size() == Len)
1720 // Just add a prefix if this wasn't a complex immediate expression.
1721 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix, Start));
1723 // Otherwise, rewrite the complex expression as a single immediate.
1724 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, Start, Len, Imm));
1727 if (getLexer().isNot(AsmToken::LBrac)) {
1728 // If a directional label (ie. 1f or 2b) was parsed above from
1729 // ParseIntelExpression() then SM.getSym() was set to a pointer to
1730 // to the MCExpr with the directional local symbol and this is a
1731 // memory operand not an immediate operand.
1733 return X86Operand::CreateMem(SM.getSym(), Start, End, Size);
1735 const MCExpr *ImmExpr = MCConstantExpr::Create(Imm, getContext());
1736 return X86Operand::CreateImm(ImmExpr, Start, End);
1739 // Only positive immediates are valid.
1741 return ErrorOperand(Start, "expected a positive immediate displacement "
1742 "before bracketed expr.");
1744 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1745 return ParseIntelMemOperand(Imm, Start, Size);
1750 if (!ParseRegister(RegNo, Start, End)) {
1751 // If this is a segment register followed by a ':', then this is the start
1752 // of a segment override, otherwise this is a normal register reference.
1753 if (getLexer().isNot(AsmToken::Colon))
1754 return X86Operand::CreateReg(RegNo, Start, End);
1756 return ParseIntelSegmentOverride(/*SegReg=*/RegNo, Start, Size);
1760 return ParseIntelMemOperand(/*Disp=*/0, Start, Size);
1763 X86Operand *X86AsmParser::ParseATTOperand() {
1764 switch (getLexer().getKind()) {
1766 // Parse a memory operand with no segment register.
1767 return ParseMemOperand(0, Parser.getTok().getLoc());
1768 case AsmToken::Percent: {
1769 // Read the register.
1772 if (ParseRegister(RegNo, Start, End)) return 0;
1773 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
1774 Error(Start, "%eiz and %riz can only be used as index registers",
1775 SMRange(Start, End));
1779 // If this is a segment register followed by a ':', then this is the start
1780 // of a memory reference, otherwise this is a normal register reference.
1781 if (getLexer().isNot(AsmToken::Colon))
1782 return X86Operand::CreateReg(RegNo, Start, End);
1784 getParser().Lex(); // Eat the colon.
1785 return ParseMemOperand(RegNo, Start);
1787 case AsmToken::Dollar: {
1788 // $42 -> immediate.
1789 SMLoc Start = Parser.getTok().getLoc(), End;
1792 if (getParser().parseExpression(Val, End))
1794 return X86Operand::CreateImm(Val, Start, End);
1799 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
1800 /// has already been parsed if present.
1801 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
1803 // We have to disambiguate a parenthesized expression "(4+5)" from the start
1804 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
1805 // only way to do this without lookahead is to eat the '(' and see what is
1807 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
1808 if (getLexer().isNot(AsmToken::LParen)) {
1810 if (getParser().parseExpression(Disp, ExprEnd)) return 0;
1812 // After parsing the base expression we could either have a parenthesized
1813 // memory address or not. If not, return now. If so, eat the (.
1814 if (getLexer().isNot(AsmToken::LParen)) {
1815 // Unless we have a segment register, treat this as an immediate.
1817 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
1818 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1824 // Okay, we have a '('. We don't know if this is an expression or not, but
1825 // so we have to eat the ( to see beyond it.
1826 SMLoc LParenLoc = Parser.getTok().getLoc();
1827 Parser.Lex(); // Eat the '('.
1829 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
1830 // Nothing to do here, fall into the code below with the '(' part of the
1831 // memory operand consumed.
1835 // It must be an parenthesized expression, parse it now.
1836 if (getParser().parseParenExpression(Disp, ExprEnd))
1839 // After parsing the base expression we could either have a parenthesized
1840 // memory address or not. If not, return now. If so, eat the (.
1841 if (getLexer().isNot(AsmToken::LParen)) {
1842 // Unless we have a segment register, treat this as an immediate.
1844 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
1845 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1853 // If we reached here, then we just ate the ( of the memory operand. Process
1854 // the rest of the memory operand.
1855 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
1858 if (getLexer().is(AsmToken::Percent)) {
1859 SMLoc StartLoc, EndLoc;
1860 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
1861 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
1862 Error(StartLoc, "eiz and riz can only be used as index registers",
1863 SMRange(StartLoc, EndLoc));
1868 if (getLexer().is(AsmToken::Comma)) {
1869 Parser.Lex(); // Eat the comma.
1870 IndexLoc = Parser.getTok().getLoc();
1872 // Following the comma we should have either an index register, or a scale
1873 // value. We don't support the later form, but we want to parse it
1876 // Not that even though it would be completely consistent to support syntax
1877 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
1878 if (getLexer().is(AsmToken::Percent)) {
1880 if (ParseRegister(IndexReg, L, L)) return 0;
1882 if (getLexer().isNot(AsmToken::RParen)) {
1883 // Parse the scale amount:
1884 // ::= ',' [scale-expression]
1885 if (getLexer().isNot(AsmToken::Comma)) {
1886 Error(Parser.getTok().getLoc(),
1887 "expected comma in scale expression");
1890 Parser.Lex(); // Eat the comma.
1892 if (getLexer().isNot(AsmToken::RParen)) {
1893 SMLoc Loc = Parser.getTok().getLoc();
1896 if (getParser().parseAbsoluteExpression(ScaleVal)){
1897 Error(Loc, "expected scale expression");
1901 // Validate the scale amount.
1902 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
1903 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
1906 Scale = (unsigned)ScaleVal;
1909 } else if (getLexer().isNot(AsmToken::RParen)) {
1910 // A scale amount without an index is ignored.
1912 SMLoc Loc = Parser.getTok().getLoc();
1915 if (getParser().parseAbsoluteExpression(Value))
1919 Warning(Loc, "scale factor without index register is ignored");
1924 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1925 if (getLexer().isNot(AsmToken::RParen)) {
1926 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1929 SMLoc MemEnd = Parser.getTok().getEndLoc();
1930 Parser.Lex(); // Eat the ')'.
1932 // If we have both a base register and an index register make sure they are
1933 // both 64-bit or 32-bit registers.
1934 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1935 if (BaseReg != 0 && IndexReg != 0) {
1936 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1937 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1938 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1939 IndexReg != X86::RIZ) {
1940 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1943 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1944 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1945 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1946 IndexReg != X86::EIZ){
1947 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1952 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1957 ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
1958 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1960 StringRef PatchedName = Name;
1962 // FIXME: Hack to recognize setneb as setne.
1963 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1964 PatchedName != "setb" && PatchedName != "setnb")
1965 PatchedName = PatchedName.substr(0, Name.size()-1);
1967 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1968 const MCExpr *ExtraImmOp = 0;
1969 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1970 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1971 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1972 bool IsVCMP = PatchedName[0] == 'v';
1973 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1974 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1975 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1979 .Case("unord", 0x03)
1984 /* AVX only from here */
1985 .Case("eq_uq", 0x08)
1988 .Case("false", 0x0B)
1989 .Case("neq_oq", 0x0C)
1993 .Case("eq_os", 0x10)
1994 .Case("lt_oq", 0x11)
1995 .Case("le_oq", 0x12)
1996 .Case("unord_s", 0x13)
1997 .Case("neq_us", 0x14)
1998 .Case("nlt_uq", 0x15)
1999 .Case("nle_uq", 0x16)
2000 .Case("ord_s", 0x17)
2001 .Case("eq_us", 0x18)
2002 .Case("nge_uq", 0x19)
2003 .Case("ngt_uq", 0x1A)
2004 .Case("false_os", 0x1B)
2005 .Case("neq_os", 0x1C)
2006 .Case("ge_oq", 0x1D)
2007 .Case("gt_oq", 0x1E)
2008 .Case("true_us", 0x1F)
2010 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
2011 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
2012 getParser().getContext());
2013 if (PatchedName.endswith("ss")) {
2014 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
2015 } else if (PatchedName.endswith("sd")) {
2016 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
2017 } else if (PatchedName.endswith("ps")) {
2018 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
2020 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
2021 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
2026 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
2028 if (ExtraImmOp && !isParsingIntelSyntax())
2029 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
2031 // Determine whether this is an instruction prefix.
2033 Name == "lock" || Name == "rep" ||
2034 Name == "repe" || Name == "repz" ||
2035 Name == "repne" || Name == "repnz" ||
2036 Name == "rex64" || Name == "data16";
2039 // This does the actual operand parsing. Don't parse any more if we have a
2040 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
2041 // just want to parse the "lock" as the first instruction and the "incl" as
2043 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
2045 // Parse '*' modifier.
2046 if (getLexer().is(AsmToken::Star))
2047 Operands.push_back(X86Operand::CreateToken("*", consumeToken()));
2049 // Read the first operand.
2050 if (X86Operand *Op = ParseOperand())
2051 Operands.push_back(Op);
2053 Parser.eatToEndOfStatement();
2057 while (getLexer().is(AsmToken::Comma)) {
2058 Parser.Lex(); // Eat the comma.
2060 // Parse and remember the operand.
2061 if (X86Operand *Op = ParseOperand())
2062 Operands.push_back(Op);
2064 Parser.eatToEndOfStatement();
2069 if (STI.getFeatureBits() & X86::FeatureAVX512) {
2070 // Parse mask register {%k1}
2071 if (getLexer().is(AsmToken::LCurly)) {
2072 Operands.push_back(X86Operand::CreateToken("{", consumeToken()));
2073 if (X86Operand *Op = ParseOperand()) {
2074 Operands.push_back(Op);
2075 if (!getLexer().is(AsmToken::RCurly)) {
2076 SMLoc Loc = getLexer().getLoc();
2077 Parser.eatToEndOfStatement();
2078 return Error(Loc, "Expected } at this point");
2080 Operands.push_back(X86Operand::CreateToken("}", consumeToken()));
2082 Parser.eatToEndOfStatement();
2086 // TODO: add parsing of broadcasts {1to8}, {1to16}
2087 // Parse "zeroing non-masked" semantic {z}
2088 if (getLexer().is(AsmToken::LCurly)) {
2089 Operands.push_back(X86Operand::CreateToken("{z}", consumeToken()));
2090 if (!getLexer().is(AsmToken::Identifier) || getLexer().getTok().getIdentifier() != "z") {
2091 SMLoc Loc = getLexer().getLoc();
2092 Parser.eatToEndOfStatement();
2093 return Error(Loc, "Expected z at this point");
2095 Parser.Lex(); // Eat the z
2096 if (!getLexer().is(AsmToken::RCurly)) {
2097 SMLoc Loc = getLexer().getLoc();
2098 Parser.eatToEndOfStatement();
2099 return Error(Loc, "Expected } at this point");
2101 Parser.Lex(); // Eat the }
2105 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2106 SMLoc Loc = getLexer().getLoc();
2107 Parser.eatToEndOfStatement();
2108 return Error(Loc, "unexpected token in argument list");
2112 if (getLexer().is(AsmToken::EndOfStatement))
2113 Parser.Lex(); // Consume the EndOfStatement
2114 else if (isPrefix && getLexer().is(AsmToken::Slash))
2115 Parser.Lex(); // Consume the prefix separator Slash
2117 if (ExtraImmOp && isParsingIntelSyntax())
2118 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
2120 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
2121 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
2122 // documented form in various unofficial manuals, so a lot of code uses it.
2123 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
2124 Operands.size() == 3) {
2125 X86Operand &Op = *(X86Operand*)Operands.back();
2126 if (Op.isMem() && Op.Mem.SegReg == 0 &&
2127 isa<MCConstantExpr>(Op.Mem.Disp) &&
2128 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2129 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2130 SMLoc Loc = Op.getEndLoc();
2131 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
2135 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
2136 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
2137 Operands.size() == 3) {
2138 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2139 if (Op.isMem() && Op.Mem.SegReg == 0 &&
2140 isa<MCConstantExpr>(Op.Mem.Disp) &&
2141 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2142 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2143 SMLoc Loc = Op.getEndLoc();
2144 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
2148 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
2149 if (Name.startswith("ins") && Operands.size() == 3 &&
2150 (Name == "insb" || Name == "insw" || Name == "insl")) {
2151 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2152 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2153 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
2154 Operands.pop_back();
2155 Operands.pop_back();
2161 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
2162 if (Name.startswith("outs") && Operands.size() == 3 &&
2163 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
2164 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2165 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2166 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
2167 Operands.pop_back();
2168 Operands.pop_back();
2174 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
2175 if (Name.startswith("movs") && Operands.size() == 3 &&
2176 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
2177 (is64BitMode() && Name == "movsq"))) {
2178 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2179 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2180 if (isSrcOp(Op) && isDstOp(Op2)) {
2181 Operands.pop_back();
2182 Operands.pop_back();
2187 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
2188 if (Name.startswith("lods") && Operands.size() == 3 &&
2189 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
2190 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
2191 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2192 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2193 if (isSrcOp(*Op1) && Op2->isReg()) {
2195 unsigned reg = Op2->getReg();
2196 bool isLods = Name == "lods";
2197 if (reg == X86::AL && (isLods || Name == "lodsb"))
2199 else if (reg == X86::AX && (isLods || Name == "lodsw"))
2201 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
2203 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
2208 Operands.pop_back();
2209 Operands.pop_back();
2213 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2217 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
2218 if (Name.startswith("stos") && Operands.size() == 3 &&
2219 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
2220 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
2221 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2222 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2223 if (isDstOp(*Op2) && Op1->isReg()) {
2225 unsigned reg = Op1->getReg();
2226 bool isStos = Name == "stos";
2227 if (reg == X86::AL && (isStos || Name == "stosb"))
2229 else if (reg == X86::AX && (isStos || Name == "stosw"))
2231 else if (reg == X86::EAX && (isStos || Name == "stosl"))
2233 else if (reg == X86::RAX && (isStos || Name == "stosq"))
2238 Operands.pop_back();
2239 Operands.pop_back();
2243 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2248 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
2250 if ((Name.startswith("shr") || Name.startswith("sar") ||
2251 Name.startswith("shl") || Name.startswith("sal") ||
2252 Name.startswith("rcl") || Name.startswith("rcr") ||
2253 Name.startswith("rol") || Name.startswith("ror")) &&
2254 Operands.size() == 3) {
2255 if (isParsingIntelSyntax()) {
2257 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
2258 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2259 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2261 Operands.pop_back();
2264 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2265 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2266 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2268 Operands.erase(Operands.begin() + 1);
2273 // Transforms "int $3" into "int3" as a size optimization. We can't write an
2274 // instalias with an immediate operand yet.
2275 if (Name == "int" && Operands.size() == 2) {
2276 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2277 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2278 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
2280 Operands.erase(Operands.begin() + 1);
2281 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
2288 static bool convertToSExti8(MCInst &Inst, unsigned Opcode, unsigned Reg,
2291 TmpInst.setOpcode(Opcode);
2293 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2294 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2295 TmpInst.addOperand(Inst.getOperand(0));
2300 static bool convert16i16to16ri8(MCInst &Inst, unsigned Opcode,
2301 bool isCmp = false) {
2302 if (!Inst.getOperand(0).isImm() ||
2303 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
2306 return convertToSExti8(Inst, Opcode, X86::AX, isCmp);
2309 static bool convert32i32to32ri8(MCInst &Inst, unsigned Opcode,
2310 bool isCmp = false) {
2311 if (!Inst.getOperand(0).isImm() ||
2312 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
2315 return convertToSExti8(Inst, Opcode, X86::EAX, isCmp);
2318 static bool convert64i32to64ri8(MCInst &Inst, unsigned Opcode,
2319 bool isCmp = false) {
2320 if (!Inst.getOperand(0).isImm() ||
2321 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
2324 return convertToSExti8(Inst, Opcode, X86::RAX, isCmp);
2328 processInstruction(MCInst &Inst,
2329 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
2330 switch (Inst.getOpcode()) {
2331 default: return false;
2332 case X86::AND16i16: return convert16i16to16ri8(Inst, X86::AND16ri8);
2333 case X86::AND32i32: return convert32i32to32ri8(Inst, X86::AND32ri8);
2334 case X86::AND64i32: return convert64i32to64ri8(Inst, X86::AND64ri8);
2335 case X86::XOR16i16: return convert16i16to16ri8(Inst, X86::XOR16ri8);
2336 case X86::XOR32i32: return convert32i32to32ri8(Inst, X86::XOR32ri8);
2337 case X86::XOR64i32: return convert64i32to64ri8(Inst, X86::XOR64ri8);
2338 case X86::OR16i16: return convert16i16to16ri8(Inst, X86::OR16ri8);
2339 case X86::OR32i32: return convert32i32to32ri8(Inst, X86::OR32ri8);
2340 case X86::OR64i32: return convert64i32to64ri8(Inst, X86::OR64ri8);
2341 case X86::CMP16i16: return convert16i16to16ri8(Inst, X86::CMP16ri8, true);
2342 case X86::CMP32i32: return convert32i32to32ri8(Inst, X86::CMP32ri8, true);
2343 case X86::CMP64i32: return convert64i32to64ri8(Inst, X86::CMP64ri8, true);
2344 case X86::ADD16i16: return convert16i16to16ri8(Inst, X86::ADD16ri8);
2345 case X86::ADD32i32: return convert32i32to32ri8(Inst, X86::ADD32ri8);
2346 case X86::ADD64i32: return convert64i32to64ri8(Inst, X86::ADD64ri8);
2347 case X86::SUB16i16: return convert16i16to16ri8(Inst, X86::SUB16ri8);
2348 case X86::SUB32i32: return convert32i32to32ri8(Inst, X86::SUB32ri8);
2349 case X86::SUB64i32: return convert64i32to64ri8(Inst, X86::SUB64ri8);
2350 case X86::ADC16i16: return convert16i16to16ri8(Inst, X86::ADC16ri8);
2351 case X86::ADC32i32: return convert32i32to32ri8(Inst, X86::ADC32ri8);
2352 case X86::ADC64i32: return convert64i32to64ri8(Inst, X86::ADC64ri8);
2353 case X86::SBB16i16: return convert16i16to16ri8(Inst, X86::SBB16ri8);
2354 case X86::SBB32i32: return convert32i32to32ri8(Inst, X86::SBB32ri8);
2355 case X86::SBB64i32: return convert64i32to64ri8(Inst, X86::SBB64ri8);
2356 case X86::VMOVAPDrr:
2357 case X86::VMOVAPDYrr:
2358 case X86::VMOVAPSrr:
2359 case X86::VMOVAPSYrr:
2360 case X86::VMOVDQArr:
2361 case X86::VMOVDQAYrr:
2362 case X86::VMOVDQUrr:
2363 case X86::VMOVDQUYrr:
2364 case X86::VMOVUPDrr:
2365 case X86::VMOVUPDYrr:
2366 case X86::VMOVUPSrr:
2367 case X86::VMOVUPSYrr: {
2368 if (X86II::isX86_64ExtendedReg(Inst.getOperand(0).getReg()) ||
2369 !X86II::isX86_64ExtendedReg(Inst.getOperand(1).getReg()))
2373 switch (Inst.getOpcode()) {
2374 default: llvm_unreachable("Invalid opcode");
2375 case X86::VMOVAPDrr: NewOpc = X86::VMOVAPDrr_REV; break;
2376 case X86::VMOVAPDYrr: NewOpc = X86::VMOVAPDYrr_REV; break;
2377 case X86::VMOVAPSrr: NewOpc = X86::VMOVAPSrr_REV; break;
2378 case X86::VMOVAPSYrr: NewOpc = X86::VMOVAPSYrr_REV; break;
2379 case X86::VMOVDQArr: NewOpc = X86::VMOVDQArr_REV; break;
2380 case X86::VMOVDQAYrr: NewOpc = X86::VMOVDQAYrr_REV; break;
2381 case X86::VMOVDQUrr: NewOpc = X86::VMOVDQUrr_REV; break;
2382 case X86::VMOVDQUYrr: NewOpc = X86::VMOVDQUYrr_REV; break;
2383 case X86::VMOVUPDrr: NewOpc = X86::VMOVUPDrr_REV; break;
2384 case X86::VMOVUPDYrr: NewOpc = X86::VMOVUPDYrr_REV; break;
2385 case X86::VMOVUPSrr: NewOpc = X86::VMOVUPSrr_REV; break;
2386 case X86::VMOVUPSYrr: NewOpc = X86::VMOVUPSYrr_REV; break;
2388 Inst.setOpcode(NewOpc);
2392 case X86::VMOVSSrr: {
2393 if (X86II::isX86_64ExtendedReg(Inst.getOperand(0).getReg()) ||
2394 !X86II::isX86_64ExtendedReg(Inst.getOperand(2).getReg()))
2397 switch (Inst.getOpcode()) {
2398 default: llvm_unreachable("Invalid opcode");
2399 case X86::VMOVSDrr: NewOpc = X86::VMOVSDrr_REV; break;
2400 case X86::VMOVSSrr: NewOpc = X86::VMOVSSrr_REV; break;
2402 Inst.setOpcode(NewOpc);
2408 static const char *getSubtargetFeatureName(unsigned Val);
2410 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2411 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2412 MCStreamer &Out, unsigned &ErrorInfo,
2413 bool MatchingInlineAsm) {
2414 assert(!Operands.empty() && "Unexpect empty operand list!");
2415 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
2416 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
2417 ArrayRef<SMRange> EmptyRanges = None;
2419 // First, handle aliases that expand to multiple instructions.
2420 // FIXME: This should be replaced with a real .td file alias mechanism.
2421 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
2423 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
2424 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
2425 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
2426 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
2428 Inst.setOpcode(X86::WAIT);
2430 if (!MatchingInlineAsm)
2431 Out.EmitInstruction(Inst);
2434 StringSwitch<const char*>(Op->getToken())
2435 .Case("finit", "fninit")
2436 .Case("fsave", "fnsave")
2437 .Case("fstcw", "fnstcw")
2438 .Case("fstcww", "fnstcw")
2439 .Case("fstenv", "fnstenv")
2440 .Case("fstsw", "fnstsw")
2441 .Case("fstsww", "fnstsw")
2442 .Case("fclex", "fnclex")
2444 assert(Repl && "Unknown wait-prefixed instruction");
2446 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
2449 bool WasOriginallyInvalidOperand = false;
2452 // First, try a direct match.
2453 switch (MatchInstructionImpl(Operands, Inst,
2454 ErrorInfo, MatchingInlineAsm,
2455 isParsingIntelSyntax())) {
2458 // Some instructions need post-processing to, for example, tweak which
2459 // encoding is selected. Loop on it while changes happen so the
2460 // individual transformations can chain off each other.
2461 if (!MatchingInlineAsm)
2462 while (processInstruction(Inst, Operands))
2466 if (!MatchingInlineAsm)
2467 Out.EmitInstruction(Inst);
2468 Opcode = Inst.getOpcode();
2470 case Match_MissingFeature: {
2471 assert(ErrorInfo && "Unknown missing feature!");
2472 // Special case the error message for the very common case where only
2473 // a single subtarget feature is missing.
2474 std::string Msg = "instruction requires:";
2476 for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
2477 if (ErrorInfo & Mask) {
2479 Msg += getSubtargetFeatureName(ErrorInfo & Mask);
2483 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2485 case Match_InvalidOperand:
2486 WasOriginallyInvalidOperand = true;
2488 case Match_MnemonicFail:
2492 // FIXME: Ideally, we would only attempt suffix matches for things which are
2493 // valid prefixes, and we could just infer the right unambiguous
2494 // type. However, that requires substantially more matcher support than the
2497 // Change the operand to point to a temporary token.
2498 StringRef Base = Op->getToken();
2499 SmallString<16> Tmp;
2502 Op->setTokenValue(Tmp.str());
2504 // If this instruction starts with an 'f', then it is a floating point stack
2505 // instruction. These come in up to three forms for 32-bit, 64-bit, and
2506 // 80-bit floating point, which use the suffixes s,l,t respectively.
2508 // Otherwise, we assume that this may be an integer instruction, which comes
2509 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
2510 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
2512 // Check for the various suffix matches.
2513 Tmp[Base.size()] = Suffixes[0];
2514 unsigned ErrorInfoIgnore;
2515 unsigned ErrorInfoMissingFeature = 0; // Init suppresses compiler warnings.
2516 unsigned Match1, Match2, Match3, Match4;
2518 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2519 MatchingInlineAsm, isParsingIntelSyntax());
2520 // If this returned as a missing feature failure, remember that.
2521 if (Match1 == Match_MissingFeature)
2522 ErrorInfoMissingFeature = ErrorInfoIgnore;
2523 Tmp[Base.size()] = Suffixes[1];
2524 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2525 MatchingInlineAsm, isParsingIntelSyntax());
2526 // If this returned as a missing feature failure, remember that.
2527 if (Match2 == Match_MissingFeature)
2528 ErrorInfoMissingFeature = ErrorInfoIgnore;
2529 Tmp[Base.size()] = Suffixes[2];
2530 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2531 MatchingInlineAsm, isParsingIntelSyntax());
2532 // If this returned as a missing feature failure, remember that.
2533 if (Match3 == Match_MissingFeature)
2534 ErrorInfoMissingFeature = ErrorInfoIgnore;
2535 Tmp[Base.size()] = Suffixes[3];
2536 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2537 MatchingInlineAsm, isParsingIntelSyntax());
2538 // If this returned as a missing feature failure, remember that.
2539 if (Match4 == Match_MissingFeature)
2540 ErrorInfoMissingFeature = ErrorInfoIgnore;
2542 // Restore the old token.
2543 Op->setTokenValue(Base);
2545 // If exactly one matched, then we treat that as a successful match (and the
2546 // instruction will already have been filled in correctly, since the failing
2547 // matches won't have modified it).
2548 unsigned NumSuccessfulMatches =
2549 (Match1 == Match_Success) + (Match2 == Match_Success) +
2550 (Match3 == Match_Success) + (Match4 == Match_Success);
2551 if (NumSuccessfulMatches == 1) {
2553 if (!MatchingInlineAsm)
2554 Out.EmitInstruction(Inst);
2555 Opcode = Inst.getOpcode();
2559 // Otherwise, the match failed, try to produce a decent error message.
2561 // If we had multiple suffix matches, then identify this as an ambiguous
2563 if (NumSuccessfulMatches > 1) {
2565 unsigned NumMatches = 0;
2566 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
2567 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
2568 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
2569 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
2571 SmallString<126> Msg;
2572 raw_svector_ostream OS(Msg);
2573 OS << "ambiguous instructions require an explicit suffix (could be ";
2574 for (unsigned i = 0; i != NumMatches; ++i) {
2577 if (i + 1 == NumMatches)
2579 OS << "'" << Base << MatchChars[i] << "'";
2582 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
2586 // Okay, we know that none of the variants matched successfully.
2588 // If all of the instructions reported an invalid mnemonic, then the original
2589 // mnemonic was invalid.
2590 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
2591 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
2592 if (!WasOriginallyInvalidOperand) {
2593 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
2595 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
2596 Ranges, MatchingInlineAsm);
2599 // Recover location info for the operand if we know which was the problem.
2600 if (ErrorInfo != ~0U) {
2601 if (ErrorInfo >= Operands.size())
2602 return Error(IDLoc, "too few operands for instruction",
2603 EmptyRanges, MatchingInlineAsm);
2605 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
2606 if (Operand->getStartLoc().isValid()) {
2607 SMRange OperandRange = Operand->getLocRange();
2608 return Error(Operand->getStartLoc(), "invalid operand for instruction",
2609 OperandRange, MatchingInlineAsm);
2613 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2617 // If one instruction matched with a missing feature, report this as a
2619 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
2620 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
2621 std::string Msg = "instruction requires:";
2623 for (unsigned i = 0; i < (sizeof(ErrorInfoMissingFeature)*8-1); ++i) {
2624 if (ErrorInfoMissingFeature & Mask) {
2626 Msg += getSubtargetFeatureName(ErrorInfoMissingFeature & Mask);
2630 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2633 // If one instruction matched with an invalid operand, report this as an
2635 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
2636 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
2637 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2642 // If all of these were an outright failure, report it in a useless way.
2643 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
2644 EmptyRanges, MatchingInlineAsm);
2649 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
2650 StringRef IDVal = DirectiveID.getIdentifier();
2651 if (IDVal == ".word")
2652 return ParseDirectiveWord(2, DirectiveID.getLoc());
2653 else if (IDVal.startswith(".code"))
2654 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
2655 else if (IDVal.startswith(".att_syntax")) {
2656 getParser().setAssemblerDialect(0);
2658 } else if (IDVal.startswith(".intel_syntax")) {
2659 getParser().setAssemblerDialect(1);
2660 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2661 if(Parser.getTok().getString() == "noprefix") {
2662 // FIXME : Handle noprefix
2672 /// ParseDirectiveWord
2673 /// ::= .word [ expression (, expression)* ]
2674 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
2675 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2677 const MCExpr *Value;
2678 if (getParser().parseExpression(Value))
2681 getParser().getStreamer().EmitValue(Value, Size);
2683 if (getLexer().is(AsmToken::EndOfStatement))
2686 // FIXME: Improve diagnostic.
2687 if (getLexer().isNot(AsmToken::Comma))
2688 return Error(L, "unexpected token in directive");
2697 /// ParseDirectiveCode
2698 /// ::= .code16 | .code32 | .code64
2699 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
2700 if (IDVal == ".code16") {
2702 if (!is16BitMode()) {
2703 SwitchMode(X86::Mode16Bit);
2704 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
2706 } else if (IDVal == ".code32") {
2708 if (!is32BitMode()) {
2709 SwitchMode(X86::Mode32Bit);
2710 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
2712 } else if (IDVal == ".code64") {
2714 if (!is64BitMode()) {
2715 SwitchMode(X86::Mode64Bit);
2716 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
2719 return Error(L, "unexpected directive " + IDVal);
2725 // Force static initialization.
2726 extern "C" void LLVMInitializeX86AsmParser() {
2727 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
2728 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
2731 #define GET_REGISTER_MATCHER
2732 #define GET_MATCHER_IMPLEMENTATION
2733 #define GET_SUBTARGET_FEATURE_NAME
2734 #include "X86GenAsmMatcher.inc"