1 //===-- X86AsmParser.cpp - Parse X86 assembly to MCInst instructions ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MCTargetDesc/X86BaseInfo.h"
11 #include "llvm/MC/MCTargetAsmParser.h"
12 #include "llvm/MC/MCStreamer.h"
13 #include "llvm/MC/MCExpr.h"
14 #include "llvm/MC/MCInst.h"
15 #include "llvm/MC/MCRegisterInfo.h"
16 #include "llvm/MC/MCSubtargetInfo.h"
17 #include "llvm/MC/MCParser/MCAsmLexer.h"
18 #include "llvm/MC/MCParser/MCAsmParser.h"
19 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/TargetRegistry.h"
27 #include "llvm/Support/raw_ostream.h"
34 class X86ATTAsmParser : public MCTargetAsmParser {
39 MCAsmParser &getParser() const { return Parser; }
41 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
43 bool Error(SMLoc L, const Twine &Msg,
44 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) {
45 return Parser.Error(L, Msg, Ranges);
48 X86Operand *ParseOperand();
49 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
51 bool ParseDirectiveWord(unsigned Size, SMLoc L);
52 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
54 bool MatchAndEmitInstruction(SMLoc IDLoc,
55 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
58 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
59 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
60 bool isSrcOp(X86Operand &Op);
62 /// isDstOp - Returns true if operand is either %es:(%rdi) in 64bit mode
63 /// or %es:(%edi) in 32bit mode.
64 bool isDstOp(X86Operand &Op);
66 bool is64BitMode() const {
67 // FIXME: Can tablegen auto-generate this?
68 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
71 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
72 setAvailableFeatures(FB);
75 /// @name Auto-generated Matcher Functions
78 #define GET_ASSEMBLER_HEADER
79 #include "X86GenAsmMatcher.inc"
84 X86ATTAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
85 : MCTargetAsmParser(), STI(sti), Parser(parser) {
87 // Initialize the set of available features.
88 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
90 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
92 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
93 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
95 virtual bool ParseDirective(AsmToken DirectiveID);
97 } // end anonymous namespace
99 /// @name Auto-generated Match Functions
102 static unsigned MatchRegisterName(StringRef Name);
108 /// X86Operand - Instances of this class represent a parsed X86 machine
110 struct X86Operand : public MCParsedAsmOperand {
118 SMLoc StartLoc, EndLoc;
143 X86Operand(KindTy K, SMLoc Start, SMLoc End)
144 : Kind(K), StartLoc(Start), EndLoc(End) {}
146 /// getStartLoc - Get the location of the first token of this operand.
147 SMLoc getStartLoc() const { return StartLoc; }
148 /// getEndLoc - Get the location of the last token of this operand.
149 SMLoc getEndLoc() const { return EndLoc; }
151 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
153 virtual void print(raw_ostream &OS) const {}
155 StringRef getToken() const {
156 assert(Kind == Token && "Invalid access!");
157 return StringRef(Tok.Data, Tok.Length);
159 void setTokenValue(StringRef Value) {
160 assert(Kind == Token && "Invalid access!");
161 Tok.Data = Value.data();
162 Tok.Length = Value.size();
165 unsigned getReg() const {
166 assert(Kind == Register && "Invalid access!");
170 const MCExpr *getImm() const {
171 assert(Kind == Immediate && "Invalid access!");
175 const MCExpr *getMemDisp() const {
176 assert(Kind == Memory && "Invalid access!");
179 unsigned getMemSegReg() const {
180 assert(Kind == Memory && "Invalid access!");
183 unsigned getMemBaseReg() const {
184 assert(Kind == Memory && "Invalid access!");
187 unsigned getMemIndexReg() const {
188 assert(Kind == Memory && "Invalid access!");
191 unsigned getMemScale() const {
192 assert(Kind == Memory && "Invalid access!");
196 bool isToken() const {return Kind == Token; }
198 bool isImm() const { return Kind == Immediate; }
200 bool isImmSExti16i8() const {
204 // If this isn't a constant expr, just assume it fits and let relaxation
206 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
210 // Otherwise, check the value is in a range that makes sense for this
212 uint64_t Value = CE->getValue();
213 return (( Value <= 0x000000000000007FULL)||
214 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
215 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
217 bool isImmSExti32i8() const {
221 // If this isn't a constant expr, just assume it fits and let relaxation
223 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
227 // Otherwise, check the value is in a range that makes sense for this
229 uint64_t Value = CE->getValue();
230 return (( Value <= 0x000000000000007FULL)||
231 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
232 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
234 bool isImmZExtu32u8() const {
238 // If this isn't a constant expr, just assume it fits and let relaxation
240 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
244 // Otherwise, check the value is in a range that makes sense for this
246 uint64_t Value = CE->getValue();
247 return (Value <= 0x00000000000000FFULL);
249 bool isImmSExti64i8() const {
253 // If this isn't a constant expr, just assume it fits and let relaxation
255 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
259 // Otherwise, check the value is in a range that makes sense for this
261 uint64_t Value = CE->getValue();
262 return (( Value <= 0x000000000000007FULL)||
263 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
265 bool isImmSExti64i32() const {
269 // If this isn't a constant expr, just assume it fits and let relaxation
271 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
275 // Otherwise, check the value is in a range that makes sense for this
277 uint64_t Value = CE->getValue();
278 return (( Value <= 0x000000007FFFFFFFULL)||
279 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
282 bool isMem() const { return Kind == Memory; }
284 bool isAbsMem() const {
285 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
286 !getMemIndexReg() && getMemScale() == 1;
289 bool isReg() const { return Kind == Register; }
291 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
292 // Add as immediates when possible.
293 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
294 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
296 Inst.addOperand(MCOperand::CreateExpr(Expr));
299 void addRegOperands(MCInst &Inst, unsigned N) const {
300 assert(N == 1 && "Invalid number of operands!");
301 Inst.addOperand(MCOperand::CreateReg(getReg()));
304 void addImmOperands(MCInst &Inst, unsigned N) const {
305 assert(N == 1 && "Invalid number of operands!");
306 addExpr(Inst, getImm());
309 void addMemOperands(MCInst &Inst, unsigned N) const {
310 assert((N == 5) && "Invalid number of operands!");
311 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
312 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
313 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
314 addExpr(Inst, getMemDisp());
315 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
318 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
319 assert((N == 1) && "Invalid number of operands!");
320 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
323 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
324 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
325 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
326 Res->Tok.Data = Str.data();
327 Res->Tok.Length = Str.size();
331 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
332 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
333 Res->Reg.RegNo = RegNo;
337 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
338 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
343 /// Create an absolute memory operand.
344 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
346 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
348 Res->Mem.Disp = Disp;
349 Res->Mem.BaseReg = 0;
350 Res->Mem.IndexReg = 0;
355 /// Create a generalized memory operand.
356 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
357 unsigned BaseReg, unsigned IndexReg,
358 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc) {
359 // We should never just have a displacement, that should be parsed as an
360 // absolute memory operand.
361 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
363 // The scale should always be one of {1,2,4,8}.
364 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
366 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
367 Res->Mem.SegReg = SegReg;
368 Res->Mem.Disp = Disp;
369 Res->Mem.BaseReg = BaseReg;
370 Res->Mem.IndexReg = IndexReg;
371 Res->Mem.Scale = Scale;
376 } // end anonymous namespace.
378 bool X86ATTAsmParser::isSrcOp(X86Operand &Op) {
379 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
381 return (Op.isMem() &&
382 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
383 isa<MCConstantExpr>(Op.Mem.Disp) &&
384 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
385 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
388 bool X86ATTAsmParser::isDstOp(X86Operand &Op) {
389 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
391 return Op.isMem() && Op.Mem.SegReg == X86::ES &&
392 isa<MCConstantExpr>(Op.Mem.Disp) &&
393 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
394 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
397 bool X86ATTAsmParser::ParseRegister(unsigned &RegNo,
398 SMLoc &StartLoc, SMLoc &EndLoc) {
400 const AsmToken &TokPercent = Parser.getTok();
401 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
402 StartLoc = TokPercent.getLoc();
403 Parser.Lex(); // Eat percent token.
405 const AsmToken &Tok = Parser.getTok();
406 if (Tok.isNot(AsmToken::Identifier))
407 return Error(StartLoc, "invalid register name",
408 SMRange(StartLoc, Tok.getEndLoc()));
410 RegNo = MatchRegisterName(Tok.getString());
412 // If the match failed, try the register name as lowercase.
414 RegNo = MatchRegisterName(Tok.getString().lower());
416 if (!is64BitMode()) {
417 // FIXME: This should be done using Requires<In32BitMode> and
418 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
420 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
422 if (RegNo == X86::RIZ ||
423 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
424 X86II::isX86_64NonExtLowByteReg(RegNo) ||
425 X86II::isX86_64ExtendedReg(RegNo))
426 return Error(StartLoc, "register %"
427 + Tok.getString() + " is only available in 64-bit mode",
428 SMRange(StartLoc, Tok.getEndLoc()));
431 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
432 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
434 EndLoc = Tok.getLoc();
435 Parser.Lex(); // Eat 'st'
437 // Check to see if we have '(4)' after %st.
438 if (getLexer().isNot(AsmToken::LParen))
443 const AsmToken &IntTok = Parser.getTok();
444 if (IntTok.isNot(AsmToken::Integer))
445 return Error(IntTok.getLoc(), "expected stack index");
446 switch (IntTok.getIntVal()) {
447 case 0: RegNo = X86::ST0; break;
448 case 1: RegNo = X86::ST1; break;
449 case 2: RegNo = X86::ST2; break;
450 case 3: RegNo = X86::ST3; break;
451 case 4: RegNo = X86::ST4; break;
452 case 5: RegNo = X86::ST5; break;
453 case 6: RegNo = X86::ST6; break;
454 case 7: RegNo = X86::ST7; break;
455 default: return Error(IntTok.getLoc(), "invalid stack index");
458 if (getParser().Lex().isNot(AsmToken::RParen))
459 return Error(Parser.getTok().getLoc(), "expected ')'");
461 EndLoc = Tok.getLoc();
462 Parser.Lex(); // Eat ')'
466 // If this is "db[0-7]", match it as an alias
468 if (RegNo == 0 && Tok.getString().size() == 3 &&
469 Tok.getString().startswith("db")) {
470 switch (Tok.getString()[2]) {
471 case '0': RegNo = X86::DR0; break;
472 case '1': RegNo = X86::DR1; break;
473 case '2': RegNo = X86::DR2; break;
474 case '3': RegNo = X86::DR3; break;
475 case '4': RegNo = X86::DR4; break;
476 case '5': RegNo = X86::DR5; break;
477 case '6': RegNo = X86::DR6; break;
478 case '7': RegNo = X86::DR7; break;
482 EndLoc = Tok.getLoc();
483 Parser.Lex(); // Eat it.
489 return Error(StartLoc, "invalid register name",
490 SMRange(StartLoc, Tok.getEndLoc()));
492 EndLoc = Tok.getEndLoc();
493 Parser.Lex(); // Eat identifier token.
497 X86Operand *X86ATTAsmParser::ParseOperand() {
498 switch (getLexer().getKind()) {
500 // Parse a memory operand with no segment register.
501 return ParseMemOperand(0, Parser.getTok().getLoc());
502 case AsmToken::Percent: {
503 // Read the register.
506 if (ParseRegister(RegNo, Start, End)) return 0;
507 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
508 Error(Start, "%eiz and %riz can only be used as index registers",
509 SMRange(Start, End));
513 // If this is a segment register followed by a ':', then this is the start
514 // of a memory reference, otherwise this is a normal register reference.
515 if (getLexer().isNot(AsmToken::Colon))
516 return X86Operand::CreateReg(RegNo, Start, End);
519 getParser().Lex(); // Eat the colon.
520 return ParseMemOperand(RegNo, Start);
522 case AsmToken::Dollar: {
524 SMLoc Start = Parser.getTok().getLoc(), End;
527 if (getParser().ParseExpression(Val, End))
529 return X86Operand::CreateImm(Val, Start, End);
534 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
535 /// has already been parsed if present.
536 X86Operand *X86ATTAsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
538 // We have to disambiguate a parenthesized expression "(4+5)" from the start
539 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
540 // only way to do this without lookahead is to eat the '(' and see what is
542 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
543 if (getLexer().isNot(AsmToken::LParen)) {
545 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
547 // After parsing the base expression we could either have a parenthesized
548 // memory address or not. If not, return now. If so, eat the (.
549 if (getLexer().isNot(AsmToken::LParen)) {
550 // Unless we have a segment register, treat this as an immediate.
552 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
553 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
559 // Okay, we have a '('. We don't know if this is an expression or not, but
560 // so we have to eat the ( to see beyond it.
561 SMLoc LParenLoc = Parser.getTok().getLoc();
562 Parser.Lex(); // Eat the '('.
564 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
565 // Nothing to do here, fall into the code below with the '(' part of the
566 // memory operand consumed.
570 // It must be an parenthesized expression, parse it now.
571 if (getParser().ParseParenExpression(Disp, ExprEnd))
574 // After parsing the base expression we could either have a parenthesized
575 // memory address or not. If not, return now. If so, eat the (.
576 if (getLexer().isNot(AsmToken::LParen)) {
577 // Unless we have a segment register, treat this as an immediate.
579 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
580 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
588 // If we reached here, then we just ate the ( of the memory operand. Process
589 // the rest of the memory operand.
590 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
592 if (getLexer().is(AsmToken::Percent)) {
593 SMLoc StartLoc, EndLoc;
594 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
595 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
596 Error(StartLoc, "eiz and riz can only be used as index registers",
597 SMRange(StartLoc, EndLoc));
602 if (getLexer().is(AsmToken::Comma)) {
603 Parser.Lex(); // Eat the comma.
605 // Following the comma we should have either an index register, or a scale
606 // value. We don't support the later form, but we want to parse it
609 // Not that even though it would be completely consistent to support syntax
610 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
611 if (getLexer().is(AsmToken::Percent)) {
613 if (ParseRegister(IndexReg, L, L)) return 0;
615 if (getLexer().isNot(AsmToken::RParen)) {
616 // Parse the scale amount:
617 // ::= ',' [scale-expression]
618 if (getLexer().isNot(AsmToken::Comma)) {
619 Error(Parser.getTok().getLoc(),
620 "expected comma in scale expression");
623 Parser.Lex(); // Eat the comma.
625 if (getLexer().isNot(AsmToken::RParen)) {
626 SMLoc Loc = Parser.getTok().getLoc();
629 if (getParser().ParseAbsoluteExpression(ScaleVal))
632 // Validate the scale amount.
633 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
634 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
637 Scale = (unsigned)ScaleVal;
640 } else if (getLexer().isNot(AsmToken::RParen)) {
641 // A scale amount without an index is ignored.
643 SMLoc Loc = Parser.getTok().getLoc();
646 if (getParser().ParseAbsoluteExpression(Value))
650 Warning(Loc, "scale factor without index register is ignored");
655 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
656 if (getLexer().isNot(AsmToken::RParen)) {
657 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
660 SMLoc MemEnd = Parser.getTok().getLoc();
661 Parser.Lex(); // Eat the ')'.
663 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
667 bool X86ATTAsmParser::
668 ParseInstruction(StringRef Name, SMLoc NameLoc,
669 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
670 StringRef PatchedName = Name;
672 // FIXME: Hack to recognize setneb as setne.
673 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
674 PatchedName != "setb" && PatchedName != "setnb")
675 PatchedName = PatchedName.substr(0, Name.size()-1);
677 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
678 const MCExpr *ExtraImmOp = 0;
679 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
680 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
681 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
682 bool IsVCMP = PatchedName.startswith("vcmp");
683 unsigned SSECCIdx = IsVCMP ? 4 : 3;
684 unsigned SSEComparisonCode = StringSwitch<unsigned>(
685 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
698 .Case("neq_oq", 0x0C)
705 .Case("unord_s", 0x13)
706 .Case("neq_us", 0x14)
707 .Case("nlt_uq", 0x15)
708 .Case("nle_uq", 0x16)
711 .Case("nge_uq", 0x19)
712 .Case("ngt_uq", 0x1A)
713 .Case("false_os", 0x1B)
714 .Case("neq_os", 0x1C)
717 .Case("true_us", 0x1F)
719 if (SSEComparisonCode != ~0U) {
720 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
721 getParser().getContext());
722 if (PatchedName.endswith("ss")) {
723 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
724 } else if (PatchedName.endswith("sd")) {
725 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
726 } else if (PatchedName.endswith("ps")) {
727 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
729 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
730 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
735 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
738 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
741 // Determine whether this is an instruction prefix.
743 Name == "lock" || Name == "rep" ||
744 Name == "repe" || Name == "repz" ||
745 Name == "repne" || Name == "repnz" ||
746 Name == "rex64" || Name == "data16";
749 // This does the actual operand parsing. Don't parse any more if we have a
750 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
751 // just want to parse the "lock" as the first instruction and the "incl" as
753 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
755 // Parse '*' modifier.
756 if (getLexer().is(AsmToken::Star)) {
757 SMLoc Loc = Parser.getTok().getLoc();
758 Operands.push_back(X86Operand::CreateToken("*", Loc));
759 Parser.Lex(); // Eat the star.
762 // Read the first operand.
763 if (X86Operand *Op = ParseOperand())
764 Operands.push_back(Op);
766 Parser.EatToEndOfStatement();
770 while (getLexer().is(AsmToken::Comma)) {
771 Parser.Lex(); // Eat the comma.
773 // Parse and remember the operand.
774 if (X86Operand *Op = ParseOperand())
775 Operands.push_back(Op);
777 Parser.EatToEndOfStatement();
782 if (getLexer().isNot(AsmToken::EndOfStatement)) {
783 SMLoc Loc = getLexer().getLoc();
784 Parser.EatToEndOfStatement();
785 return Error(Loc, "unexpected token in argument list");
789 if (getLexer().is(AsmToken::EndOfStatement))
790 Parser.Lex(); // Consume the EndOfStatement
791 else if (isPrefix && getLexer().is(AsmToken::Slash))
792 Parser.Lex(); // Consume the prefix separator Slash
794 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
795 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
796 // documented form in various unofficial manuals, so a lot of code uses it.
797 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
798 Operands.size() == 3) {
799 X86Operand &Op = *(X86Operand*)Operands.back();
800 if (Op.isMem() && Op.Mem.SegReg == 0 &&
801 isa<MCConstantExpr>(Op.Mem.Disp) &&
802 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
803 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
804 SMLoc Loc = Op.getEndLoc();
805 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
809 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
810 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
811 Operands.size() == 3) {
812 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
813 if (Op.isMem() && Op.Mem.SegReg == 0 &&
814 isa<MCConstantExpr>(Op.Mem.Disp) &&
815 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
816 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
817 SMLoc Loc = Op.getEndLoc();
818 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
822 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
823 if (Name.startswith("ins") && Operands.size() == 3 &&
824 (Name == "insb" || Name == "insw" || Name == "insl")) {
825 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
826 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
827 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
835 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
836 if (Name.startswith("outs") && Operands.size() == 3 &&
837 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
838 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
839 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
840 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
848 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
849 if (Name.startswith("movs") && Operands.size() == 3 &&
850 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
851 (is64BitMode() && Name == "movsq"))) {
852 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
853 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
854 if (isSrcOp(Op) && isDstOp(Op2)) {
861 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
862 if (Name.startswith("lods") && Operands.size() == 3 &&
863 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
864 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
865 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
866 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
867 if (isSrcOp(*Op1) && Op2->isReg()) {
869 unsigned reg = Op2->getReg();
870 bool isLods = Name == "lods";
871 if (reg == X86::AL && (isLods || Name == "lodsb"))
873 else if (reg == X86::AX && (isLods || Name == "lodsw"))
875 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
877 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
887 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
891 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
892 if (Name.startswith("stos") && Operands.size() == 3 &&
893 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
894 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
895 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
896 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
897 if (isDstOp(*Op2) && Op1->isReg()) {
899 unsigned reg = Op1->getReg();
900 bool isStos = Name == "stos";
901 if (reg == X86::AL && (isStos || Name == "stosb"))
903 else if (reg == X86::AX && (isStos || Name == "stosw"))
905 else if (reg == X86::EAX && (isStos || Name == "stosl"))
907 else if (reg == X86::RAX && (isStos || Name == "stosq"))
917 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
922 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
924 if ((Name.startswith("shr") || Name.startswith("sar") ||
925 Name.startswith("shl") || Name.startswith("sal") ||
926 Name.startswith("rcl") || Name.startswith("rcr") ||
927 Name.startswith("rol") || Name.startswith("ror")) &&
928 Operands.size() == 3) {
929 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
930 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
931 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
933 Operands.erase(Operands.begin() + 1);
937 // Transforms "int $3" into "int3" as a size optimization. We can't write an
938 // instalias with an immediate operand yet.
939 if (Name == "int" && Operands.size() == 2) {
940 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
941 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
942 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
944 Operands.erase(Operands.begin() + 1);
945 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
952 bool X86ATTAsmParser::
953 MatchAndEmitInstruction(SMLoc IDLoc,
954 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
956 assert(!Operands.empty() && "Unexpect empty operand list!");
957 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
958 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
960 // First, handle aliases that expand to multiple instructions.
961 // FIXME: This should be replaced with a real .td file alias mechanism.
962 // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
964 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
965 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
966 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
967 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
969 Inst.setOpcode(X86::WAIT);
970 Out.EmitInstruction(Inst);
973 StringSwitch<const char*>(Op->getToken())
974 .Case("finit", "fninit")
975 .Case("fsave", "fnsave")
976 .Case("fstcw", "fnstcw")
977 .Case("fstcww", "fnstcw")
978 .Case("fstenv", "fnstenv")
979 .Case("fstsw", "fnstsw")
980 .Case("fstsww", "fnstsw")
981 .Case("fclex", "fnclex")
983 assert(Repl && "Unknown wait-prefixed instruction");
985 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
988 bool WasOriginallyInvalidOperand = false;
989 unsigned OrigErrorInfo;
992 // First, try a direct match.
993 switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo)) {
996 Out.EmitInstruction(Inst);
998 case Match_MissingFeature:
999 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1001 case Match_ConversionFail:
1002 return Error(IDLoc, "unable to convert operands to instruction");
1003 case Match_InvalidOperand:
1004 WasOriginallyInvalidOperand = true;
1006 case Match_MnemonicFail:
1010 // FIXME: Ideally, we would only attempt suffix matches for things which are
1011 // valid prefixes, and we could just infer the right unambiguous
1012 // type. However, that requires substantially more matcher support than the
1015 // Change the operand to point to a temporary token.
1016 StringRef Base = Op->getToken();
1017 SmallString<16> Tmp;
1020 Op->setTokenValue(Tmp.str());
1022 // If this instruction starts with an 'f', then it is a floating point stack
1023 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1024 // 80-bit floating point, which use the suffixes s,l,t respectively.
1026 // Otherwise, we assume that this may be an integer instruction, which comes
1027 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1028 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1030 // Check for the various suffix matches.
1031 Tmp[Base.size()] = Suffixes[0];
1032 unsigned ErrorInfoIgnore;
1033 unsigned Match1, Match2, Match3, Match4;
1035 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1036 Tmp[Base.size()] = Suffixes[1];
1037 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1038 Tmp[Base.size()] = Suffixes[2];
1039 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1040 Tmp[Base.size()] = Suffixes[3];
1041 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1043 // Restore the old token.
1044 Op->setTokenValue(Base);
1046 // If exactly one matched, then we treat that as a successful match (and the
1047 // instruction will already have been filled in correctly, since the failing
1048 // matches won't have modified it).
1049 unsigned NumSuccessfulMatches =
1050 (Match1 == Match_Success) + (Match2 == Match_Success) +
1051 (Match3 == Match_Success) + (Match4 == Match_Success);
1052 if (NumSuccessfulMatches == 1) {
1053 Out.EmitInstruction(Inst);
1057 // Otherwise, the match failed, try to produce a decent error message.
1059 // If we had multiple suffix matches, then identify this as an ambiguous
1061 if (NumSuccessfulMatches > 1) {
1063 unsigned NumMatches = 0;
1064 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1065 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1066 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1067 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1069 SmallString<126> Msg;
1070 raw_svector_ostream OS(Msg);
1071 OS << "ambiguous instructions require an explicit suffix (could be ";
1072 for (unsigned i = 0; i != NumMatches; ++i) {
1075 if (i + 1 == NumMatches)
1077 OS << "'" << Base << MatchChars[i] << "'";
1080 Error(IDLoc, OS.str());
1084 // Okay, we know that none of the variants matched successfully.
1086 // If all of the instructions reported an invalid mnemonic, then the original
1087 // mnemonic was invalid.
1088 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1089 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1090 if (!WasOriginallyInvalidOperand) {
1091 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1095 // Recover location info for the operand if we know which was the problem.
1096 if (OrigErrorInfo != ~0U) {
1097 if (OrigErrorInfo >= Operands.size())
1098 return Error(IDLoc, "too few operands for instruction");
1100 X86Operand *Operand = (X86Operand*)Operands[OrigErrorInfo];
1101 if (Operand->getStartLoc().isValid()) {
1102 SMRange OperandRange = Operand->getLocRange();
1103 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1108 return Error(IDLoc, "invalid operand for instruction");
1111 // If one instruction matched with a missing feature, report this as a
1113 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1114 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1115 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1119 // If one instruction matched with an invalid operand, report this as an
1121 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1122 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1123 Error(IDLoc, "invalid operand for instruction");
1127 // If all of these were an outright failure, report it in a useless way.
1128 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
1133 bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
1134 StringRef IDVal = DirectiveID.getIdentifier();
1135 if (IDVal == ".word")
1136 return ParseDirectiveWord(2, DirectiveID.getLoc());
1137 else if (IDVal.startswith(".code"))
1138 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1142 /// ParseDirectiveWord
1143 /// ::= .word [ expression (, expression)* ]
1144 bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1145 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1147 const MCExpr *Value;
1148 if (getParser().ParseExpression(Value))
1151 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1153 if (getLexer().is(AsmToken::EndOfStatement))
1156 // FIXME: Improve diagnostic.
1157 if (getLexer().isNot(AsmToken::Comma))
1158 return Error(L, "unexpected token in directive");
1167 /// ParseDirectiveCode
1168 /// ::= .code32 | .code64
1169 bool X86ATTAsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1170 if (IDVal == ".code32") {
1172 if (is64BitMode()) {
1174 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1176 } else if (IDVal == ".code64") {
1178 if (!is64BitMode()) {
1180 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1183 return Error(L, "unexpected directive " + IDVal);
1190 extern "C" void LLVMInitializeX86AsmLexer();
1192 // Force static initialization.
1193 extern "C" void LLVMInitializeX86AsmParser() {
1194 RegisterMCAsmParser<X86ATTAsmParser> X(TheX86_32Target);
1195 RegisterMCAsmParser<X86ATTAsmParser> Y(TheX86_64Target);
1196 LLVMInitializeX86AsmLexer();
1199 #define GET_REGISTER_MATCHER
1200 #define GET_MATCHER_IMPLEMENTATION
1201 #include "X86GenAsmMatcher.inc"