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/MCAsmLexer.h"
15 #include "llvm/MC/MCAsmParser.h"
16 #include "llvm/MC/MCStreamer.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCInst.h"
19 #include "llvm/MC/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,
53 /// MatchRegisterName - Match the given string to a register name, or 0 if
54 /// there is no match.
55 unsigned MatchRegisterName(const StringRef &Name);
60 X86ATTAsmParser(const Target &T, MCAsmParser &_Parser)
61 : TargetAsmParser(T), Parser(_Parser) {}
63 virtual bool ParseInstruction(const StringRef &Name, SMLoc NameLoc,
64 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
66 virtual bool ParseDirective(AsmToken DirectiveID);
69 } // end anonymous namespace
74 /// X86Operand - Instances of this class represent a parsed X86 machine
76 struct X86Operand : public MCParsedAsmOperand {
84 SMLoc StartLoc, EndLoc;
109 X86Operand(KindTy K, SMLoc Start, SMLoc End)
110 : Kind(K), StartLoc(Start), EndLoc(End) {}
112 /// getStartLoc - Get the location of the first token of this operand.
113 SMLoc getStartLoc() const { return StartLoc; }
114 /// getEndLoc - Get the location of the last token of this operand.
115 SMLoc getEndLoc() const { return EndLoc; }
117 StringRef getToken() const {
118 assert(Kind == Token && "Invalid access!");
119 return StringRef(Tok.Data, Tok.Length);
122 unsigned getReg() const {
123 assert(Kind == Register && "Invalid access!");
127 const MCExpr *getImm() const {
128 assert(Kind == Immediate && "Invalid access!");
132 const MCExpr *getMemDisp() const {
133 assert(Kind == Memory && "Invalid access!");
136 unsigned getMemSegReg() const {
137 assert(Kind == Memory && "Invalid access!");
140 unsigned getMemBaseReg() const {
141 assert(Kind == Memory && "Invalid access!");
144 unsigned getMemIndexReg() const {
145 assert(Kind == Memory && "Invalid access!");
148 unsigned getMemScale() const {
149 assert(Kind == Memory && "Invalid access!");
153 bool isToken() const {return Kind == Token; }
155 bool isImm() const { return Kind == Immediate; }
157 bool isImmSExt8() const {
158 // Accept immediates which fit in 8 bits when sign extended, and
159 // non-absolute immediates.
163 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
164 int64_t Value = CE->getValue();
165 return Value == (int64_t) (int8_t) Value;
171 bool isMem() const { return Kind == Memory; }
173 bool isReg() const { return Kind == Register; }
175 void addRegOperands(MCInst &Inst, unsigned N) const {
176 assert(N == 1 && "Invalid number of operands!");
177 Inst.addOperand(MCOperand::CreateReg(getReg()));
180 void addImmOperands(MCInst &Inst, unsigned N) const {
181 assert(N == 1 && "Invalid number of operands!");
182 Inst.addOperand(MCOperand::CreateExpr(getImm()));
185 void addImmSExt8Operands(MCInst &Inst, unsigned N) const {
186 // FIXME: Support user customization of the render method.
187 assert(N == 1 && "Invalid number of operands!");
188 Inst.addOperand(MCOperand::CreateExpr(getImm()));
191 void addMemOperands(MCInst &Inst, unsigned N) const {
192 assert((N == 4 || N == 5) && "Invalid number of operands!");
194 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
195 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
196 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
197 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
199 // FIXME: What a hack.
201 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
204 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
205 X86Operand *Res = new X86Operand(Token, Loc, Loc);
206 Res->Tok.Data = Str.data();
207 Res->Tok.Length = Str.size();
211 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
212 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
213 Res->Reg.RegNo = RegNo;
217 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
218 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
223 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
224 unsigned BaseReg, unsigned IndexReg,
225 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc) {
226 // We should never just have a displacement, that would be an immediate.
227 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
229 // The scale should always be one of {1,2,4,8}.
230 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
232 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
233 Res->Mem.SegReg = SegReg;
234 Res->Mem.Disp = Disp;
235 Res->Mem.BaseReg = BaseReg;
236 Res->Mem.IndexReg = IndexReg;
237 Res->Mem.Scale = Scale;
242 } // end anonymous namespace.
245 bool X86ATTAsmParser::ParseRegister(unsigned &RegNo,
246 SMLoc &StartLoc, SMLoc &EndLoc) {
248 const AsmToken &TokPercent = getLexer().getTok();
249 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
250 StartLoc = TokPercent.getLoc();
251 Parser.Lex(); // Eat percent token.
253 const AsmToken &Tok = getLexer().getTok();
254 if (Tok.isNot(AsmToken::Identifier))
255 return Error(Tok.getLoc(), "invalid register name");
257 // FIXME: Validate register for the current architecture; we have to do
258 // validation later, so maybe there is no need for this here.
259 RegNo = MatchRegisterName(Tok.getString());
261 return Error(Tok.getLoc(), "invalid register name");
263 EndLoc = Tok.getLoc();
264 Parser.Lex(); // Eat identifier token.
268 X86Operand *X86ATTAsmParser::ParseOperand() {
269 switch (getLexer().getKind()) {
271 return ParseMemOperand();
272 case AsmToken::Percent: {
273 // FIXME: if a segment register, this could either be just the seg reg, or
274 // the start of a memory operand.
277 if (ParseRegister(RegNo, Start, End)) return 0;
278 return X86Operand::CreateReg(RegNo, Start, End);
280 case AsmToken::Dollar: {
282 SMLoc Start = getLexer().getTok().getLoc(), End;
285 if (getParser().ParseExpression(Val, End))
287 return X86Operand::CreateImm(Val, Start, End);
292 /// ParseMemOperand: segment: disp(basereg, indexreg, scale)
293 X86Operand *X86ATTAsmParser::ParseMemOperand() {
294 SMLoc MemStart = getLexer().getTok().getLoc();
296 // FIXME: If SegReg ':' (e.g. %gs:), eat and remember.
299 // We have to disambiguate a parenthesized expression "(4+5)" from the start
300 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
301 // only way to do this without lookahead is to eat the ( and see what is after
303 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
304 if (getLexer().isNot(AsmToken::LParen)) {
306 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
308 // After parsing the base expression we could either have a parenthesized
309 // memory address or not. If not, return now. If so, eat the (.
310 if (getLexer().isNot(AsmToken::LParen)) {
311 // Unless we have a segment register, treat this as an immediate.
313 return X86Operand::CreateImm(Disp, MemStart, ExprEnd);
314 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
320 // Okay, we have a '('. We don't know if this is an expression or not, but
321 // so we have to eat the ( to see beyond it.
322 SMLoc LParenLoc = getLexer().getTok().getLoc();
323 Parser.Lex(); // Eat the '('.
325 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
326 // Nothing to do here, fall into the code below with the '(' part of the
327 // memory operand consumed.
331 // It must be an parenthesized expression, parse it now.
332 if (getParser().ParseParenExpression(Disp, ExprEnd))
335 // After parsing the base expression we could either have a parenthesized
336 // memory address or not. If not, return now. If so, eat the (.
337 if (getLexer().isNot(AsmToken::LParen)) {
338 // Unless we have a segment register, treat this as an immediate.
340 return X86Operand::CreateImm(Disp, LParenLoc, ExprEnd);
341 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
349 // If we reached here, then we just ate the ( of the memory operand. Process
350 // the rest of the memory operand.
351 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
353 if (getLexer().is(AsmToken::Percent)) {
355 if (ParseRegister(BaseReg, L, L)) return 0;
358 if (getLexer().is(AsmToken::Comma)) {
359 Parser.Lex(); // Eat the comma.
361 // Following the comma we should have either an index register, or a scale
362 // value. We don't support the later form, but we want to parse it
365 // Not that even though it would be completely consistent to support syntax
366 // like "1(%eax,,1)", the assembler doesn't.
367 if (getLexer().is(AsmToken::Percent)) {
369 if (ParseRegister(IndexReg, L, L)) return 0;
371 if (getLexer().isNot(AsmToken::RParen)) {
372 // Parse the scale amount:
373 // ::= ',' [scale-expression]
374 if (getLexer().isNot(AsmToken::Comma)) {
375 Error(getLexer().getTok().getLoc(),
376 "expected comma in scale expression");
379 Parser.Lex(); // Eat the comma.
381 if (getLexer().isNot(AsmToken::RParen)) {
382 SMLoc Loc = getLexer().getTok().getLoc();
385 if (getParser().ParseAbsoluteExpression(ScaleVal))
388 // Validate the scale amount.
389 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
390 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
393 Scale = (unsigned)ScaleVal;
396 } else if (getLexer().isNot(AsmToken::RParen)) {
397 // Otherwise we have the unsupported form of a scale amount without an
399 SMLoc Loc = getLexer().getTok().getLoc();
402 if (getParser().ParseAbsoluteExpression(Value))
405 Error(Loc, "cannot have scale factor without index register");
410 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
411 if (getLexer().isNot(AsmToken::RParen)) {
412 Error(getLexer().getTok().getLoc(), "unexpected token in memory operand");
415 SMLoc MemEnd = getLexer().getTok().getLoc();
416 Parser.Lex(); // Eat the ')'.
418 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
422 bool X86ATTAsmParser::
423 ParseInstruction(const StringRef &Name, SMLoc NameLoc,
424 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
426 Operands.push_back(X86Operand::CreateToken(Name, NameLoc));
428 if (getLexer().isNot(AsmToken::EndOfStatement)) {
430 // Parse '*' modifier.
431 if (getLexer().is(AsmToken::Star)) {
432 SMLoc Loc = getLexer().getTok().getLoc();
433 Operands.push_back(X86Operand::CreateToken("*", Loc));
434 Parser.Lex(); // Eat the star.
437 // Read the first operand.
438 if (X86Operand *Op = ParseOperand())
439 Operands.push_back(Op);
443 while (getLexer().is(AsmToken::Comma)) {
444 Parser.Lex(); // Eat the comma.
446 // Parse and remember the operand.
447 if (X86Operand *Op = ParseOperand())
448 Operands.push_back(Op);
457 bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
458 StringRef IDVal = DirectiveID.getIdentifier();
459 if (IDVal == ".word")
460 return ParseDirectiveWord(2, DirectiveID.getLoc());
464 /// ParseDirectiveWord
465 /// ::= .word [ expression (, expression)* ]
466 bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
467 if (getLexer().isNot(AsmToken::EndOfStatement)) {
470 if (getParser().ParseExpression(Value))
473 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
475 if (getLexer().is(AsmToken::EndOfStatement))
478 // FIXME: Improve diagnostic.
479 if (getLexer().isNot(AsmToken::Comma))
480 return Error(L, "unexpected token in directive");
489 // Force static initialization.
490 extern "C" void LLVMInitializeX86AsmParser() {
491 RegisterAsmParser<X86ATTAsmParser> X(TheX86_32Target);
492 RegisterAsmParser<X86ATTAsmParser> Y(TheX86_64Target);
495 #include "X86GenAsmMatcher.inc"