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