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 "llvm/Target/TargetAsmParser.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/StringSwitch.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/MC/MCStreamer.h"
16 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCInst.h"
18 #include "llvm/MC/MCParser/MCAsmLexer.h"
19 #include "llvm/MC/MCParser/MCAsmParser.h"
20 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
21 #include "llvm/Support/SourceMgr.h"
22 #include "llvm/Target/TargetRegistry.h"
23 #include "llvm/Target/TargetAsmParser.h"
29 class X86ATTAsmParser : public TargetAsmParser {
36 MCAsmParser &getParser() const { return Parser; }
38 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
40 void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
42 bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
44 bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
46 X86Operand *ParseOperand();
47 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
49 bool ParseDirectiveWord(unsigned Size, SMLoc L);
51 void InstructionCleanup(MCInst &Inst);
53 /// @name Auto-generated Match Functions
56 bool MatchInstruction(const SmallVectorImpl<MCParsedAsmOperand*> &Operands,
62 X86ATTAsmParser(const Target &T, MCAsmParser &_Parser)
63 : TargetAsmParser(T), Parser(_Parser) {}
65 virtual bool ParseInstruction(const StringRef &Name, SMLoc NameLoc,
66 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
68 virtual bool ParseDirective(AsmToken DirectiveID);
71 class X86_32ATTAsmParser : public X86ATTAsmParser {
73 X86_32ATTAsmParser(const Target &T, MCAsmParser &_Parser)
74 : X86ATTAsmParser(T, _Parser) {
79 class X86_64ATTAsmParser : public X86ATTAsmParser {
81 X86_64ATTAsmParser(const Target &T, MCAsmParser &_Parser)
82 : X86ATTAsmParser(T, _Parser) {
87 } // end anonymous namespace
89 /// @name Auto-generated Match Functions
92 static unsigned MatchRegisterName(StringRef Name);
98 /// X86Operand - Instances of this class represent a parsed X86 machine
100 struct X86Operand : public MCParsedAsmOperand {
108 SMLoc StartLoc, EndLoc;
133 X86Operand(KindTy K, SMLoc Start, SMLoc End)
134 : Kind(K), StartLoc(Start), EndLoc(End) {}
136 /// getStartLoc - Get the location of the first token of this operand.
137 SMLoc getStartLoc() const { return StartLoc; }
138 /// getEndLoc - Get the location of the last token of this operand.
139 SMLoc getEndLoc() const { return EndLoc; }
141 StringRef getToken() const {
142 assert(Kind == Token && "Invalid access!");
143 return StringRef(Tok.Data, Tok.Length);
146 unsigned getReg() const {
147 assert(Kind == Register && "Invalid access!");
151 const MCExpr *getImm() const {
152 assert(Kind == Immediate && "Invalid access!");
156 const MCExpr *getMemDisp() const {
157 assert(Kind == Memory && "Invalid access!");
160 unsigned getMemSegReg() const {
161 assert(Kind == Memory && "Invalid access!");
164 unsigned getMemBaseReg() const {
165 assert(Kind == Memory && "Invalid access!");
168 unsigned getMemIndexReg() const {
169 assert(Kind == Memory && "Invalid access!");
172 unsigned getMemScale() const {
173 assert(Kind == Memory && "Invalid access!");
177 bool isToken() const {return Kind == Token; }
179 bool isImm() const { return Kind == Immediate; }
181 bool isImmSExt8() const {
182 // Accept immediates which fit in 8 bits when sign extended, and
183 // non-absolute immediates.
187 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
188 int64_t Value = CE->getValue();
189 return Value == (int64_t) (int8_t) Value;
195 bool isMem() const { return Kind == Memory; }
197 bool isAbsMem() const {
198 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
199 !getMemIndexReg() && getMemScale() == 1;
202 bool isNoSegMem() const {
203 return Kind == Memory && !getMemSegReg();
206 bool isReg() const { return Kind == Register; }
208 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
209 // Add as immediates when possible.
210 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
211 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
213 Inst.addOperand(MCOperand::CreateExpr(Expr));
216 void addRegOperands(MCInst &Inst, unsigned N) const {
217 assert(N == 1 && "Invalid number of operands!");
218 Inst.addOperand(MCOperand::CreateReg(getReg()));
221 void addImmOperands(MCInst &Inst, unsigned N) const {
222 assert(N == 1 && "Invalid number of operands!");
223 addExpr(Inst, getImm());
226 void addImmSExt8Operands(MCInst &Inst, unsigned N) const {
227 // FIXME: Support user customization of the render method.
228 assert(N == 1 && "Invalid number of operands!");
229 addExpr(Inst, getImm());
232 void addMemOperands(MCInst &Inst, unsigned N) const {
233 assert((N == 5) && "Invalid number of operands!");
234 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
235 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
236 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
237 addExpr(Inst, getMemDisp());
238 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
241 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
242 assert((N == 1) && "Invalid number of operands!");
243 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
246 void addNoSegMemOperands(MCInst &Inst, unsigned N) const {
247 assert((N == 4) && "Invalid number of operands!");
248 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
249 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
250 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
251 addExpr(Inst, getMemDisp());
254 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
255 X86Operand *Res = new X86Operand(Token, Loc, Loc);
256 Res->Tok.Data = Str.data();
257 Res->Tok.Length = Str.size();
261 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
262 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
263 Res->Reg.RegNo = RegNo;
267 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
268 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
273 /// Create an absolute memory operand.
274 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
276 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
278 Res->Mem.Disp = Disp;
279 Res->Mem.BaseReg = 0;
280 Res->Mem.IndexReg = 0;
285 /// Create a generalized memory operand.
286 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
287 unsigned BaseReg, unsigned IndexReg,
288 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc) {
289 // We should never just have a displacement, that should be parsed as an
290 // absolute memory operand.
291 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
293 // The scale should always be one of {1,2,4,8}.
294 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
296 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
297 Res->Mem.SegReg = SegReg;
298 Res->Mem.Disp = Disp;
299 Res->Mem.BaseReg = BaseReg;
300 Res->Mem.IndexReg = IndexReg;
301 Res->Mem.Scale = Scale;
306 } // end anonymous namespace.
309 bool X86ATTAsmParser::ParseRegister(unsigned &RegNo,
310 SMLoc &StartLoc, SMLoc &EndLoc) {
312 const AsmToken &TokPercent = Parser.getTok();
313 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
314 StartLoc = TokPercent.getLoc();
315 Parser.Lex(); // Eat percent token.
317 const AsmToken &Tok = Parser.getTok();
318 if (Tok.isNot(AsmToken::Identifier))
319 return Error(Tok.getLoc(), "invalid register name");
321 // FIXME: Validate register for the current architecture; we have to do
322 // validation later, so maybe there is no need for this here.
323 RegNo = MatchRegisterName(Tok.getString());
325 // Parse %st(1) and "%st" as "%st(0)"
326 if (RegNo == 0 && Tok.getString() == "st") {
328 EndLoc = Tok.getLoc();
329 Parser.Lex(); // Eat 'st'
331 // Check to see if we have '(4)' after %st.
332 if (getLexer().isNot(AsmToken::LParen))
337 const AsmToken &IntTok = Parser.getTok();
338 if (IntTok.isNot(AsmToken::Integer))
339 return Error(IntTok.getLoc(), "expected stack index");
340 switch (IntTok.getIntVal()) {
341 case 0: RegNo = X86::ST0; break;
342 case 1: RegNo = X86::ST1; break;
343 case 2: RegNo = X86::ST2; break;
344 case 3: RegNo = X86::ST3; break;
345 case 4: RegNo = X86::ST4; break;
346 case 5: RegNo = X86::ST5; break;
347 case 6: RegNo = X86::ST6; break;
348 case 7: RegNo = X86::ST7; break;
349 default: return Error(IntTok.getLoc(), "invalid stack index");
352 if (getParser().Lex().isNot(AsmToken::RParen))
353 return Error(Parser.getTok().getLoc(), "expected ')'");
355 EndLoc = Tok.getLoc();
356 Parser.Lex(); // Eat ')'
361 return Error(Tok.getLoc(), "invalid register name");
363 EndLoc = Tok.getLoc();
364 Parser.Lex(); // Eat identifier token.
368 X86Operand *X86ATTAsmParser::ParseOperand() {
369 switch (getLexer().getKind()) {
371 // Parse a memory operand with no segment register.
372 return ParseMemOperand(0, Parser.getTok().getLoc());
373 case AsmToken::Percent: {
374 // Read the register.
377 if (ParseRegister(RegNo, Start, End)) return 0;
379 // If this is a segment register followed by a ':', then this is the start
380 // of a memory reference, otherwise this is a normal register reference.
381 if (getLexer().isNot(AsmToken::Colon))
382 return X86Operand::CreateReg(RegNo, Start, End);
385 getParser().Lex(); // Eat the colon.
386 return ParseMemOperand(RegNo, Start);
388 case AsmToken::Dollar: {
390 SMLoc Start = Parser.getTok().getLoc(), End;
393 if (getParser().ParseExpression(Val, End))
395 return X86Operand::CreateImm(Val, Start, End);
400 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
401 /// has already been parsed if present.
402 X86Operand *X86ATTAsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
404 // We have to disambiguate a parenthesized expression "(4+5)" from the start
405 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
406 // only way to do this without lookahead is to eat the '(' and see what is
408 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
409 if (getLexer().isNot(AsmToken::LParen)) {
411 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
413 // After parsing the base expression we could either have a parenthesized
414 // memory address or not. If not, return now. If so, eat the (.
415 if (getLexer().isNot(AsmToken::LParen)) {
416 // Unless we have a segment register, treat this as an immediate.
418 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
419 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
425 // Okay, we have a '('. We don't know if this is an expression or not, but
426 // so we have to eat the ( to see beyond it.
427 SMLoc LParenLoc = Parser.getTok().getLoc();
428 Parser.Lex(); // Eat the '('.
430 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
431 // Nothing to do here, fall into the code below with the '(' part of the
432 // memory operand consumed.
436 // It must be an parenthesized expression, parse it now.
437 if (getParser().ParseParenExpression(Disp, ExprEnd))
440 // After parsing the base expression we could either have a parenthesized
441 // memory address or not. If not, return now. If so, eat the (.
442 if (getLexer().isNot(AsmToken::LParen)) {
443 // Unless we have a segment register, treat this as an immediate.
445 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
446 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
454 // If we reached here, then we just ate the ( of the memory operand. Process
455 // the rest of the memory operand.
456 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
458 if (getLexer().is(AsmToken::Percent)) {
460 if (ParseRegister(BaseReg, L, L)) return 0;
463 if (getLexer().is(AsmToken::Comma)) {
464 Parser.Lex(); // Eat the comma.
466 // Following the comma we should have either an index register, or a scale
467 // value. We don't support the later form, but we want to parse it
470 // Not that even though it would be completely consistent to support syntax
471 // like "1(%eax,,1)", the assembler doesn't.
472 if (getLexer().is(AsmToken::Percent)) {
474 if (ParseRegister(IndexReg, L, L)) return 0;
476 if (getLexer().isNot(AsmToken::RParen)) {
477 // Parse the scale amount:
478 // ::= ',' [scale-expression]
479 if (getLexer().isNot(AsmToken::Comma)) {
480 Error(Parser.getTok().getLoc(),
481 "expected comma in scale expression");
484 Parser.Lex(); // Eat the comma.
486 if (getLexer().isNot(AsmToken::RParen)) {
487 SMLoc Loc = Parser.getTok().getLoc();
490 if (getParser().ParseAbsoluteExpression(ScaleVal))
493 // Validate the scale amount.
494 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
495 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
498 Scale = (unsigned)ScaleVal;
501 } else if (getLexer().isNot(AsmToken::RParen)) {
502 // Otherwise we have the unsupported form of a scale amount without an
504 SMLoc Loc = Parser.getTok().getLoc();
507 if (getParser().ParseAbsoluteExpression(Value))
510 Error(Loc, "cannot have scale factor without index register");
515 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
516 if (getLexer().isNot(AsmToken::RParen)) {
517 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
520 SMLoc MemEnd = Parser.getTok().getLoc();
521 Parser.Lex(); // Eat the ')'.
523 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
527 bool X86ATTAsmParser::
528 ParseInstruction(const StringRef &Name, SMLoc NameLoc,
529 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
530 // FIXME: Hack to recognize "sal..." and "rep..." for now. We need a way to
531 // represent alternative syntaxes in the .td file, without requiring
532 // instruction duplication.
533 StringRef PatchedName = StringSwitch<StringRef>(Name)
535 .Case("salb", "shlb")
536 .Case("sall", "shll")
537 .Case("salq", "shlq")
538 .Case("salw", "shlw")
541 .Case("repnz", "repne")
543 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
545 if (getLexer().isNot(AsmToken::EndOfStatement)) {
547 // Parse '*' modifier.
548 if (getLexer().is(AsmToken::Star)) {
549 SMLoc Loc = Parser.getTok().getLoc();
550 Operands.push_back(X86Operand::CreateToken("*", Loc));
551 Parser.Lex(); // Eat the star.
554 // Read the first operand.
555 if (X86Operand *Op = ParseOperand())
556 Operands.push_back(Op);
560 while (getLexer().is(AsmToken::Comma)) {
561 Parser.Lex(); // Eat the comma.
563 // Parse and remember the operand.
564 if (X86Operand *Op = ParseOperand())
565 Operands.push_back(Op);
571 // FIXME: Hack to handle recognizing s{hr,ar,hl}? $1.
572 if ((Name.startswith("shr") || Name.startswith("sar") ||
573 Name.startswith("shl")) &&
574 Operands.size() == 3 &&
575 static_cast<X86Operand*>(Operands[1])->isImm() &&
576 isa<MCConstantExpr>(static_cast<X86Operand*>(Operands[1])->getImm()) &&
577 cast<MCConstantExpr>(static_cast<X86Operand*>(Operands[1])->getImm())->getValue() == 1) {
579 Operands.erase(Operands.begin() + 1);
585 bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
586 StringRef IDVal = DirectiveID.getIdentifier();
587 if (IDVal == ".word")
588 return ParseDirectiveWord(2, DirectiveID.getLoc());
592 /// ParseDirectiveWord
593 /// ::= .word [ expression (, expression)* ]
594 bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
595 if (getLexer().isNot(AsmToken::EndOfStatement)) {
598 if (getParser().ParseExpression(Value))
601 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
603 if (getLexer().is(AsmToken::EndOfStatement))
606 // FIXME: Improve diagnostic.
607 if (getLexer().isNot(AsmToken::Comma))
608 return Error(L, "unexpected token in directive");
617 // FIXME: Custom X86 cleanup function to implement a temporary hack to handle
618 // matching INCL/DECL correctly for x86_64. This needs to be replaced by a
619 // proper mechanism for supporting (ambiguous) feature dependent instructions.
620 void X86ATTAsmParser::InstructionCleanup(MCInst &Inst) {
621 if (!Is64Bit) return;
623 switch (Inst.getOpcode()) {
624 case X86::DEC16r: Inst.setOpcode(X86::DEC64_16r); break;
625 case X86::DEC16m: Inst.setOpcode(X86::DEC64_16m); break;
626 case X86::DEC32r: Inst.setOpcode(X86::DEC64_32r); break;
627 case X86::DEC32m: Inst.setOpcode(X86::DEC64_32m); break;
628 case X86::INC16r: Inst.setOpcode(X86::INC64_16r); break;
629 case X86::INC16m: Inst.setOpcode(X86::INC64_16m); break;
630 case X86::INC32r: Inst.setOpcode(X86::INC64_32r); break;
631 case X86::INC32m: Inst.setOpcode(X86::INC64_32m); break;
635 extern "C" void LLVMInitializeX86AsmLexer();
637 // Force static initialization.
638 extern "C" void LLVMInitializeX86AsmParser() {
639 RegisterAsmParser<X86_32ATTAsmParser> X(TheX86_32Target);
640 RegisterAsmParser<X86_64ATTAsmParser> Y(TheX86_64Target);
641 LLVMInitializeX86AsmLexer();
644 #include "X86GenAsmMatcher.inc"