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