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();
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 return ParseMemOperand();
372 case AsmToken::Percent: {
373 // FIXME: if a segment register, this could either be just the seg reg, or
374 // the start of a memory operand.
377 if (ParseRegister(RegNo, Start, End)) return 0;
378 return X86Operand::CreateReg(RegNo, Start, End);
380 case AsmToken::Dollar: {
382 SMLoc Start = Parser.getTok().getLoc(), End;
385 if (getParser().ParseExpression(Val, End))
387 return X86Operand::CreateImm(Val, Start, End);
392 /// ParseMemOperand: segment: disp(basereg, indexreg, scale)
393 X86Operand *X86ATTAsmParser::ParseMemOperand() {
394 SMLoc MemStart = Parser.getTok().getLoc();
396 // FIXME: If SegReg ':' (e.g. %gs:), eat and remember.
399 // We have to disambiguate a parenthesized expression "(4+5)" from the start
400 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
401 // only way to do this without lookahead is to eat the '(' and see what is
403 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
404 if (getLexer().isNot(AsmToken::LParen)) {
406 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
408 // After parsing the base expression we could either have a parenthesized
409 // memory address or not. If not, return now. If so, eat the (.
410 if (getLexer().isNot(AsmToken::LParen)) {
411 // Unless we have a segment register, treat this as an immediate.
413 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
414 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
420 // Okay, we have a '('. We don't know if this is an expression or not, but
421 // so we have to eat the ( to see beyond it.
422 SMLoc LParenLoc = Parser.getTok().getLoc();
423 Parser.Lex(); // Eat the '('.
425 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
426 // Nothing to do here, fall into the code below with the '(' part of the
427 // memory operand consumed.
431 // It must be an parenthesized expression, parse it now.
432 if (getParser().ParseParenExpression(Disp, ExprEnd))
435 // After parsing the base expression we could either have a parenthesized
436 // memory address or not. If not, return now. If so, eat the (.
437 if (getLexer().isNot(AsmToken::LParen)) {
438 // Unless we have a segment register, treat this as an immediate.
440 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
441 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
449 // If we reached here, then we just ate the ( of the memory operand. Process
450 // the rest of the memory operand.
451 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
453 if (getLexer().is(AsmToken::Percent)) {
455 if (ParseRegister(BaseReg, L, L)) return 0;
458 if (getLexer().is(AsmToken::Comma)) {
459 Parser.Lex(); // Eat the comma.
461 // Following the comma we should have either an index register, or a scale
462 // value. We don't support the later form, but we want to parse it
465 // Not that even though it would be completely consistent to support syntax
466 // like "1(%eax,,1)", the assembler doesn't.
467 if (getLexer().is(AsmToken::Percent)) {
469 if (ParseRegister(IndexReg, L, L)) return 0;
471 if (getLexer().isNot(AsmToken::RParen)) {
472 // Parse the scale amount:
473 // ::= ',' [scale-expression]
474 if (getLexer().isNot(AsmToken::Comma)) {
475 Error(Parser.getTok().getLoc(),
476 "expected comma in scale expression");
479 Parser.Lex(); // Eat the comma.
481 if (getLexer().isNot(AsmToken::RParen)) {
482 SMLoc Loc = Parser.getTok().getLoc();
485 if (getParser().ParseAbsoluteExpression(ScaleVal))
488 // Validate the scale amount.
489 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
490 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
493 Scale = (unsigned)ScaleVal;
496 } else if (getLexer().isNot(AsmToken::RParen)) {
497 // Otherwise we have the unsupported form of a scale amount without an
499 SMLoc Loc = Parser.getTok().getLoc();
502 if (getParser().ParseAbsoluteExpression(Value))
505 Error(Loc, "cannot have scale factor without index register");
510 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
511 if (getLexer().isNot(AsmToken::RParen)) {
512 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
515 SMLoc MemEnd = Parser.getTok().getLoc();
516 Parser.Lex(); // Eat the ')'.
518 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
522 bool X86ATTAsmParser::
523 ParseInstruction(const StringRef &Name, SMLoc NameLoc,
524 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
525 // FIXME: Hack to recognize "sal..." and "rep..." for now. We need a way to
526 // represent alternative syntaxes in the .td file, without requiring
527 // instruction duplication.
528 StringRef PatchedName = StringSwitch<StringRef>(Name)
530 .Case("salb", "shlb")
531 .Case("sall", "shll")
532 .Case("salq", "shlq")
533 .Case("salw", "shlw")
536 .Case("repnz", "repne")
538 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
540 if (getLexer().isNot(AsmToken::EndOfStatement)) {
542 // Parse '*' modifier.
543 if (getLexer().is(AsmToken::Star)) {
544 SMLoc Loc = Parser.getTok().getLoc();
545 Operands.push_back(X86Operand::CreateToken("*", Loc));
546 Parser.Lex(); // Eat the star.
549 // Read the first operand.
550 if (X86Operand *Op = ParseOperand())
551 Operands.push_back(Op);
555 while (getLexer().is(AsmToken::Comma)) {
556 Parser.Lex(); // Eat the comma.
558 // Parse and remember the operand.
559 if (X86Operand *Op = ParseOperand())
560 Operands.push_back(Op);
566 // FIXME: Hack to handle recognizing s{hr,ar,hl}? $1.
567 if ((Name.startswith("shr") || Name.startswith("sar") ||
568 Name.startswith("shl")) &&
569 Operands.size() == 3 &&
570 static_cast<X86Operand*>(Operands[1])->isImm() &&
571 isa<MCConstantExpr>(static_cast<X86Operand*>(Operands[1])->getImm()) &&
572 cast<MCConstantExpr>(static_cast<X86Operand*>(Operands[1])->getImm())->getValue() == 1)
573 Operands.erase(Operands.begin() + 1);
578 bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
579 StringRef IDVal = DirectiveID.getIdentifier();
580 if (IDVal == ".word")
581 return ParseDirectiveWord(2, DirectiveID.getLoc());
585 /// ParseDirectiveWord
586 /// ::= .word [ expression (, expression)* ]
587 bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
588 if (getLexer().isNot(AsmToken::EndOfStatement)) {
591 if (getParser().ParseExpression(Value))
594 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
596 if (getLexer().is(AsmToken::EndOfStatement))
599 // FIXME: Improve diagnostic.
600 if (getLexer().isNot(AsmToken::Comma))
601 return Error(L, "unexpected token in directive");
610 // FIXME: Custom X86 cleanup function to implement a temporary hack to handle
611 // matching INCL/DECL correctly for x86_64. This needs to be replaced by a
612 // proper mechanism for supporting (ambiguous) feature dependent instructions.
613 void X86ATTAsmParser::InstructionCleanup(MCInst &Inst) {
614 if (!Is64Bit) return;
616 switch (Inst.getOpcode()) {
617 case X86::DEC16r: Inst.setOpcode(X86::DEC64_16r); break;
618 case X86::DEC16m: Inst.setOpcode(X86::DEC64_16m); break;
619 case X86::DEC32r: Inst.setOpcode(X86::DEC64_32r); break;
620 case X86::DEC32m: Inst.setOpcode(X86::DEC64_32m); break;
621 case X86::INC16r: Inst.setOpcode(X86::INC64_16r); break;
622 case X86::INC16m: Inst.setOpcode(X86::INC64_16m); break;
623 case X86::INC32r: Inst.setOpcode(X86::INC64_32r); break;
624 case X86::INC32m: Inst.setOpcode(X86::INC64_32m); break;
628 extern "C" void LLVMInitializeX86AsmLexer();
630 // Force static initialization.
631 extern "C" void LLVMInitializeX86AsmParser() {
632 RegisterAsmParser<X86_32ATTAsmParser> X(TheX86_32Target);
633 RegisterAsmParser<X86_64ATTAsmParser> Y(TheX86_64Target);
634 LLVMInitializeX86AsmLexer();
637 #include "X86GenAsmMatcher.inc"