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 {
33 MCAsmParser &getParser() const { return Parser; }
35 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
37 void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
39 bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
41 bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
43 X86Operand *ParseOperand();
44 X86Operand *ParseMemOperand();
46 bool ParseDirectiveWord(unsigned Size, SMLoc L);
48 /// @name Auto-generated Match Functions
51 bool MatchInstruction(const SmallVectorImpl<MCParsedAsmOperand*> &Operands,
57 X86ATTAsmParser(const Target &T, MCAsmParser &_Parser)
58 : TargetAsmParser(T), Parser(_Parser) {}
60 virtual bool ParseInstruction(const StringRef &Name, SMLoc NameLoc,
61 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
63 virtual bool ParseDirective(AsmToken DirectiveID);
66 } // end anonymous namespace
68 /// @name Auto-generated Match Functions
71 static unsigned MatchRegisterName(StringRef Name);
77 /// X86Operand - Instances of this class represent a parsed X86 machine
79 struct X86Operand : public MCParsedAsmOperand {
87 SMLoc StartLoc, EndLoc;
112 X86Operand(KindTy K, SMLoc Start, SMLoc End)
113 : Kind(K), StartLoc(Start), EndLoc(End) {}
115 /// getStartLoc - Get the location of the first token of this operand.
116 SMLoc getStartLoc() const { return StartLoc; }
117 /// getEndLoc - Get the location of the last token of this operand.
118 SMLoc getEndLoc() const { return EndLoc; }
120 StringRef getToken() const {
121 assert(Kind == Token && "Invalid access!");
122 return StringRef(Tok.Data, Tok.Length);
125 unsigned getReg() const {
126 assert(Kind == Register && "Invalid access!");
130 const MCExpr *getImm() const {
131 assert(Kind == Immediate && "Invalid access!");
135 const MCExpr *getMemDisp() const {
136 assert(Kind == Memory && "Invalid access!");
139 unsigned getMemSegReg() const {
140 assert(Kind == Memory && "Invalid access!");
143 unsigned getMemBaseReg() const {
144 assert(Kind == Memory && "Invalid access!");
147 unsigned getMemIndexReg() const {
148 assert(Kind == Memory && "Invalid access!");
151 unsigned getMemScale() const {
152 assert(Kind == Memory && "Invalid access!");
156 bool isToken() const {return Kind == Token; }
158 bool isImm() const { return Kind == Immediate; }
160 bool isImmSExt8() const {
161 // Accept immediates which fit in 8 bits when sign extended, and
162 // non-absolute immediates.
166 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
167 int64_t Value = CE->getValue();
168 return Value == (int64_t) (int8_t) Value;
174 bool isMem() const { return Kind == Memory; }
176 bool isAbsMem() const {
177 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
178 !getMemIndexReg() && getMemScale() == 1;
181 bool isNoSegMem() const {
182 return Kind == Memory && !getMemSegReg();
185 bool isReg() const { return Kind == Register; }
187 void addRegOperands(MCInst &Inst, unsigned N) const {
188 assert(N == 1 && "Invalid number of operands!");
189 Inst.addOperand(MCOperand::CreateReg(getReg()));
192 void addImmOperands(MCInst &Inst, unsigned N) const {
193 assert(N == 1 && "Invalid number of operands!");
194 Inst.addOperand(MCOperand::CreateExpr(getImm()));
197 void addImmSExt8Operands(MCInst &Inst, unsigned N) const {
198 // FIXME: Support user customization of the render method.
199 assert(N == 1 && "Invalid number of operands!");
200 Inst.addOperand(MCOperand::CreateExpr(getImm()));
203 void addMemOperands(MCInst &Inst, unsigned N) const {
204 assert((N == 5) && "Invalid number of operands!");
205 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
206 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
207 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
208 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
209 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
212 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
213 assert((N == 1) && "Invalid number of operands!");
214 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
217 void addNoSegMemOperands(MCInst &Inst, unsigned N) const {
218 assert((N == 4) && "Invalid number of operands!");
219 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
220 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
221 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
222 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
225 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
226 X86Operand *Res = new X86Operand(Token, Loc, Loc);
227 Res->Tok.Data = Str.data();
228 Res->Tok.Length = Str.size();
232 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
233 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
234 Res->Reg.RegNo = RegNo;
238 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
239 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
244 /// Create an absolute memory operand.
245 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
247 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
249 Res->Mem.Disp = Disp;
250 Res->Mem.BaseReg = 0;
251 Res->Mem.IndexReg = 0;
256 /// Create a generalized memory operand.
257 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
258 unsigned BaseReg, unsigned IndexReg,
259 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc) {
260 // We should never just have a displacement, that should be parsed as an
261 // absolute memory operand.
262 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
264 // The scale should always be one of {1,2,4,8}.
265 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
267 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
268 Res->Mem.SegReg = SegReg;
269 Res->Mem.Disp = Disp;
270 Res->Mem.BaseReg = BaseReg;
271 Res->Mem.IndexReg = IndexReg;
272 Res->Mem.Scale = Scale;
277 } // end anonymous namespace.
280 bool X86ATTAsmParser::ParseRegister(unsigned &RegNo,
281 SMLoc &StartLoc, SMLoc &EndLoc) {
283 const AsmToken &TokPercent = Parser.getTok();
284 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
285 StartLoc = TokPercent.getLoc();
286 Parser.Lex(); // Eat percent token.
288 const AsmToken &Tok = Parser.getTok();
289 if (Tok.isNot(AsmToken::Identifier))
290 return Error(Tok.getLoc(), "invalid register name");
292 // FIXME: Validate register for the current architecture; we have to do
293 // validation later, so maybe there is no need for this here.
294 RegNo = MatchRegisterName(Tok.getString());
296 // Parse %st(1) and "%st" as "%st(0)"
297 if (RegNo == 0 && Tok.getString() == "st") {
299 EndLoc = Tok.getLoc();
300 Parser.Lex(); // Eat 'st'
302 // Check to see if we have '(4)' after %st.
303 if (getLexer().isNot(AsmToken::LParen))
308 const AsmToken &IntTok = Parser.getTok();
309 if (IntTok.isNot(AsmToken::Integer))
310 return Error(IntTok.getLoc(), "expected stack index");
311 switch (IntTok.getIntVal()) {
312 case 0: RegNo = X86::ST0; break;
313 case 1: RegNo = X86::ST1; break;
314 case 2: RegNo = X86::ST2; break;
315 case 3: RegNo = X86::ST3; break;
316 case 4: RegNo = X86::ST4; break;
317 case 5: RegNo = X86::ST5; break;
318 case 6: RegNo = X86::ST6; break;
319 case 7: RegNo = X86::ST7; break;
320 default: return Error(IntTok.getLoc(), "invalid stack index");
323 if (getParser().Lex().isNot(AsmToken::RParen))
324 return Error(Parser.getTok().getLoc(), "expected ')'");
326 EndLoc = Tok.getLoc();
327 Parser.Lex(); // Eat ')'
332 return Error(Tok.getLoc(), "invalid register name");
334 EndLoc = Tok.getLoc();
335 Parser.Lex(); // Eat identifier token.
339 X86Operand *X86ATTAsmParser::ParseOperand() {
340 switch (getLexer().getKind()) {
342 return ParseMemOperand();
343 case AsmToken::Percent: {
344 // FIXME: if a segment register, this could either be just the seg reg, or
345 // the start of a memory operand.
348 if (ParseRegister(RegNo, Start, End)) return 0;
349 return X86Operand::CreateReg(RegNo, Start, End);
351 case AsmToken::Dollar: {
353 SMLoc Start = Parser.getTok().getLoc(), End;
356 if (getParser().ParseExpression(Val, End))
358 return X86Operand::CreateImm(Val, Start, End);
363 /// ParseMemOperand: segment: disp(basereg, indexreg, scale)
364 X86Operand *X86ATTAsmParser::ParseMemOperand() {
365 SMLoc MemStart = Parser.getTok().getLoc();
367 // FIXME: If SegReg ':' (e.g. %gs:), eat and remember.
370 // We have to disambiguate a parenthesized expression "(4+5)" from the start
371 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
372 // only way to do this without lookahead is to eat the '(' and see what is
374 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
375 if (getLexer().isNot(AsmToken::LParen)) {
377 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
379 // After parsing the base expression we could either have a parenthesized
380 // memory address or not. If not, return now. If so, eat the (.
381 if (getLexer().isNot(AsmToken::LParen)) {
382 // Unless we have a segment register, treat this as an immediate.
384 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
385 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
391 // Okay, we have a '('. We don't know if this is an expression or not, but
392 // so we have to eat the ( to see beyond it.
393 SMLoc LParenLoc = Parser.getTok().getLoc();
394 Parser.Lex(); // Eat the '('.
396 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
397 // Nothing to do here, fall into the code below with the '(' part of the
398 // memory operand consumed.
402 // It must be an parenthesized expression, parse it now.
403 if (getParser().ParseParenExpression(Disp, ExprEnd))
406 // After parsing the base expression we could either have a parenthesized
407 // memory address or not. If not, return now. If so, eat the (.
408 if (getLexer().isNot(AsmToken::LParen)) {
409 // Unless we have a segment register, treat this as an immediate.
411 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
412 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
420 // If we reached here, then we just ate the ( of the memory operand. Process
421 // the rest of the memory operand.
422 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
424 if (getLexer().is(AsmToken::Percent)) {
426 if (ParseRegister(BaseReg, L, L)) return 0;
429 if (getLexer().is(AsmToken::Comma)) {
430 Parser.Lex(); // Eat the comma.
432 // Following the comma we should have either an index register, or a scale
433 // value. We don't support the later form, but we want to parse it
436 // Not that even though it would be completely consistent to support syntax
437 // like "1(%eax,,1)", the assembler doesn't.
438 if (getLexer().is(AsmToken::Percent)) {
440 if (ParseRegister(IndexReg, L, L)) return 0;
442 if (getLexer().isNot(AsmToken::RParen)) {
443 // Parse the scale amount:
444 // ::= ',' [scale-expression]
445 if (getLexer().isNot(AsmToken::Comma)) {
446 Error(Parser.getTok().getLoc(),
447 "expected comma in scale expression");
450 Parser.Lex(); // Eat the comma.
452 if (getLexer().isNot(AsmToken::RParen)) {
453 SMLoc Loc = Parser.getTok().getLoc();
456 if (getParser().ParseAbsoluteExpression(ScaleVal))
459 // Validate the scale amount.
460 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
461 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
464 Scale = (unsigned)ScaleVal;
467 } else if (getLexer().isNot(AsmToken::RParen)) {
468 // Otherwise we have the unsupported form of a scale amount without an
470 SMLoc Loc = Parser.getTok().getLoc();
473 if (getParser().ParseAbsoluteExpression(Value))
476 Error(Loc, "cannot have scale factor without index register");
481 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
482 if (getLexer().isNot(AsmToken::RParen)) {
483 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
486 SMLoc MemEnd = Parser.getTok().getLoc();
487 Parser.Lex(); // Eat the ')'.
489 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
493 bool X86ATTAsmParser::
494 ParseInstruction(const StringRef &Name, SMLoc NameLoc,
495 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
496 // FIXME: Hack to recognize "sal..." and "rep..." for now. We need a way to
497 // represent alternative syntaxes in the .td file, without requiring
498 // instruction duplication.
499 StringRef PatchedName = StringSwitch<StringRef>(Name)
501 .Case("salb", "shlb")
502 .Case("sall", "shll")
503 .Case("salq", "shlq")
504 .Case("salw", "shlw")
507 .Case("repnz", "repne")
509 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
511 if (getLexer().isNot(AsmToken::EndOfStatement)) {
513 // Parse '*' modifier.
514 if (getLexer().is(AsmToken::Star)) {
515 SMLoc Loc = Parser.getTok().getLoc();
516 Operands.push_back(X86Operand::CreateToken("*", Loc));
517 Parser.Lex(); // Eat the star.
520 // Read the first operand.
521 if (X86Operand *Op = ParseOperand())
522 Operands.push_back(Op);
526 while (getLexer().is(AsmToken::Comma)) {
527 Parser.Lex(); // Eat the comma.
529 // Parse and remember the operand.
530 if (X86Operand *Op = ParseOperand())
531 Operands.push_back(Op);
540 bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
541 StringRef IDVal = DirectiveID.getIdentifier();
542 if (IDVal == ".word")
543 return ParseDirectiveWord(2, DirectiveID.getLoc());
547 /// ParseDirectiveWord
548 /// ::= .word [ expression (, expression)* ]
549 bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
550 if (getLexer().isNot(AsmToken::EndOfStatement)) {
553 if (getParser().ParseExpression(Value))
556 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
558 if (getLexer().is(AsmToken::EndOfStatement))
561 // FIXME: Improve diagnostic.
562 if (getLexer().isNot(AsmToken::Comma))
563 return Error(L, "unexpected token in directive");
572 extern "C" void LLVMInitializeX86AsmLexer();
574 // Force static initialization.
575 extern "C" void LLVMInitializeX86AsmParser() {
576 RegisterAsmParser<X86ATTAsmParser> X(TheX86_32Target);
577 RegisterAsmParser<X86ATTAsmParser> Y(TheX86_64Target);
578 LLVMInitializeX86AsmLexer();
581 #include "X86GenAsmMatcher.inc"