X86AsmParser.cpp revision 00743c2218ff3f0f4edce972e2d88893a19e6ef8
1//===-- X86AsmParser.cpp - Parse X86 assembly to MCInst instructions ------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Target/TargetAsmParser.h"
11#include "X86.h"
12#include "X86Subtarget.h"
13#include "llvm/Target/TargetRegistry.h"
14#include "llvm/Target/TargetAsmParser.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/ADT/SmallString.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/ADT/StringSwitch.h"
25#include "llvm/ADT/Twine.h"
26#include "llvm/Support/SourceMgr.h"
27#include "llvm/Support/raw_ostream.h"
28using namespace llvm;
29
30namespace {
31struct X86Operand;
32
33class X86ATTAsmParser : public TargetAsmParser {
34  MCAsmParser &Parser;
35  TargetMachine &TM;
36
37protected:
38  unsigned Is64Bit : 1;
39
40private:
41  MCAsmParser &getParser() const { return Parser; }
42
43  MCAsmLexer &getLexer() const { return Parser.getLexer(); }
44
45  bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
46
47  X86Operand *ParseOperand();
48  X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
49
50  bool ParseDirectiveWord(unsigned Size, SMLoc L);
51
52  bool MatchAndEmitInstruction(SMLoc IDLoc,
53                               SmallVectorImpl<MCParsedAsmOperand*> &Operands,
54                               MCStreamer &Out);
55
56  /// @name Auto-generated Matcher Functions
57  /// {
58
59#define GET_ASSEMBLER_HEADER
60#include "X86GenAsmMatcher.inc"
61
62  /// }
63
64public:
65  X86ATTAsmParser(const Target &T, MCAsmParser &parser, TargetMachine &TM)
66    : TargetAsmParser(T), Parser(parser), TM(TM) {
67
68    // Initialize the set of available features.
69    setAvailableFeatures(ComputeAvailableFeatures(
70                           &TM.getSubtarget<X86Subtarget>()));
71  }
72  virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
73
74  virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
75                                SmallVectorImpl<MCParsedAsmOperand*> &Operands);
76
77  virtual bool ParseDirective(AsmToken DirectiveID);
78};
79
80class X86_32ATTAsmParser : public X86ATTAsmParser {
81public:
82  X86_32ATTAsmParser(const Target &T, MCAsmParser &Parser, TargetMachine &TM)
83    : X86ATTAsmParser(T, Parser, TM) {
84    Is64Bit = false;
85  }
86};
87
88class X86_64ATTAsmParser : public X86ATTAsmParser {
89public:
90  X86_64ATTAsmParser(const Target &T, MCAsmParser &Parser, TargetMachine &TM)
91    : X86ATTAsmParser(T, Parser, TM) {
92    Is64Bit = true;
93  }
94};
95
96} // end anonymous namespace
97
98/// @name Auto-generated Match Functions
99/// {
100
101static unsigned MatchRegisterName(StringRef Name);
102
103/// }
104
105namespace {
106
107/// X86Operand - Instances of this class represent a parsed X86 machine
108/// instruction.
109struct X86Operand : public MCParsedAsmOperand {
110  enum KindTy {
111    Token,
112    Register,
113    Immediate,
114    Memory
115  } Kind;
116
117  SMLoc StartLoc, EndLoc;
118
119  union {
120    struct {
121      const char *Data;
122      unsigned Length;
123    } Tok;
124
125    struct {
126      unsigned RegNo;
127    } Reg;
128
129    struct {
130      const MCExpr *Val;
131    } Imm;
132
133    struct {
134      unsigned SegReg;
135      const MCExpr *Disp;
136      unsigned BaseReg;
137      unsigned IndexReg;
138      unsigned Scale;
139    } Mem;
140  };
141
142  X86Operand(KindTy K, SMLoc Start, SMLoc End)
143    : Kind(K), StartLoc(Start), EndLoc(End) {}
144
145  /// getStartLoc - Get the location of the first token of this operand.
146  SMLoc getStartLoc() const { return StartLoc; }
147  /// getEndLoc - Get the location of the last token of this operand.
148  SMLoc getEndLoc() const { return EndLoc; }
149
150  virtual void dump(raw_ostream &OS) const {}
151
152  StringRef getToken() const {
153    assert(Kind == Token && "Invalid access!");
154    return StringRef(Tok.Data, Tok.Length);
155  }
156  void setTokenValue(StringRef Value) {
157    assert(Kind == Token && "Invalid access!");
158    Tok.Data = Value.data();
159    Tok.Length = Value.size();
160  }
161
162  unsigned getReg() const {
163    assert(Kind == Register && "Invalid access!");
164    return Reg.RegNo;
165  }
166
167  const MCExpr *getImm() const {
168    assert(Kind == Immediate && "Invalid access!");
169    return Imm.Val;
170  }
171
172  const MCExpr *getMemDisp() const {
173    assert(Kind == Memory && "Invalid access!");
174    return Mem.Disp;
175  }
176  unsigned getMemSegReg() const {
177    assert(Kind == Memory && "Invalid access!");
178    return Mem.SegReg;
179  }
180  unsigned getMemBaseReg() const {
181    assert(Kind == Memory && "Invalid access!");
182    return Mem.BaseReg;
183  }
184  unsigned getMemIndexReg() const {
185    assert(Kind == Memory && "Invalid access!");
186    return Mem.IndexReg;
187  }
188  unsigned getMemScale() const {
189    assert(Kind == Memory && "Invalid access!");
190    return Mem.Scale;
191  }
192
193  bool isToken() const {return Kind == Token; }
194
195  bool isImm() const { return Kind == Immediate; }
196
197  bool isImmSExti16i8() const {
198    if (!isImm())
199      return false;
200
201    // If this isn't a constant expr, just assume it fits and let relaxation
202    // handle it.
203    const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
204    if (!CE)
205      return true;
206
207    // Otherwise, check the value is in a range that makes sense for this
208    // extension.
209    uint64_t Value = CE->getValue();
210    return ((                                  Value <= 0x000000000000007FULL)||
211            (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
212            (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
213  }
214  bool isImmSExti32i8() const {
215    if (!isImm())
216      return false;
217
218    // If this isn't a constant expr, just assume it fits and let relaxation
219    // handle it.
220    const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
221    if (!CE)
222      return true;
223
224    // Otherwise, check the value is in a range that makes sense for this
225    // extension.
226    uint64_t Value = CE->getValue();
227    return ((                                  Value <= 0x000000000000007FULL)||
228            (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
229            (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
230  }
231  bool isImmSExti64i8() const {
232    if (!isImm())
233      return false;
234
235    // If this isn't a constant expr, just assume it fits and let relaxation
236    // handle it.
237    const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
238    if (!CE)
239      return true;
240
241    // Otherwise, check the value is in a range that makes sense for this
242    // extension.
243    uint64_t Value = CE->getValue();
244    return ((                                  Value <= 0x000000000000007FULL)||
245            (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
246  }
247  bool isImmSExti64i32() const {
248    if (!isImm())
249      return false;
250
251    // If this isn't a constant expr, just assume it fits and let relaxation
252    // handle it.
253    const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
254    if (!CE)
255      return true;
256
257    // Otherwise, check the value is in a range that makes sense for this
258    // extension.
259    uint64_t Value = CE->getValue();
260    return ((                                  Value <= 0x000000007FFFFFFFULL)||
261            (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
262  }
263
264  bool isMem() const { return Kind == Memory; }
265
266  bool isAbsMem() const {
267    return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
268      !getMemIndexReg() && getMemScale() == 1;
269  }
270
271  bool isReg() const { return Kind == Register; }
272
273  void addExpr(MCInst &Inst, const MCExpr *Expr) const {
274    // Add as immediates when possible.
275    if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
276      Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
277    else
278      Inst.addOperand(MCOperand::CreateExpr(Expr));
279  }
280
281  void addRegOperands(MCInst &Inst, unsigned N) const {
282    assert(N == 1 && "Invalid number of operands!");
283    Inst.addOperand(MCOperand::CreateReg(getReg()));
284  }
285
286  void addImmOperands(MCInst &Inst, unsigned N) const {
287    assert(N == 1 && "Invalid number of operands!");
288    addExpr(Inst, getImm());
289  }
290
291  void addMemOperands(MCInst &Inst, unsigned N) const {
292    assert((N == 5) && "Invalid number of operands!");
293    Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
294    Inst.addOperand(MCOperand::CreateImm(getMemScale()));
295    Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
296    addExpr(Inst, getMemDisp());
297    Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
298  }
299
300  void addAbsMemOperands(MCInst &Inst, unsigned N) const {
301    assert((N == 1) && "Invalid number of operands!");
302    Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
303  }
304
305  static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
306    X86Operand *Res = new X86Operand(Token, Loc, Loc);
307    Res->Tok.Data = Str.data();
308    Res->Tok.Length = Str.size();
309    return Res;
310  }
311
312  static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
313    X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
314    Res->Reg.RegNo = RegNo;
315    return Res;
316  }
317
318  static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
319    X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
320    Res->Imm.Val = Val;
321    return Res;
322  }
323
324  /// Create an absolute memory operand.
325  static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
326                               SMLoc EndLoc) {
327    X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
328    Res->Mem.SegReg   = 0;
329    Res->Mem.Disp     = Disp;
330    Res->Mem.BaseReg  = 0;
331    Res->Mem.IndexReg = 0;
332    Res->Mem.Scale    = 1;
333    return Res;
334  }
335
336  /// Create a generalized memory operand.
337  static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
338                               unsigned BaseReg, unsigned IndexReg,
339                               unsigned Scale, SMLoc StartLoc, SMLoc EndLoc) {
340    // We should never just have a displacement, that should be parsed as an
341    // absolute memory operand.
342    assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
343
344    // The scale should always be one of {1,2,4,8}.
345    assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
346           "Invalid scale!");
347    X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
348    Res->Mem.SegReg   = SegReg;
349    Res->Mem.Disp     = Disp;
350    Res->Mem.BaseReg  = BaseReg;
351    Res->Mem.IndexReg = IndexReg;
352    Res->Mem.Scale    = Scale;
353    return Res;
354  }
355};
356
357} // end anonymous namespace.
358
359
360bool X86ATTAsmParser::ParseRegister(unsigned &RegNo,
361                                    SMLoc &StartLoc, SMLoc &EndLoc) {
362  RegNo = 0;
363  const AsmToken &TokPercent = Parser.getTok();
364  assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
365  StartLoc = TokPercent.getLoc();
366  Parser.Lex(); // Eat percent token.
367
368  const AsmToken &Tok = Parser.getTok();
369  if (Tok.isNot(AsmToken::Identifier))
370    return Error(Tok.getLoc(), "invalid register name");
371
372  // FIXME: Validate register for the current architecture; we have to do
373  // validation later, so maybe there is no need for this here.
374  RegNo = MatchRegisterName(Tok.getString());
375
376  // If the match failed, try the register name as lowercase.
377  if (RegNo == 0)
378    RegNo = MatchRegisterName(LowercaseString(Tok.getString()));
379
380  // FIXME: This should be done using Requires<In32BitMode> and
381  // Requires<In64BitMode> so "eiz" usage in 64-bit instructions
382  // can be also checked.
383  if (RegNo == X86::RIZ && !Is64Bit)
384    return Error(Tok.getLoc(), "riz register in 64-bit mode only");
385
386  // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
387  if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
388    RegNo = X86::ST0;
389    EndLoc = Tok.getLoc();
390    Parser.Lex(); // Eat 'st'
391
392    // Check to see if we have '(4)' after %st.
393    if (getLexer().isNot(AsmToken::LParen))
394      return false;
395    // Lex the paren.
396    getParser().Lex();
397
398    const AsmToken &IntTok = Parser.getTok();
399    if (IntTok.isNot(AsmToken::Integer))
400      return Error(IntTok.getLoc(), "expected stack index");
401    switch (IntTok.getIntVal()) {
402    case 0: RegNo = X86::ST0; break;
403    case 1: RegNo = X86::ST1; break;
404    case 2: RegNo = X86::ST2; break;
405    case 3: RegNo = X86::ST3; break;
406    case 4: RegNo = X86::ST4; break;
407    case 5: RegNo = X86::ST5; break;
408    case 6: RegNo = X86::ST6; break;
409    case 7: RegNo = X86::ST7; break;
410    default: return Error(IntTok.getLoc(), "invalid stack index");
411    }
412
413    if (getParser().Lex().isNot(AsmToken::RParen))
414      return Error(Parser.getTok().getLoc(), "expected ')'");
415
416    EndLoc = Tok.getLoc();
417    Parser.Lex(); // Eat ')'
418    return false;
419  }
420
421  // If this is "db[0-7]", match it as an alias
422  // for dr[0-7].
423  if (RegNo == 0 && Tok.getString().size() == 3 &&
424      Tok.getString().startswith("db")) {
425    switch (Tok.getString()[2]) {
426    case '0': RegNo = X86::DR0; break;
427    case '1': RegNo = X86::DR1; break;
428    case '2': RegNo = X86::DR2; break;
429    case '3': RegNo = X86::DR3; break;
430    case '4': RegNo = X86::DR4; break;
431    case '5': RegNo = X86::DR5; break;
432    case '6': RegNo = X86::DR6; break;
433    case '7': RegNo = X86::DR7; break;
434    }
435
436    if (RegNo != 0) {
437      EndLoc = Tok.getLoc();
438      Parser.Lex(); // Eat it.
439      return false;
440    }
441  }
442
443  if (RegNo == 0)
444    return Error(Tok.getLoc(), "invalid register name");
445
446  EndLoc = Tok.getLoc();
447  Parser.Lex(); // Eat identifier token.
448  return false;
449}
450
451X86Operand *X86ATTAsmParser::ParseOperand() {
452  switch (getLexer().getKind()) {
453  default:
454    // Parse a memory operand with no segment register.
455    return ParseMemOperand(0, Parser.getTok().getLoc());
456  case AsmToken::Percent: {
457    // Read the register.
458    unsigned RegNo;
459    SMLoc Start, End;
460    if (ParseRegister(RegNo, Start, End)) return 0;
461    if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
462      Error(Start, "eiz and riz can only be used as index registers");
463      return 0;
464    }
465
466    // If this is a segment register followed by a ':', then this is the start
467    // of a memory reference, otherwise this is a normal register reference.
468    if (getLexer().isNot(AsmToken::Colon))
469      return X86Operand::CreateReg(RegNo, Start, End);
470
471
472    getParser().Lex(); // Eat the colon.
473    return ParseMemOperand(RegNo, Start);
474  }
475  case AsmToken::Dollar: {
476    // $42 -> immediate.
477    SMLoc Start = Parser.getTok().getLoc(), End;
478    Parser.Lex();
479    const MCExpr *Val;
480    if (getParser().ParseExpression(Val, End))
481      return 0;
482    return X86Operand::CreateImm(Val, Start, End);
483  }
484  }
485}
486
487/// ParseMemOperand: segment: disp(basereg, indexreg, scale).  The '%ds:' prefix
488/// has already been parsed if present.
489X86Operand *X86ATTAsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
490
491  // We have to disambiguate a parenthesized expression "(4+5)" from the start
492  // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)".  The
493  // only way to do this without lookahead is to eat the '(' and see what is
494  // after it.
495  const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
496  if (getLexer().isNot(AsmToken::LParen)) {
497    SMLoc ExprEnd;
498    if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
499
500    // After parsing the base expression we could either have a parenthesized
501    // memory address or not.  If not, return now.  If so, eat the (.
502    if (getLexer().isNot(AsmToken::LParen)) {
503      // Unless we have a segment register, treat this as an immediate.
504      if (SegReg == 0)
505        return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
506      return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
507    }
508
509    // Eat the '('.
510    Parser.Lex();
511  } else {
512    // Okay, we have a '('.  We don't know if this is an expression or not, but
513    // so we have to eat the ( to see beyond it.
514    SMLoc LParenLoc = Parser.getTok().getLoc();
515    Parser.Lex(); // Eat the '('.
516
517    if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
518      // Nothing to do here, fall into the code below with the '(' part of the
519      // memory operand consumed.
520    } else {
521      SMLoc ExprEnd;
522
523      // It must be an parenthesized expression, parse it now.
524      if (getParser().ParseParenExpression(Disp, ExprEnd))
525        return 0;
526
527      // After parsing the base expression we could either have a parenthesized
528      // memory address or not.  If not, return now.  If so, eat the (.
529      if (getLexer().isNot(AsmToken::LParen)) {
530        // Unless we have a segment register, treat this as an immediate.
531        if (SegReg == 0)
532          return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
533        return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
534      }
535
536      // Eat the '('.
537      Parser.Lex();
538    }
539  }
540
541  // If we reached here, then we just ate the ( of the memory operand.  Process
542  // the rest of the memory operand.
543  unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
544
545  if (getLexer().is(AsmToken::Percent)) {
546    SMLoc L;
547    if (ParseRegister(BaseReg, L, L)) return 0;
548    if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
549      Error(L, "eiz and riz can only be used as index registers");
550      return 0;
551    }
552  }
553
554  if (getLexer().is(AsmToken::Comma)) {
555    Parser.Lex(); // Eat the comma.
556
557    // Following the comma we should have either an index register, or a scale
558    // value. We don't support the later form, but we want to parse it
559    // correctly.
560    //
561    // Not that even though it would be completely consistent to support syntax
562    // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
563    if (getLexer().is(AsmToken::Percent)) {
564      SMLoc L;
565      if (ParseRegister(IndexReg, L, L)) return 0;
566
567      if (getLexer().isNot(AsmToken::RParen)) {
568        // Parse the scale amount:
569        //  ::= ',' [scale-expression]
570        if (getLexer().isNot(AsmToken::Comma)) {
571          Error(Parser.getTok().getLoc(),
572                "expected comma in scale expression");
573          return 0;
574        }
575        Parser.Lex(); // Eat the comma.
576
577        if (getLexer().isNot(AsmToken::RParen)) {
578          SMLoc Loc = Parser.getTok().getLoc();
579
580          int64_t ScaleVal;
581          if (getParser().ParseAbsoluteExpression(ScaleVal))
582            return 0;
583
584          // Validate the scale amount.
585          if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
586            Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
587            return 0;
588          }
589          Scale = (unsigned)ScaleVal;
590        }
591      }
592    } else if (getLexer().isNot(AsmToken::RParen)) {
593      // A scale amount without an index is ignored.
594      // index.
595      SMLoc Loc = Parser.getTok().getLoc();
596
597      int64_t Value;
598      if (getParser().ParseAbsoluteExpression(Value))
599        return 0;
600
601      if (Value != 1)
602        Warning(Loc, "scale factor without index register is ignored");
603      Scale = 1;
604    }
605  }
606
607  // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
608  if (getLexer().isNot(AsmToken::RParen)) {
609    Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
610    return 0;
611  }
612  SMLoc MemEnd = Parser.getTok().getLoc();
613  Parser.Lex(); // Eat the ')'.
614
615  return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
616                               MemStart, MemEnd);
617}
618
619bool X86ATTAsmParser::
620ParseInstruction(StringRef Name, SMLoc NameLoc,
621                 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
622  StringRef PatchedName = Name;
623
624  // FIXME: Hack to recognize setneb as setne.
625  if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
626      PatchedName != "setb" && PatchedName != "setnb")
627    PatchedName = PatchedName.substr(0, Name.size()-1);
628
629  // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
630  const MCExpr *ExtraImmOp = 0;
631  if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
632      (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
633       PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
634    bool IsVCMP = PatchedName.startswith("vcmp");
635    unsigned SSECCIdx = IsVCMP ? 4 : 3;
636    unsigned SSEComparisonCode = StringSwitch<unsigned>(
637      PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
638      .Case("eq",          0)
639      .Case("lt",          1)
640      .Case("le",          2)
641      .Case("unord",       3)
642      .Case("neq",         4)
643      .Case("nlt",         5)
644      .Case("nle",         6)
645      .Case("ord",         7)
646      .Case("eq_uq",       8)
647      .Case("nge",         9)
648      .Case("ngt",      0x0A)
649      .Case("false",    0x0B)
650      .Case("neq_oq",   0x0C)
651      .Case("ge",       0x0D)
652      .Case("gt",       0x0E)
653      .Case("true",     0x0F)
654      .Case("eq_os",    0x10)
655      .Case("lt_oq",    0x11)
656      .Case("le_oq",    0x12)
657      .Case("unord_s",  0x13)
658      .Case("neq_us",   0x14)
659      .Case("nlt_uq",   0x15)
660      .Case("nle_uq",   0x16)
661      .Case("ord_s",    0x17)
662      .Case("eq_us",    0x18)
663      .Case("nge_uq",   0x19)
664      .Case("ngt_uq",   0x1A)
665      .Case("false_os", 0x1B)
666      .Case("neq_os",   0x1C)
667      .Case("ge_oq",    0x1D)
668      .Case("gt_oq",    0x1E)
669      .Case("true_us",  0x1F)
670      .Default(~0U);
671    if (SSEComparisonCode != ~0U) {
672      ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
673                                          getParser().getContext());
674      if (PatchedName.endswith("ss")) {
675        PatchedName = IsVCMP ? "vcmpss" : "cmpss";
676      } else if (PatchedName.endswith("sd")) {
677        PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
678      } else if (PatchedName.endswith("ps")) {
679        PatchedName = IsVCMP ? "vcmpps" : "cmpps";
680      } else {
681        assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
682        PatchedName = IsVCMP ? "vcmppd" : "cmppd";
683      }
684    }
685  }
686
687  // FIXME: Hack to recognize vpclmul<src1_quadword, src2_quadword>dq
688  if (PatchedName.startswith("vpclmul")) {
689    unsigned CLMULQuadWordSelect = StringSwitch<unsigned>(
690      PatchedName.slice(7, PatchedName.size() - 2))
691      .Case("lqlq", 0x00) // src1[63:0],   src2[63:0]
692      .Case("hqlq", 0x01) // src1[127:64], src2[63:0]
693      .Case("lqhq", 0x10) // src1[63:0],   src2[127:64]
694      .Case("hqhq", 0x11) // src1[127:64], src2[127:64]
695      .Default(~0U);
696    if (CLMULQuadWordSelect != ~0U) {
697      ExtraImmOp = MCConstantExpr::Create(CLMULQuadWordSelect,
698                                          getParser().getContext());
699      assert(PatchedName.endswith("dq") && "Unexpected mnemonic!");
700      PatchedName = "vpclmulqdq";
701    }
702  }
703
704  Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
705
706  if (ExtraImmOp)
707    Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
708
709
710  // Determine whether this is an instruction prefix.
711  bool isPrefix =
712    Name == "lock" || Name == "rep" ||
713    Name == "repe" || Name == "repz" ||
714    Name == "repne" || Name == "repnz" ||
715    Name == "rex64" || Name == "data16";
716
717
718  // This does the actual operand parsing.  Don't parse any more if we have a
719  // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
720  // just want to parse the "lock" as the first instruction and the "incl" as
721  // the next one.
722  if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
723
724    // Parse '*' modifier.
725    if (getLexer().is(AsmToken::Star)) {
726      SMLoc Loc = Parser.getTok().getLoc();
727      Operands.push_back(X86Operand::CreateToken("*", Loc));
728      Parser.Lex(); // Eat the star.
729    }
730
731    // Read the first operand.
732    if (X86Operand *Op = ParseOperand())
733      Operands.push_back(Op);
734    else {
735      Parser.EatToEndOfStatement();
736      return true;
737    }
738
739    while (getLexer().is(AsmToken::Comma)) {
740      Parser.Lex();  // Eat the comma.
741
742      // Parse and remember the operand.
743      if (X86Operand *Op = ParseOperand())
744        Operands.push_back(Op);
745      else {
746        Parser.EatToEndOfStatement();
747        return true;
748      }
749    }
750
751    if (getLexer().isNot(AsmToken::EndOfStatement)) {
752      SMLoc Loc = getLexer().getLoc();
753      Parser.EatToEndOfStatement();
754      return Error(Loc, "unexpected token in argument list");
755    }
756  }
757
758  if (getLexer().is(AsmToken::EndOfStatement))
759    Parser.Lex(); // Consume the EndOfStatement
760  else if (isPrefix && getLexer().is(AsmToken::Slash))
761    Parser.Lex(); // Consume the prefix separator Slash
762
763  // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
764  // "outb %al, %dx".  Out doesn't take a memory form, but this is a widely
765  // documented form in various unofficial manuals, so a lot of code uses it.
766  if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
767      Operands.size() == 3) {
768    X86Operand &Op = *(X86Operand*)Operands.back();
769    if (Op.isMem() && Op.Mem.SegReg == 0 &&
770        isa<MCConstantExpr>(Op.Mem.Disp) &&
771        cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
772        Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
773      SMLoc Loc = Op.getEndLoc();
774      Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
775      delete &Op;
776    }
777  }
778  // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
779  if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
780      Operands.size() == 3) {
781    X86Operand &Op = *(X86Operand*)Operands.begin()[1];
782    if (Op.isMem() && Op.Mem.SegReg == 0 &&
783        isa<MCConstantExpr>(Op.Mem.Disp) &&
784        cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
785        Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
786      SMLoc Loc = Op.getEndLoc();
787      Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
788      delete &Op;
789    }
790  }
791
792  // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>.  Canonicalize to
793  // "shift <op>".
794  if ((Name.startswith("shr") || Name.startswith("sar") ||
795       Name.startswith("shl") || Name.startswith("sal") ||
796       Name.startswith("rcl") || Name.startswith("rcr") ||
797       Name.startswith("rol") || Name.startswith("ror")) &&
798      Operands.size() == 3) {
799    X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
800    if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
801        cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
802      delete Operands[1];
803      Operands.erase(Operands.begin() + 1);
804    }
805  }
806
807  return false;
808}
809
810bool X86ATTAsmParser::
811MatchAndEmitInstruction(SMLoc IDLoc,
812                        SmallVectorImpl<MCParsedAsmOperand*> &Operands,
813                        MCStreamer &Out) {
814  assert(!Operands.empty() && "Unexpect empty operand list!");
815  X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
816  assert(Op->isToken() && "Leading operand should always be a mnemonic!");
817
818  // First, handle aliases that expand to multiple instructions.
819  // FIXME: This should be replaced with a real .td file alias mechanism.
820  // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
821  // call.
822  if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
823      Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
824      Op->getToken() == "finit" || Op->getToken() == "fsave" ||
825      Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
826    MCInst Inst;
827    Inst.setOpcode(X86::WAIT);
828    Out.EmitInstruction(Inst);
829
830    const char *Repl =
831      StringSwitch<const char*>(Op->getToken())
832        .Case("finit",  "fninit")
833        .Case("fsave",  "fnsave")
834        .Case("fstcw",  "fnstcw")
835        .Case("fstcww",  "fnstcw")
836        .Case("fstenv", "fnstenv")
837        .Case("fstsw",  "fnstsw")
838        .Case("fstsww", "fnstsw")
839        .Case("fclex",  "fnclex")
840        .Default(0);
841    assert(Repl && "Unknown wait-prefixed instruction");
842    delete Operands[0];
843    Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
844  }
845
846  bool WasOriginallyInvalidOperand = false;
847  unsigned OrigErrorInfo;
848  MCInst Inst;
849
850  // First, try a direct match.
851  switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo)) {
852  case Match_Success:
853    Out.EmitInstruction(Inst);
854    return false;
855  case Match_MissingFeature:
856    Error(IDLoc, "instruction requires a CPU feature not currently enabled");
857    return true;
858  case Match_ConversionFail:
859    return Error(IDLoc, "unable to convert operands to instruction");
860  case Match_InvalidOperand:
861    WasOriginallyInvalidOperand = true;
862    break;
863  case Match_MnemonicFail:
864    break;
865  }
866
867  // FIXME: Ideally, we would only attempt suffix matches for things which are
868  // valid prefixes, and we could just infer the right unambiguous
869  // type. However, that requires substantially more matcher support than the
870  // following hack.
871
872  // Change the operand to point to a temporary token.
873  StringRef Base = Op->getToken();
874  SmallString<16> Tmp;
875  Tmp += Base;
876  Tmp += ' ';
877  Op->setTokenValue(Tmp.str());
878
879  // If this instruction starts with an 'f', then it is a floating point stack
880  // instruction.  These come in up to three forms for 32-bit, 64-bit, and
881  // 80-bit floating point, which use the suffixes s,l,t respectively.
882  //
883  // Otherwise, we assume that this may be an integer instruction, which comes
884  // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
885  const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
886
887  // Check for the various suffix matches.
888  Tmp[Base.size()] = Suffixes[0];
889  unsigned ErrorInfoIgnore;
890  MatchResultTy Match1, Match2, Match3, Match4;
891
892  Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
893  Tmp[Base.size()] = Suffixes[1];
894  Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
895  Tmp[Base.size()] = Suffixes[2];
896  Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
897  Tmp[Base.size()] = Suffixes[3];
898  Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
899
900  // Restore the old token.
901  Op->setTokenValue(Base);
902
903  // If exactly one matched, then we treat that as a successful match (and the
904  // instruction will already have been filled in correctly, since the failing
905  // matches won't have modified it).
906  unsigned NumSuccessfulMatches =
907    (Match1 == Match_Success) + (Match2 == Match_Success) +
908    (Match3 == Match_Success) + (Match4 == Match_Success);
909  if (NumSuccessfulMatches == 1) {
910    Out.EmitInstruction(Inst);
911    return false;
912  }
913
914  // Otherwise, the match failed, try to produce a decent error message.
915
916  // If we had multiple suffix matches, then identify this as an ambiguous
917  // match.
918  if (NumSuccessfulMatches > 1) {
919    char MatchChars[4];
920    unsigned NumMatches = 0;
921    if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
922    if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
923    if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
924    if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
925
926    SmallString<126> Msg;
927    raw_svector_ostream OS(Msg);
928    OS << "ambiguous instructions require an explicit suffix (could be ";
929    for (unsigned i = 0; i != NumMatches; ++i) {
930      if (i != 0)
931        OS << ", ";
932      if (i + 1 == NumMatches)
933        OS << "or ";
934      OS << "'" << Base << MatchChars[i] << "'";
935    }
936    OS << ")";
937    Error(IDLoc, OS.str());
938    return true;
939  }
940
941  // Okay, we know that none of the variants matched successfully.
942
943  // If all of the instructions reported an invalid mnemonic, then the original
944  // mnemonic was invalid.
945  if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
946      (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
947    if (!WasOriginallyInvalidOperand) {
948      Error(IDLoc, "invalid instruction mnemonic '" + Base + "'");
949      return true;
950    }
951
952    // Recover location info for the operand if we know which was the problem.
953    SMLoc ErrorLoc = IDLoc;
954    if (OrigErrorInfo != ~0U) {
955      if (OrigErrorInfo >= Operands.size())
956        return Error(IDLoc, "too few operands for instruction");
957
958      ErrorLoc = ((X86Operand*)Operands[OrigErrorInfo])->getStartLoc();
959      if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
960    }
961
962    return Error(ErrorLoc, "invalid operand for instruction");
963  }
964
965  // If one instruction matched with a missing feature, report this as a
966  // missing feature.
967  if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
968      (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
969    Error(IDLoc, "instruction requires a CPU feature not currently enabled");
970    return true;
971  }
972
973  // If one instruction matched with an invalid operand, report this as an
974  // operand failure.
975  if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
976      (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
977    Error(IDLoc, "invalid operand for instruction");
978    return true;
979  }
980
981  // If all of these were an outright failure, report it in a useless way.
982  // FIXME: We should give nicer diagnostics about the exact failure.
983  Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
984  return true;
985}
986
987
988bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
989  StringRef IDVal = DirectiveID.getIdentifier();
990  if (IDVal == ".word")
991    return ParseDirectiveWord(2, DirectiveID.getLoc());
992  return true;
993}
994
995/// ParseDirectiveWord
996///  ::= .word [ expression (, expression)* ]
997bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
998  if (getLexer().isNot(AsmToken::EndOfStatement)) {
999    for (;;) {
1000      const MCExpr *Value;
1001      if (getParser().ParseExpression(Value))
1002        return true;
1003
1004      getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1005
1006      if (getLexer().is(AsmToken::EndOfStatement))
1007        break;
1008
1009      // FIXME: Improve diagnostic.
1010      if (getLexer().isNot(AsmToken::Comma))
1011        return Error(L, "unexpected token in directive");
1012      Parser.Lex();
1013    }
1014  }
1015
1016  Parser.Lex();
1017  return false;
1018}
1019
1020
1021
1022
1023extern "C" void LLVMInitializeX86AsmLexer();
1024
1025// Force static initialization.
1026extern "C" void LLVMInitializeX86AsmParser() {
1027  RegisterAsmParser<X86_32ATTAsmParser> X(TheX86_32Target);
1028  RegisterAsmParser<X86_64ATTAsmParser> Y(TheX86_64Target);
1029  LLVMInitializeX86AsmLexer();
1030}
1031
1032#define GET_REGISTER_MATCHER
1033#define GET_MATCHER_IMPLEMENTATION
1034#include "X86GenAsmMatcher.inc"
1035