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/Twine.h"
14 #include "llvm/MC/MCStreamer.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCInst.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/Support/SourceMgr.h"
21 #include "llvm/Target/TargetRegistry.h"
22 #include "llvm/Target/TargetAsmParser.h"
28 class X86ATTAsmParser : public TargetAsmParser {
32 MCAsmParser &getParser() const { return Parser; }
34 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
36 void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
38 bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
40 bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
42 X86Operand *ParseOperand();
43 X86Operand *ParseMemOperand();
45 bool ParseDirectiveWord(unsigned Size, SMLoc L);
47 /// @name Auto-generated Match Functions
50 bool MatchInstruction(const SmallVectorImpl<MCParsedAsmOperand*> &Operands,
56 X86ATTAsmParser(const Target &T, MCAsmParser &_Parser)
57 : TargetAsmParser(T), Parser(_Parser) {}
59 virtual bool ParseInstruction(const StringRef &Name, SMLoc NameLoc,
60 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
62 virtual bool ParseDirective(AsmToken DirectiveID);
65 } // end anonymous namespace
67 /// @name Auto-generated Match Functions
70 static unsigned MatchRegisterName(const StringRef &Name);
76 /// X86Operand - Instances of this class represent a parsed X86 machine
78 struct X86Operand : public MCParsedAsmOperand {
86 SMLoc StartLoc, EndLoc;
111 X86Operand(KindTy K, SMLoc Start, SMLoc End)
112 : Kind(K), StartLoc(Start), EndLoc(End) {}
114 /// getStartLoc - Get the location of the first token of this operand.
115 SMLoc getStartLoc() const { return StartLoc; }
116 /// getEndLoc - Get the location of the last token of this operand.
117 SMLoc getEndLoc() const { return EndLoc; }
119 StringRef getToken() const {
120 assert(Kind == Token && "Invalid access!");
121 return StringRef(Tok.Data, Tok.Length);
124 unsigned getReg() const {
125 assert(Kind == Register && "Invalid access!");
129 const MCExpr *getImm() const {
130 assert(Kind == Immediate && "Invalid access!");
134 const MCExpr *getMemDisp() const {
135 assert(Kind == Memory && "Invalid access!");
138 unsigned getMemSegReg() const {
139 assert(Kind == Memory && "Invalid access!");
142 unsigned getMemBaseReg() const {
143 assert(Kind == Memory && "Invalid access!");
146 unsigned getMemIndexReg() const {
147 assert(Kind == Memory && "Invalid access!");
150 unsigned getMemScale() const {
151 assert(Kind == Memory && "Invalid access!");
155 bool isToken() const {return Kind == Token; }
157 bool isImm() const { return Kind == Immediate; }
159 bool isImmSExt8() const {
160 // Accept immediates which fit in 8 bits when sign extended, and
161 // non-absolute immediates.
165 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
166 int64_t Value = CE->getValue();
167 return Value == (int64_t) (int8_t) Value;
173 bool isMem() const { return Kind == Memory; }
175 bool isReg() const { return Kind == Register; }
177 void addRegOperands(MCInst &Inst, unsigned N) const {
178 assert(N == 1 && "Invalid number of operands!");
179 Inst.addOperand(MCOperand::CreateReg(getReg()));
182 void addImmOperands(MCInst &Inst, unsigned N) const {
183 assert(N == 1 && "Invalid number of operands!");
184 Inst.addOperand(MCOperand::CreateExpr(getImm()));
187 void addImmSExt8Operands(MCInst &Inst, unsigned N) const {
188 // FIXME: Support user customization of the render method.
189 assert(N == 1 && "Invalid number of operands!");
190 Inst.addOperand(MCOperand::CreateExpr(getImm()));
193 void addMemOperands(MCInst &Inst, unsigned N) const {
194 assert((N == 4 || N == 5) && "Invalid number of operands!");
196 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
197 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
198 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
199 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
201 // FIXME: What a hack.
203 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
206 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
207 X86Operand *Res = new X86Operand(Token, Loc, Loc);
208 Res->Tok.Data = Str.data();
209 Res->Tok.Length = Str.size();
213 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
214 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
215 Res->Reg.RegNo = RegNo;
219 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
220 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
225 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
226 unsigned BaseReg, unsigned IndexReg,
227 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc) {
228 // We should never just have a displacement, that would be an immediate.
229 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
231 // The scale should always be one of {1,2,4,8}.
232 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
234 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
235 Res->Mem.SegReg = SegReg;
236 Res->Mem.Disp = Disp;
237 Res->Mem.BaseReg = BaseReg;
238 Res->Mem.IndexReg = IndexReg;
239 Res->Mem.Scale = Scale;
244 } // end anonymous namespace.
247 bool X86ATTAsmParser::ParseRegister(unsigned &RegNo,
248 SMLoc &StartLoc, SMLoc &EndLoc) {
250 const AsmToken &TokPercent = Parser.getTok();
251 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
252 StartLoc = TokPercent.getLoc();
253 Parser.Lex(); // Eat percent token.
255 const AsmToken &Tok = Parser.getTok();
256 if (Tok.isNot(AsmToken::Identifier))
257 return Error(Tok.getLoc(), "invalid register name");
259 // FIXME: Validate register for the current architecture; we have to do
260 // validation later, so maybe there is no need for this here.
261 RegNo = MatchRegisterName(Tok.getString());
263 return Error(Tok.getLoc(), "invalid register name");
265 EndLoc = Tok.getLoc();
266 Parser.Lex(); // Eat identifier token.
270 X86Operand *X86ATTAsmParser::ParseOperand() {
271 switch (getLexer().getKind()) {
273 return ParseMemOperand();
274 case AsmToken::Percent: {
275 // FIXME: if a segment register, this could either be just the seg reg, or
276 // the start of a memory operand.
279 if (ParseRegister(RegNo, Start, End)) return 0;
280 return X86Operand::CreateReg(RegNo, Start, End);
282 case AsmToken::Dollar: {
284 SMLoc Start = Parser.getTok().getLoc(), End;
287 if (getParser().ParseExpression(Val, End))
289 return X86Operand::CreateImm(Val, Start, End);
294 /// ParseMemOperand: segment: disp(basereg, indexreg, scale)
295 X86Operand *X86ATTAsmParser::ParseMemOperand() {
296 SMLoc MemStart = Parser.getTok().getLoc();
298 // FIXME: If SegReg ':' (e.g. %gs:), eat and remember.
301 // We have to disambiguate a parenthesized expression "(4+5)" from the start
302 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
303 // only way to do this without lookahead is to eat the ( and see what is after
305 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
306 if (getLexer().isNot(AsmToken::LParen)) {
308 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
310 // After parsing the base expression we could either have a parenthesized
311 // memory address or not. If not, return now. If so, eat the (.
312 if (getLexer().isNot(AsmToken::LParen)) {
313 // Unless we have a segment register, treat this as an immediate.
315 return X86Operand::CreateImm(Disp, MemStart, ExprEnd);
316 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
322 // Okay, we have a '('. We don't know if this is an expression or not, but
323 // so we have to eat the ( to see beyond it.
324 SMLoc LParenLoc = Parser.getTok().getLoc();
325 Parser.Lex(); // Eat the '('.
327 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
328 // Nothing to do here, fall into the code below with the '(' part of the
329 // memory operand consumed.
333 // It must be an parenthesized expression, parse it now.
334 if (getParser().ParseParenExpression(Disp, ExprEnd))
337 // After parsing the base expression we could either have a parenthesized
338 // memory address or not. If not, return now. If so, eat the (.
339 if (getLexer().isNot(AsmToken::LParen)) {
340 // Unless we have a segment register, treat this as an immediate.
342 return X86Operand::CreateImm(Disp, LParenLoc, ExprEnd);
343 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
351 // If we reached here, then we just ate the ( of the memory operand. Process
352 // the rest of the memory operand.
353 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
355 if (getLexer().is(AsmToken::Percent)) {
357 if (ParseRegister(BaseReg, L, L)) return 0;
360 if (getLexer().is(AsmToken::Comma)) {
361 Parser.Lex(); // Eat the comma.
363 // Following the comma we should have either an index register, or a scale
364 // value. We don't support the later form, but we want to parse it
367 // Not that even though it would be completely consistent to support syntax
368 // like "1(%eax,,1)", the assembler doesn't.
369 if (getLexer().is(AsmToken::Percent)) {
371 if (ParseRegister(IndexReg, L, L)) return 0;
373 if (getLexer().isNot(AsmToken::RParen)) {
374 // Parse the scale amount:
375 // ::= ',' [scale-expression]
376 if (getLexer().isNot(AsmToken::Comma)) {
377 Error(Parser.getTok().getLoc(),
378 "expected comma in scale expression");
381 Parser.Lex(); // Eat the comma.
383 if (getLexer().isNot(AsmToken::RParen)) {
384 SMLoc Loc = Parser.getTok().getLoc();
387 if (getParser().ParseAbsoluteExpression(ScaleVal))
390 // Validate the scale amount.
391 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
392 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
395 Scale = (unsigned)ScaleVal;
398 } else if (getLexer().isNot(AsmToken::RParen)) {
399 // Otherwise we have the unsupported form of a scale amount without an
401 SMLoc Loc = Parser.getTok().getLoc();
404 if (getParser().ParseAbsoluteExpression(Value))
407 Error(Loc, "cannot have scale factor without index register");
412 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
413 if (getLexer().isNot(AsmToken::RParen)) {
414 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
417 SMLoc MemEnd = Parser.getTok().getLoc();
418 Parser.Lex(); // Eat the ')'.
420 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
424 bool X86ATTAsmParser::
425 ParseInstruction(const StringRef &Name, SMLoc NameLoc,
426 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
428 Operands.push_back(X86Operand::CreateToken(Name, NameLoc));
430 if (getLexer().isNot(AsmToken::EndOfStatement)) {
432 // Parse '*' modifier.
433 if (getLexer().is(AsmToken::Star)) {
434 SMLoc Loc = Parser.getTok().getLoc();
435 Operands.push_back(X86Operand::CreateToken("*", Loc));
436 Parser.Lex(); // Eat the star.
439 // Read the first operand.
440 if (X86Operand *Op = ParseOperand())
441 Operands.push_back(Op);
445 while (getLexer().is(AsmToken::Comma)) {
446 Parser.Lex(); // Eat the comma.
448 // Parse and remember the operand.
449 if (X86Operand *Op = ParseOperand())
450 Operands.push_back(Op);
459 bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
460 StringRef IDVal = DirectiveID.getIdentifier();
461 if (IDVal == ".word")
462 return ParseDirectiveWord(2, DirectiveID.getLoc());
466 /// ParseDirectiveWord
467 /// ::= .word [ expression (, expression)* ]
468 bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
469 if (getLexer().isNot(AsmToken::EndOfStatement)) {
472 if (getParser().ParseExpression(Value))
475 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
477 if (getLexer().is(AsmToken::EndOfStatement))
480 // FIXME: Improve diagnostic.
481 if (getLexer().isNot(AsmToken::Comma))
482 return Error(L, "unexpected token in directive");
491 // Force static initialization.
492 extern "C" void LLVMInitializeX86AsmParser() {
493 RegisterAsmParser<X86ATTAsmParser> X(TheX86_32Target);
494 RegisterAsmParser<X86ATTAsmParser> Y(TheX86_64Target);
497 #include "X86GenAsmMatcher.inc"