LLVM API Documentation

X86AsmParser.cpp

Go to the documentation of this file.
00001 //===-- X86AsmParser.cpp - Parse X86 assembly to MCInst instructions ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "X86.h"
00011 #include "llvm/ADT/SmallVector.h"
00012 #include "llvm/ADT/Twine.h"
00013 #include "llvm/MC/MCAsmLexer.h"
00014 #include "llvm/MC/MCAsmParser.h"
00015 #include "llvm/MC/MCInst.h"
00016 #include "llvm/MC/MCValue.h"
00017 #include "llvm/Support/SourceMgr.h"
00018 #include "llvm/Target/TargetRegistry.h"
00019 #include "llvm/Target/TargetAsmParser.h"
00020 using namespace llvm;
00021 
00022 namespace {
00023 struct X86Operand;
00024 
00025 class X86ATTAsmParser : public TargetAsmParser {
00026   MCAsmParser &Parser;
00027 
00028 private:
00029   MCAsmParser &getParser() const { return Parser; }
00030 
00031   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
00032 
00033   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
00034 
00035   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
00036 
00037   bool ParseRegister(X86Operand &Op);
00038 
00039   bool ParseOperand(X86Operand &Op);
00040 
00041   bool ParseMemOperand(X86Operand &Op);
00042   
00043   /// @name Auto-generated Match Functions
00044   /// {  
00045 
00046   bool MatchInstruction(SmallVectorImpl<X86Operand> &Operands,
00047                         MCInst &Inst);
00048 
00049   /// MatchRegisterName - Match the given string to a register name, or 0 if
00050   /// there is no match.
00051   unsigned MatchRegisterName(const StringRef &Name);
00052 
00053   /// }
00054 
00055 public:
00056   X86ATTAsmParser(const Target &T, MCAsmParser &_Parser)
00057     : TargetAsmParser(T), Parser(_Parser) {}
00058 
00059   virtual bool ParseInstruction(const StringRef &Name, MCInst &Inst);
00060 };
00061   
00062 } // end anonymous namespace
00063 
00064 
00065 namespace {
00066 
00067 /// X86Operand - Instances of this class represent a parsed X86 machine
00068 /// instruction.
00069 struct X86Operand {
00070   enum {
00071     Token,
00072     Register,
00073     Immediate,
00074     Memory
00075   } Kind;
00076 
00077   union {
00078     struct {
00079       const char *Data;
00080       unsigned Length;
00081     } Tok;
00082 
00083     struct {
00084       unsigned RegNo;
00085     } Reg;
00086 
00087     struct {
00088       MCValue Val;
00089     } Imm;
00090 
00091     struct {
00092       unsigned SegReg;
00093       MCValue Disp;
00094       unsigned BaseReg;
00095       unsigned IndexReg;
00096       unsigned Scale;
00097     } Mem;
00098   };
00099 
00100   StringRef getToken() const {
00101     assert(Kind == Token && "Invalid access!");
00102     return StringRef(Tok.Data, Tok.Length);
00103   }
00104 
00105   unsigned getReg() const {
00106     assert(Kind == Register && "Invalid access!");
00107     return Reg.RegNo;
00108   }
00109 
00110   const MCValue &getImm() const {
00111     assert(Kind == Immediate && "Invalid access!");
00112     return Imm.Val;
00113   }
00114 
00115   const MCValue &getMemDisp() const {
00116     assert(Kind == Memory && "Invalid access!");
00117     return Mem.Disp;
00118   }
00119   unsigned getMemSegReg() const {
00120     assert(Kind == Memory && "Invalid access!");
00121     return Mem.SegReg;
00122   }
00123   unsigned getMemBaseReg() const {
00124     assert(Kind == Memory && "Invalid access!");
00125     return Mem.BaseReg;
00126   }
00127   unsigned getMemIndexReg() const {
00128     assert(Kind == Memory && "Invalid access!");
00129     return Mem.IndexReg;
00130   }
00131   unsigned getMemScale() const {
00132     assert(Kind == Memory && "Invalid access!");
00133     return Mem.Scale;
00134   }
00135 
00136   bool isToken() const {return Kind == Token; }
00137 
00138   bool isImm() const { return Kind == Immediate; }
00139   
00140   bool isImmSExt8() const { 
00141     // Accept immediates which fit in 8 bits when sign extended, and
00142     // non-absolute immediates.
00143     if (!isImm())
00144       return false;
00145 
00146     if (!getImm().isAbsolute())
00147       return true;
00148 
00149     int64_t Value = getImm().getConstant();
00150     return Value == (int64_t) (int8_t) Value;
00151   }
00152   
00153   bool isMem() const { return Kind == Memory; }
00154 
00155   bool isReg() const { return Kind == Register; }
00156 
00157   void addRegOperands(MCInst &Inst, unsigned N) const {
00158     assert(N == 1 && "Invalid number of operands!");
00159     Inst.addOperand(MCOperand::CreateReg(getReg()));
00160   }
00161 
00162   void addImmOperands(MCInst &Inst, unsigned N) const {
00163     assert(N == 1 && "Invalid number of operands!");
00164     Inst.addOperand(MCOperand::CreateMCValue(getImm()));
00165   }
00166 
00167   void addImmSExt8Operands(MCInst &Inst, unsigned N) const {
00168     // FIXME: Support user customization of the render method.
00169     assert(N == 1 && "Invalid number of operands!");
00170     Inst.addOperand(MCOperand::CreateMCValue(getImm()));
00171   }
00172 
00173   void addMemOperands(MCInst &Inst, unsigned N) const {
00174     assert((N == 4 || N == 5) && "Invalid number of operands!");
00175 
00176     Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
00177     Inst.addOperand(MCOperand::CreateImm(getMemScale()));
00178     Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
00179     Inst.addOperand(MCOperand::CreateMCValue(getMemDisp()));
00180 
00181     // FIXME: What a hack.
00182     if (N == 5)
00183       Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
00184   }
00185 
00186   static X86Operand CreateToken(StringRef Str) {
00187     X86Operand Res;
00188     Res.Kind = Token;
00189     Res.Tok.Data = Str.data();
00190     Res.Tok.Length = Str.size();
00191     return Res;
00192   }
00193 
00194   static X86Operand CreateReg(unsigned RegNo) {
00195     X86Operand Res;
00196     Res.Kind = Register;
00197     Res.Reg.RegNo = RegNo;
00198     return Res;
00199   }
00200 
00201   static X86Operand CreateImm(MCValue Val) {
00202     X86Operand Res;
00203     Res.Kind = Immediate;
00204     Res.Imm.Val = Val;
00205     return Res;
00206   }
00207 
00208   static X86Operand CreateMem(unsigned SegReg, MCValue Disp, unsigned BaseReg,
00209                               unsigned IndexReg, unsigned Scale) {
00210     // We should never just have a displacement, that would be an immediate.
00211     assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
00212 
00213     // The scale should always be one of {1,2,4,8}.
00214     assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
00215            "Invalid scale!");
00216     X86Operand Res;
00217     Res.Kind = Memory;
00218     Res.Mem.SegReg   = SegReg;
00219     Res.Mem.Disp     = Disp;
00220     Res.Mem.BaseReg  = BaseReg;
00221     Res.Mem.IndexReg = IndexReg;
00222     Res.Mem.Scale    = Scale;
00223     return Res;
00224   }
00225 };
00226 
00227 } // end anonymous namespace.
00228 
00229 
00230 bool X86ATTAsmParser::ParseRegister(X86Operand &Op) {
00231   const AsmToken &Tok = getLexer().getTok();
00232   assert(Tok.is(AsmToken::Register) && "Invalid token kind!");
00233 
00234   // FIXME: Validate register for the current architecture; we have to do
00235   // validation later, so maybe there is no need for this here.
00236   unsigned RegNo;
00237   assert(Tok.getString().startswith("%") && "Invalid register name!");
00238 
00239   RegNo = MatchRegisterName(Tok.getString().substr(1));
00240   if (RegNo == 0)
00241     return Error(Tok.getLoc(), "invalid register name");
00242 
00243   Op = X86Operand::CreateReg(RegNo);
00244   getLexer().Lex(); // Eat register token.
00245 
00246   return false;
00247 }
00248 
00249 bool X86ATTAsmParser::ParseOperand(X86Operand &Op) {
00250   switch (getLexer().getKind()) {
00251   default:
00252     return ParseMemOperand(Op);
00253   case AsmToken::Register:
00254     // FIXME: if a segment register, this could either be just the seg reg, or
00255     // the start of a memory operand.
00256     return ParseRegister(Op);
00257   case AsmToken::Dollar: {
00258     // $42 -> immediate.
00259     getLexer().Lex();
00260     MCValue Val;
00261     if (getParser().ParseRelocatableExpression(Val))
00262       return true;
00263     Op = X86Operand::CreateImm(Val);
00264     return false;
00265   }
00266   }
00267 }
00268 
00269 /// ParseMemOperand: segment: disp(basereg, indexreg, scale)
00270 bool X86ATTAsmParser::ParseMemOperand(X86Operand &Op) {
00271   // FIXME: If SegReg ':'  (e.g. %gs:), eat and remember.
00272   unsigned SegReg = 0;
00273   
00274   // We have to disambiguate a parenthesized expression "(4+5)" from the start
00275   // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)".  The
00276   // only way to do this without lookahead is to eat the ( and see what is after
00277   // it.
00278   MCValue Disp = MCValue::get(0, 0, 0);
00279   if (getLexer().isNot(AsmToken::LParen)) {
00280     if (getParser().ParseRelocatableExpression(Disp)) return true;
00281     
00282     // After parsing the base expression we could either have a parenthesized
00283     // memory address or not.  If not, return now.  If so, eat the (.
00284     if (getLexer().isNot(AsmToken::LParen)) {
00285       // Unless we have a segment register, treat this as an immediate.
00286       if (SegReg)
00287         Op = X86Operand::CreateMem(SegReg, Disp, 0, 0, 1);
00288       else
00289         Op = X86Operand::CreateImm(Disp);
00290       return false;
00291     }
00292     
00293     // Eat the '('.
00294     getLexer().Lex();
00295   } else {
00296     // Okay, we have a '('.  We don't know if this is an expression or not, but
00297     // so we have to eat the ( to see beyond it.
00298     getLexer().Lex(); // Eat the '('.
00299     
00300     if (getLexer().is(AsmToken::Register) || getLexer().is(AsmToken::Comma)) {
00301       // Nothing to do here, fall into the code below with the '(' part of the
00302       // memory operand consumed.
00303     } else {
00304       // It must be an parenthesized expression, parse it now.
00305       if (getParser().ParseParenRelocatableExpression(Disp))
00306         return true;
00307       
00308       // After parsing the base expression we could either have a parenthesized
00309       // memory address or not.  If not, return now.  If so, eat the (.
00310       if (getLexer().isNot(AsmToken::LParen)) {
00311         // Unless we have a segment register, treat this as an immediate.
00312         if (SegReg)
00313           Op = X86Operand::CreateMem(SegReg, Disp, 0, 0, 1);
00314         else
00315           Op = X86Operand::CreateImm(Disp);
00316         return false;
00317       }
00318       
00319       // Eat the '('.
00320       getLexer().Lex();
00321     }
00322   }
00323   
00324   // If we reached here, then we just ate the ( of the memory operand.  Process
00325   // the rest of the memory operand.
00326   unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
00327   
00328   if (getLexer().is(AsmToken::Register)) {
00329     if (ParseRegister(Op))
00330       return true;
00331     BaseReg = Op.getReg();
00332   }
00333   
00334   if (getLexer().is(AsmToken::Comma)) {
00335     getLexer().Lex(); // Eat the comma.
00336 
00337     // Following the comma we should have either an index register, or a scale
00338     // value. We don't support the later form, but we want to parse it
00339     // correctly.
00340     //
00341     // Not that even though it would be completely consistent to support syntax
00342     // like "1(%eax,,1)", the assembler doesn't.
00343     if (getLexer().is(AsmToken::Register)) {
00344       if (ParseRegister(Op))
00345         return true;
00346       IndexReg = Op.getReg();
00347     
00348       if (getLexer().isNot(AsmToken::RParen)) {
00349         // Parse the scale amount:
00350         //  ::= ',' [scale-expression]
00351         if (getLexer().isNot(AsmToken::Comma))
00352           return true;
00353         getLexer().Lex(); // Eat the comma.
00354 
00355         if (getLexer().isNot(AsmToken::RParen)) {
00356           SMLoc Loc = getLexer().getTok().getLoc();
00357 
00358           int64_t ScaleVal;
00359           if (getParser().ParseAbsoluteExpression(ScaleVal))
00360             return true;
00361           
00362           // Validate the scale amount.
00363           if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8)
00364             return Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
00365           Scale = (unsigned)ScaleVal;
00366         }
00367       }
00368     } else if (getLexer().isNot(AsmToken::RParen)) {
00369       // Otherwise we have the unsupported form of a scale amount without an
00370       // index.
00371       SMLoc Loc = getLexer().getTok().getLoc();
00372 
00373       int64_t Value;
00374       if (getParser().ParseAbsoluteExpression(Value))
00375         return true;
00376       
00377       return Error(Loc, "cannot have scale factor without index register");
00378     }
00379   }
00380   
00381   // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
00382   if (getLexer().isNot(AsmToken::RParen))
00383     return Error(getLexer().getTok().getLoc(),
00384                     "unexpected token in memory operand");
00385   getLexer().Lex(); // Eat the ')'.
00386   
00387   Op = X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale);
00388   return false;
00389 }
00390 
00391 bool X86ATTAsmParser::ParseInstruction(const StringRef &Name, MCInst &Inst) {
00392   SmallVector<X86Operand, 8> Operands;
00393 
00394   Operands.push_back(X86Operand::CreateToken(Name));
00395 
00396   SMLoc Loc = getLexer().getTok().getLoc();
00397   if (getLexer().isNot(AsmToken::EndOfStatement)) {
00398 
00399     // Parse '*' modifier.
00400     if (getLexer().is(AsmToken::Star)) {
00401       getLexer().Lex(); // Eat the star.
00402       Operands.push_back(X86Operand::CreateToken("*"));
00403     }
00404 
00405     // Read the first operand.
00406     Operands.push_back(X86Operand());
00407     if (ParseOperand(Operands.back()))
00408       return true;
00409 
00410     while (getLexer().is(AsmToken::Comma)) {
00411       getLexer().Lex();  // Eat the comma.
00412 
00413       // Parse and remember the operand.
00414       Operands.push_back(X86Operand());
00415       if (ParseOperand(Operands.back()))
00416         return true;
00417     }
00418   }
00419 
00420   if (!MatchInstruction(Operands, Inst))
00421     return false;
00422 
00423   // FIXME: We should give nicer diagnostics about the exact failure.
00424 
00425   Error(Loc, "unrecognized instruction");
00426   return true;
00427 }
00428 
00429 // Force static initialization.
00430 extern "C" void LLVMInitializeX86AsmParser() {
00431   RegisterAsmParser<X86ATTAsmParser> X(TheX86_32Target);
00432   RegisterAsmParser<X86ATTAsmParser> Y(TheX86_64Target);
00433 }
00434 
00435 #include "X86GenAsmMatcher.inc"