Intel syntax: Parse memory operand with empty base reg, e.g. DWORD PTR [4*RDI]
[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 "MCTargetDesc/X86BaseInfo.h"
11 #include "llvm/MC/MCTargetAsmParser.h"
12 #include "llvm/MC/MCStreamer.h"
13 #include "llvm/MC/MCExpr.h"
14 #include "llvm/MC/MCInst.h"
15 #include "llvm/MC/MCRegisterInfo.h"
16 #include "llvm/MC/MCSubtargetInfo.h"
17 #include "llvm/MC/MCParser/MCAsmLexer.h"
18 #include "llvm/MC/MCParser/MCAsmParser.h"
19 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/TargetRegistry.h"
27 #include "llvm/Support/raw_ostream.h"
28
29 using namespace llvm;
30
31 namespace {
32 struct X86Operand;
33
34 class X86AsmParser : public MCTargetAsmParser {
35   MCSubtargetInfo &STI;
36   MCAsmParser &Parser;
37
38 private:
39   MCAsmParser &getParser() const { return Parser; }
40
41   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
42
43   bool Error(SMLoc L, const Twine &Msg,
44              ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) {
45     return Parser.Error(L, Msg, Ranges);
46   }
47
48   X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
49     Error(Loc, Msg);
50     return 0;
51   }
52
53   X86Operand *ParseOperand();
54   X86Operand *ParseATTOperand();
55   X86Operand *ParseIntelOperand();
56   X86Operand *ParseIntelMemOperand();
57   X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
58   X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
59
60   bool ParseDirectiveWord(unsigned Size, SMLoc L);
61   bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
62
63   bool processInstruction(MCInst &Inst,
64                           const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
65
66   bool MatchAndEmitInstruction(SMLoc IDLoc,
67                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
68                                MCStreamer &Out);
69
70   /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
71   /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
72   bool isSrcOp(X86Operand &Op);
73
74   /// isDstOp - Returns true if operand is either %es:(%rdi) in 64bit mode
75   /// or %es:(%edi) in 32bit mode.
76   bool isDstOp(X86Operand &Op);
77
78   bool is64BitMode() const {
79     // FIXME: Can tablegen auto-generate this?
80     return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
81   }
82   void SwitchMode() {
83     unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
84     setAvailableFeatures(FB);
85   }
86
87   /// @name Auto-generated Matcher Functions
88   /// {
89
90 #define GET_ASSEMBLER_HEADER
91 #include "X86GenAsmMatcher.inc"
92
93   /// }
94
95 public:
96   X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
97     : MCTargetAsmParser(), STI(sti), Parser(parser) {
98
99     // Initialize the set of available features.
100     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
101   }
102   virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
103
104   virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
105                                 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
106
107   virtual bool ParseDirective(AsmToken DirectiveID);
108 };
109 } // end anonymous namespace
110
111 /// @name Auto-generated Match Functions
112 /// {
113
114 static unsigned MatchRegisterName(StringRef Name);
115
116 /// }
117
118 static  bool isImmSExti16i8Value(uint64_t Value) {
119   return ((                                  Value <= 0x000000000000007FULL)||
120           (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
121           (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
122 }
123
124 static bool isImmSExti32i8Value(uint64_t Value) {
125   return ((                                  Value <= 0x000000000000007FULL)||
126           (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
127           (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
128 }
129
130 static bool isImmZExtu32u8Value(uint64_t Value) {
131     return (Value <= 0x00000000000000FFULL);
132 }
133
134 static bool isImmSExti64i8Value(uint64_t Value) {
135   return ((                                  Value <= 0x000000000000007FULL)||
136           (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
137 }
138
139 static bool isImmSExti64i32Value(uint64_t Value) {
140   return ((                                  Value <= 0x000000007FFFFFFFULL)||
141           (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
142 }
143 namespace {
144
145 /// X86Operand - Instances of this class represent a parsed X86 machine
146 /// instruction.
147 struct X86Operand : public MCParsedAsmOperand {
148   enum KindTy {
149     Token,
150     Register,
151     Immediate,
152     Memory
153   } Kind;
154
155   SMLoc StartLoc, EndLoc;
156
157   union {
158     struct {
159       const char *Data;
160       unsigned Length;
161     } Tok;
162
163     struct {
164       unsigned RegNo;
165     } Reg;
166
167     struct {
168       const MCExpr *Val;
169     } Imm;
170
171     struct {
172       unsigned SegReg;
173       const MCExpr *Disp;
174       unsigned BaseReg;
175       unsigned IndexReg;
176       unsigned Scale;
177       unsigned Size;
178     } Mem;
179   };
180
181   X86Operand(KindTy K, SMLoc Start, SMLoc End)
182     : Kind(K), StartLoc(Start), EndLoc(End) {}
183
184   /// getStartLoc - Get the location of the first token of this operand.
185   SMLoc getStartLoc() const { return StartLoc; }
186   /// getEndLoc - Get the location of the last token of this operand.
187   SMLoc getEndLoc() const { return EndLoc; }
188   
189   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
190
191   virtual void print(raw_ostream &OS) const {}
192
193   StringRef getToken() const {
194     assert(Kind == Token && "Invalid access!");
195     return StringRef(Tok.Data, Tok.Length);
196   }
197   void setTokenValue(StringRef Value) {
198     assert(Kind == Token && "Invalid access!");
199     Tok.Data = Value.data();
200     Tok.Length = Value.size();
201   }
202
203   unsigned getReg() const {
204     assert(Kind == Register && "Invalid access!");
205     return Reg.RegNo;
206   }
207
208   const MCExpr *getImm() const {
209     assert(Kind == Immediate && "Invalid access!");
210     return Imm.Val;
211   }
212
213   const MCExpr *getMemDisp() const {
214     assert(Kind == Memory && "Invalid access!");
215     return Mem.Disp;
216   }
217   unsigned getMemSegReg() const {
218     assert(Kind == Memory && "Invalid access!");
219     return Mem.SegReg;
220   }
221   unsigned getMemBaseReg() const {
222     assert(Kind == Memory && "Invalid access!");
223     return Mem.BaseReg;
224   }
225   unsigned getMemIndexReg() const {
226     assert(Kind == Memory && "Invalid access!");
227     return Mem.IndexReg;
228   }
229   unsigned getMemScale() const {
230     assert(Kind == Memory && "Invalid access!");
231     return Mem.Scale;
232   }
233
234   bool isToken() const {return Kind == Token; }
235
236   bool isImm() const { return Kind == Immediate; }
237
238   bool isImmSExti16i8() const {
239     if (!isImm())
240       return false;
241
242     // If this isn't a constant expr, just assume it fits and let relaxation
243     // handle it.
244     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
245     if (!CE)
246       return true;
247
248     // Otherwise, check the value is in a range that makes sense for this
249     // extension.
250     return isImmSExti16i8Value(CE->getValue());
251   }
252   bool isImmSExti32i8() const {
253     if (!isImm())
254       return false;
255
256     // If this isn't a constant expr, just assume it fits and let relaxation
257     // handle it.
258     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
259     if (!CE)
260       return true;
261
262     // Otherwise, check the value is in a range that makes sense for this
263     // extension.
264     return isImmSExti32i8Value(CE->getValue());
265   }
266   bool isImmZExtu32u8() const {
267     if (!isImm())
268       return false;
269
270     // If this isn't a constant expr, just assume it fits and let relaxation
271     // handle it.
272     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
273     if (!CE)
274       return true;
275
276     // Otherwise, check the value is in a range that makes sense for this
277     // extension.
278     return isImmZExtu32u8Value(CE->getValue());
279   }
280   bool isImmSExti64i8() const {
281     if (!isImm())
282       return false;
283
284     // If this isn't a constant expr, just assume it fits and let relaxation
285     // handle it.
286     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
287     if (!CE)
288       return true;
289
290     // Otherwise, check the value is in a range that makes sense for this
291     // extension.
292     return isImmSExti64i8Value(CE->getValue());
293   }
294   bool isImmSExti64i32() const {
295     if (!isImm())
296       return false;
297
298     // If this isn't a constant expr, just assume it fits and let relaxation
299     // handle it.
300     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
301     if (!CE)
302       return true;
303
304     // Otherwise, check the value is in a range that makes sense for this
305     // extension.
306     return isImmSExti64i32Value(CE->getValue());
307   }
308
309   bool isMem() const { return Kind == Memory; }
310   bool isMem8() const { 
311     return Kind == Memory && (!Mem.Size || Mem.Size == 8);
312   }
313   bool isMem16() const { 
314     return Kind == Memory && (!Mem.Size || Mem.Size == 16);
315   }
316   bool isMem32() const { 
317     return Kind == Memory && (!Mem.Size || Mem.Size == 32);
318   }
319   bool isMem64() const { 
320     return Kind == Memory && (!Mem.Size || Mem.Size == 64);
321   }
322   bool isMem80() const { 
323     return Kind == Memory && (!Mem.Size || Mem.Size == 80);
324   }
325   bool isMem128() const { 
326     return Kind == Memory && (!Mem.Size || Mem.Size == 128);
327   }
328   bool isMem256() const { 
329     return Kind == Memory && (!Mem.Size || Mem.Size == 256);
330   }
331
332   bool isAbsMem() const {
333     return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
334       !getMemIndexReg() && getMemScale() == 1;
335   }
336
337   bool isReg() const { return Kind == Register; }
338
339   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
340     // Add as immediates when possible.
341     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
342       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
343     else
344       Inst.addOperand(MCOperand::CreateExpr(Expr));
345   }
346
347   void addRegOperands(MCInst &Inst, unsigned N) const {
348     assert(N == 1 && "Invalid number of operands!");
349     Inst.addOperand(MCOperand::CreateReg(getReg()));
350   }
351
352   void addImmOperands(MCInst &Inst, unsigned N) const {
353     assert(N == 1 && "Invalid number of operands!");
354     addExpr(Inst, getImm());
355   }
356
357   void addMem8Operands(MCInst &Inst, unsigned N) const { 
358     addMemOperands(Inst, N); 
359   }
360   void addMem16Operands(MCInst &Inst, unsigned N) const { 
361     addMemOperands(Inst, N); 
362   }
363   void addMem32Operands(MCInst &Inst, unsigned N) const { 
364     addMemOperands(Inst, N); 
365   }
366   void addMem64Operands(MCInst &Inst, unsigned N) const { 
367     addMemOperands(Inst, N); 
368   }
369   void addMem80Operands(MCInst &Inst, unsigned N) const { 
370     addMemOperands(Inst, N); 
371   }
372   void addMem128Operands(MCInst &Inst, unsigned N) const { 
373     addMemOperands(Inst, N); 
374   }
375   void addMem256Operands(MCInst &Inst, unsigned N) const { 
376     addMemOperands(Inst, N); 
377   }
378
379   void addMemOperands(MCInst &Inst, unsigned N) const {
380     assert((N == 5) && "Invalid number of operands!");
381     Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
382     Inst.addOperand(MCOperand::CreateImm(getMemScale()));
383     Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
384     addExpr(Inst, getMemDisp());
385     Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
386   }
387
388   void addAbsMemOperands(MCInst &Inst, unsigned N) const {
389     assert((N == 1) && "Invalid number of operands!");
390     Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
391   }
392
393   static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
394     SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
395     X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
396     Res->Tok.Data = Str.data();
397     Res->Tok.Length = Str.size();
398     return Res;
399   }
400
401   static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
402     X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
403     Res->Reg.RegNo = RegNo;
404     return Res;
405   }
406
407   static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
408     X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
409     Res->Imm.Val = Val;
410     return Res;
411   }
412
413   /// Create an absolute memory operand.
414   static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
415                                SMLoc EndLoc, unsigned Size = 0) {
416     X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
417     Res->Mem.SegReg   = 0;
418     Res->Mem.Disp     = Disp;
419     Res->Mem.BaseReg  = 0;
420     Res->Mem.IndexReg = 0;
421     Res->Mem.Scale    = 1;
422     Res->Mem.Size     = Size;
423     return Res;
424   }
425
426   /// Create a generalized memory operand.
427   static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
428                                unsigned BaseReg, unsigned IndexReg,
429                                unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
430                                unsigned Size = 0) {
431     // We should never just have a displacement, that should be parsed as an
432     // absolute memory operand.
433     assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
434
435     // The scale should always be one of {1,2,4,8}.
436     assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
437            "Invalid scale!");
438     X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
439     Res->Mem.SegReg   = SegReg;
440     Res->Mem.Disp     = Disp;
441     Res->Mem.BaseReg  = BaseReg;
442     Res->Mem.IndexReg = IndexReg;
443     Res->Mem.Scale    = Scale;
444     Res->Mem.Size     = Size;
445     return Res;
446   }
447 };
448
449 } // end anonymous namespace.
450
451 bool X86AsmParser::isSrcOp(X86Operand &Op) {
452   unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
453
454   return (Op.isMem() &&
455     (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
456     isa<MCConstantExpr>(Op.Mem.Disp) &&
457     cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
458     Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
459 }
460
461 bool X86AsmParser::isDstOp(X86Operand &Op) {
462   unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
463
464   return Op.isMem() && Op.Mem.SegReg == X86::ES &&
465     isa<MCConstantExpr>(Op.Mem.Disp) &&
466     cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
467     Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
468 }
469
470 bool X86AsmParser::ParseRegister(unsigned &RegNo,
471                                  SMLoc &StartLoc, SMLoc &EndLoc) {
472   RegNo = 0;
473   bool IntelSyntax = getParser().getAssemblerDialect();
474   if (!IntelSyntax) {
475     const AsmToken &TokPercent = Parser.getTok();
476     assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
477     StartLoc = TokPercent.getLoc();
478     Parser.Lex(); // Eat percent token.
479   }
480
481   const AsmToken &Tok = Parser.getTok();
482   if (Tok.isNot(AsmToken::Identifier)) {
483     if (IntelSyntax) return true;
484     return Error(StartLoc, "invalid register name",
485                  SMRange(StartLoc, Tok.getEndLoc()));
486   }
487
488   RegNo = MatchRegisterName(Tok.getString());
489
490   // If the match failed, try the register name as lowercase.
491   if (RegNo == 0)
492     RegNo = MatchRegisterName(Tok.getString().lower());
493
494   if (!is64BitMode()) {
495     // FIXME: This should be done using Requires<In32BitMode> and
496     // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
497     // checked.
498     // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
499     // REX prefix.
500     if (RegNo == X86::RIZ ||
501         X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
502         X86II::isX86_64NonExtLowByteReg(RegNo) ||
503         X86II::isX86_64ExtendedReg(RegNo))
504       return Error(StartLoc, "register %"
505                    + Tok.getString() + " is only available in 64-bit mode",
506                    SMRange(StartLoc, Tok.getEndLoc()));
507   }
508
509   // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
510   if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
511     RegNo = X86::ST0;
512     EndLoc = Tok.getLoc();
513     Parser.Lex(); // Eat 'st'
514
515     // Check to see if we have '(4)' after %st.
516     if (getLexer().isNot(AsmToken::LParen))
517       return false;
518     // Lex the paren.
519     getParser().Lex();
520
521     const AsmToken &IntTok = Parser.getTok();
522     if (IntTok.isNot(AsmToken::Integer))
523       return Error(IntTok.getLoc(), "expected stack index");
524     switch (IntTok.getIntVal()) {
525     case 0: RegNo = X86::ST0; break;
526     case 1: RegNo = X86::ST1; break;
527     case 2: RegNo = X86::ST2; break;
528     case 3: RegNo = X86::ST3; break;
529     case 4: RegNo = X86::ST4; break;
530     case 5: RegNo = X86::ST5; break;
531     case 6: RegNo = X86::ST6; break;
532     case 7: RegNo = X86::ST7; break;
533     default: return Error(IntTok.getLoc(), "invalid stack index");
534     }
535
536     if (getParser().Lex().isNot(AsmToken::RParen))
537       return Error(Parser.getTok().getLoc(), "expected ')'");
538
539     EndLoc = Tok.getLoc();
540     Parser.Lex(); // Eat ')'
541     return false;
542   }
543
544   // If this is "db[0-7]", match it as an alias
545   // for dr[0-7].
546   if (RegNo == 0 && Tok.getString().size() == 3 &&
547       Tok.getString().startswith("db")) {
548     switch (Tok.getString()[2]) {
549     case '0': RegNo = X86::DR0; break;
550     case '1': RegNo = X86::DR1; break;
551     case '2': RegNo = X86::DR2; break;
552     case '3': RegNo = X86::DR3; break;
553     case '4': RegNo = X86::DR4; break;
554     case '5': RegNo = X86::DR5; break;
555     case '6': RegNo = X86::DR6; break;
556     case '7': RegNo = X86::DR7; break;
557     }
558
559     if (RegNo != 0) {
560       EndLoc = Tok.getLoc();
561       Parser.Lex(); // Eat it.
562       return false;
563     }
564   }
565
566   if (RegNo == 0) {
567     if (IntelSyntax) return true;
568     return Error(StartLoc, "invalid register name",
569                  SMRange(StartLoc, Tok.getEndLoc()));
570   }
571
572   EndLoc = Tok.getEndLoc();
573   Parser.Lex(); // Eat identifier token.
574   return false;
575 }
576
577 X86Operand *X86AsmParser::ParseOperand() {
578   if (getParser().getAssemblerDialect())
579     return ParseIntelOperand();
580   return ParseATTOperand();
581 }
582
583 /// getIntelMemOperandSize - Return intel memory operand size.
584 static unsigned getIntelMemOperandSize(StringRef OpStr) {
585   unsigned Size = 0;
586   if (OpStr == "BYTE") Size = 8;
587   if (OpStr == "WORD") Size = 16;
588   if (OpStr == "DWORD") Size = 32;
589   if (OpStr == "QWORD") Size = 64;
590   if (OpStr == "XWORD") Size = 80;
591   if (OpStr == "XMMWORD") Size = 128;
592   if (OpStr == "YMMWORD") Size = 256;
593   return Size;
594 }
595
596 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
597                                                    unsigned Size) {
598   unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
599   SMLoc Start = Parser.getTok().getLoc(), End;
600
601   const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
602   // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
603
604   // Eat '['
605   if (getLexer().isNot(AsmToken::LBrac))
606     return ErrorOperand(Start, "Expected '[' token!");
607   Parser.Lex();
608   
609   if (getLexer().is(AsmToken::Identifier)) {
610     // Parse BaseReg
611     if (ParseRegister(BaseReg, Start, End)) {
612       // Handle '[' 'symbol' ']'
613       const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
614       if (getParser().ParseExpression(Disp, End)) return 0;
615       if (getLexer().isNot(AsmToken::RBrac))
616         return ErrorOperand(Start, "Expected ']' token!");
617       Parser.Lex();
618       return X86Operand::CreateMem(Disp, Start, End, Size);
619     }
620   } else if (getLexer().is(AsmToken::Integer)) {
621       int64_t Val = Parser.getTok().getIntVal();
622       Parser.Lex();
623       SMLoc Loc = Parser.getTok().getLoc();
624       if (getLexer().is(AsmToken::RBrac)) {
625         // Handle '[' number ']'
626         Parser.Lex();
627         return X86Operand::CreateMem(MCConstantExpr::Create(Val, getContext()),
628                                      Start, End, Size);
629       } else if (getLexer().is(AsmToken::Star)) {
630         // Handle '[' Scale*IndexReg ']'
631         Parser.Lex();
632         SMLoc IdxRegLoc = Parser.getTok().getLoc();
633         if (ParseRegister(IndexReg, IdxRegLoc, End))
634           return ErrorOperand(IdxRegLoc, "Expected register");
635         Scale = Val;
636       } else
637         return ErrorOperand(Loc, "Unepxeted token");
638   }
639
640   if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
641     bool isPlus = getLexer().is(AsmToken::Plus);
642     Parser.Lex();
643     SMLoc PlusLoc = Parser.getTok().getLoc();
644     if (getLexer().is(AsmToken::Integer)) {
645       int64_t Val = Parser.getTok().getIntVal();
646       Parser.Lex();
647       if (getLexer().is(AsmToken::Star)) {
648         Parser.Lex();
649         SMLoc IdxRegLoc = Parser.getTok().getLoc();
650         if (ParseRegister(IndexReg, IdxRegLoc, End))
651           return ErrorOperand(IdxRegLoc, "Expected register");
652         Scale = Val;
653       } else if (getLexer().is(AsmToken::RBrac)) {
654         const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
655         Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
656       } else
657         return ErrorOperand(PlusLoc, "unexpected token after +");
658     } else if (getLexer().is(AsmToken::Identifier))
659       ParseRegister(IndexReg, Start, End);
660   }
661
662   if (getLexer().isNot(AsmToken::RBrac))
663     if (getParser().ParseExpression(Disp, End)) return 0;
664
665   End = Parser.getTok().getLoc();
666   if (getLexer().isNot(AsmToken::RBrac))
667     return ErrorOperand(End, "expected ']' token!");
668   Parser.Lex();
669   End = Parser.getTok().getLoc();
670
671   // handle [-42]
672   if (!BaseReg && !IndexReg)
673     return X86Operand::CreateMem(Disp, Start, End, Size);
674
675   return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
676                                Start, End, Size);
677 }
678
679 /// ParseIntelMemOperand - Parse intel style memory operand.
680 X86Operand *X86AsmParser::ParseIntelMemOperand() {
681   const AsmToken &Tok = Parser.getTok();
682   SMLoc Start = Parser.getTok().getLoc(), End;
683   unsigned SegReg = 0;
684
685   unsigned Size = getIntelMemOperandSize(Tok.getString());
686   if (Size) {
687     Parser.Lex();
688     assert (Tok.getString() == "PTR" && "Unexpected token!");
689     Parser.Lex();
690   }
691
692   if (getLexer().is(AsmToken::LBrac))
693     return ParseIntelBracExpression(SegReg, Size);
694
695   if (!ParseRegister(SegReg, Start, End)) {
696     // Handel SegReg : [ ... ]
697     if (getLexer().isNot(AsmToken::Colon))
698       return ErrorOperand(Start, "Expected ':' token!");
699     Parser.Lex(); // Eat :
700     if (getLexer().isNot(AsmToken::LBrac))
701       return ErrorOperand(Start, "Expected '[' token!");
702     return ParseIntelBracExpression(SegReg, Size);
703   }
704
705   const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
706   if (getParser().ParseExpression(Disp, End)) return 0;
707   return X86Operand::CreateMem(Disp, Start, End, Size);
708 }
709
710 X86Operand *X86AsmParser::ParseIntelOperand() {
711   SMLoc Start = Parser.getTok().getLoc(), End;
712
713   // immediate.
714   if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
715       getLexer().is(AsmToken::Minus)) {
716     const MCExpr *Val;
717     if (!getParser().ParseExpression(Val, End)) {
718       End = Parser.getTok().getLoc();
719       return X86Operand::CreateImm(Val, Start, End);
720     }
721   }
722
723   // register
724   unsigned RegNo = 0;
725   if (!ParseRegister(RegNo, Start, End)) {
726     End = Parser.getTok().getLoc();
727     return X86Operand::CreateReg(RegNo, Start, End);
728   }
729
730   // mem operand
731   return ParseIntelMemOperand();
732 }
733
734 X86Operand *X86AsmParser::ParseATTOperand() {
735   switch (getLexer().getKind()) {
736   default:
737     // Parse a memory operand with no segment register.
738     return ParseMemOperand(0, Parser.getTok().getLoc());
739   case AsmToken::Percent: {
740     // Read the register.
741     unsigned RegNo;
742     SMLoc Start, End;
743     if (ParseRegister(RegNo, Start, End)) return 0;
744     if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
745       Error(Start, "%eiz and %riz can only be used as index registers",
746             SMRange(Start, End));
747       return 0;
748     }
749
750     // If this is a segment register followed by a ':', then this is the start
751     // of a memory reference, otherwise this is a normal register reference.
752     if (getLexer().isNot(AsmToken::Colon))
753       return X86Operand::CreateReg(RegNo, Start, End);
754
755
756     getParser().Lex(); // Eat the colon.
757     return ParseMemOperand(RegNo, Start);
758   }
759   case AsmToken::Dollar: {
760     // $42 -> immediate.
761     SMLoc Start = Parser.getTok().getLoc(), End;
762     Parser.Lex();
763     const MCExpr *Val;
764     if (getParser().ParseExpression(Val, End))
765       return 0;
766     return X86Operand::CreateImm(Val, Start, End);
767   }
768   }
769 }
770
771 /// ParseMemOperand: segment: disp(basereg, indexreg, scale).  The '%ds:' prefix
772 /// has already been parsed if present.
773 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
774
775   // We have to disambiguate a parenthesized expression "(4+5)" from the start
776   // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)".  The
777   // only way to do this without lookahead is to eat the '(' and see what is
778   // after it.
779   const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
780   if (getLexer().isNot(AsmToken::LParen)) {
781     SMLoc ExprEnd;
782     if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
783
784     // After parsing the base expression we could either have a parenthesized
785     // memory address or not.  If not, return now.  If so, eat the (.
786     if (getLexer().isNot(AsmToken::LParen)) {
787       // Unless we have a segment register, treat this as an immediate.
788       if (SegReg == 0)
789         return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
790       return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
791     }
792
793     // Eat the '('.
794     Parser.Lex();
795   } else {
796     // Okay, we have a '('.  We don't know if this is an expression or not, but
797     // so we have to eat the ( to see beyond it.
798     SMLoc LParenLoc = Parser.getTok().getLoc();
799     Parser.Lex(); // Eat the '('.
800
801     if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
802       // Nothing to do here, fall into the code below with the '(' part of the
803       // memory operand consumed.
804     } else {
805       SMLoc ExprEnd;
806
807       // It must be an parenthesized expression, parse it now.
808       if (getParser().ParseParenExpression(Disp, ExprEnd))
809         return 0;
810
811       // After parsing the base expression we could either have a parenthesized
812       // memory address or not.  If not, return now.  If so, eat the (.
813       if (getLexer().isNot(AsmToken::LParen)) {
814         // Unless we have a segment register, treat this as an immediate.
815         if (SegReg == 0)
816           return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
817         return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
818       }
819
820       // Eat the '('.
821       Parser.Lex();
822     }
823   }
824
825   // If we reached here, then we just ate the ( of the memory operand.  Process
826   // the rest of the memory operand.
827   unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
828
829   if (getLexer().is(AsmToken::Percent)) {
830     SMLoc StartLoc, EndLoc;
831     if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
832     if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
833       Error(StartLoc, "eiz and riz can only be used as index registers",
834             SMRange(StartLoc, EndLoc));
835       return 0;
836     }
837   }
838
839   if (getLexer().is(AsmToken::Comma)) {
840     Parser.Lex(); // Eat the comma.
841
842     // Following the comma we should have either an index register, or a scale
843     // value. We don't support the later form, but we want to parse it
844     // correctly.
845     //
846     // Not that even though it would be completely consistent to support syntax
847     // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
848     if (getLexer().is(AsmToken::Percent)) {
849       SMLoc L;
850       if (ParseRegister(IndexReg, L, L)) return 0;
851
852       if (getLexer().isNot(AsmToken::RParen)) {
853         // Parse the scale amount:
854         //  ::= ',' [scale-expression]
855         if (getLexer().isNot(AsmToken::Comma)) {
856           Error(Parser.getTok().getLoc(),
857                 "expected comma in scale expression");
858           return 0;
859         }
860         Parser.Lex(); // Eat the comma.
861
862         if (getLexer().isNot(AsmToken::RParen)) {
863           SMLoc Loc = Parser.getTok().getLoc();
864
865           int64_t ScaleVal;
866           if (getParser().ParseAbsoluteExpression(ScaleVal))
867             return 0;
868
869           // Validate the scale amount.
870           if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
871             Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
872             return 0;
873           }
874           Scale = (unsigned)ScaleVal;
875         }
876       }
877     } else if (getLexer().isNot(AsmToken::RParen)) {
878       // A scale amount without an index is ignored.
879       // index.
880       SMLoc Loc = Parser.getTok().getLoc();
881
882       int64_t Value;
883       if (getParser().ParseAbsoluteExpression(Value))
884         return 0;
885
886       if (Value != 1)
887         Warning(Loc, "scale factor without index register is ignored");
888       Scale = 1;
889     }
890   }
891
892   // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
893   if (getLexer().isNot(AsmToken::RParen)) {
894     Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
895     return 0;
896   }
897   SMLoc MemEnd = Parser.getTok().getLoc();
898   Parser.Lex(); // Eat the ')'.
899
900   return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
901                                MemStart, MemEnd);
902 }
903
904 bool X86AsmParser::
905 ParseInstruction(StringRef Name, SMLoc NameLoc,
906                  SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
907   StringRef PatchedName = Name;
908
909   // FIXME: Hack to recognize setneb as setne.
910   if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
911       PatchedName != "setb" && PatchedName != "setnb")
912     PatchedName = PatchedName.substr(0, Name.size()-1);
913   
914   // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
915   const MCExpr *ExtraImmOp = 0;
916   if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
917       (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
918        PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
919     bool IsVCMP = PatchedName.startswith("vcmp");
920     unsigned SSECCIdx = IsVCMP ? 4 : 3;
921     unsigned SSEComparisonCode = StringSwitch<unsigned>(
922       PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
923       .Case("eq",          0)
924       .Case("lt",          1)
925       .Case("le",          2)
926       .Case("unord",       3)
927       .Case("neq",         4)
928       .Case("nlt",         5)
929       .Case("nle",         6)
930       .Case("ord",         7)
931       .Case("eq_uq",       8)
932       .Case("nge",         9)
933       .Case("ngt",      0x0A)
934       .Case("false",    0x0B)
935       .Case("neq_oq",   0x0C)
936       .Case("ge",       0x0D)
937       .Case("gt",       0x0E)
938       .Case("true",     0x0F)
939       .Case("eq_os",    0x10)
940       .Case("lt_oq",    0x11)
941       .Case("le_oq",    0x12)
942       .Case("unord_s",  0x13)
943       .Case("neq_us",   0x14)
944       .Case("nlt_uq",   0x15)
945       .Case("nle_uq",   0x16)
946       .Case("ord_s",    0x17)
947       .Case("eq_us",    0x18)
948       .Case("nge_uq",   0x19)
949       .Case("ngt_uq",   0x1A)
950       .Case("false_os", 0x1B)
951       .Case("neq_os",   0x1C)
952       .Case("ge_oq",    0x1D)
953       .Case("gt_oq",    0x1E)
954       .Case("true_us",  0x1F)
955       .Default(~0U);
956     if (SSEComparisonCode != ~0U) {
957       ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
958                                           getParser().getContext());
959       if (PatchedName.endswith("ss")) {
960         PatchedName = IsVCMP ? "vcmpss" : "cmpss";
961       } else if (PatchedName.endswith("sd")) {
962         PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
963       } else if (PatchedName.endswith("ps")) {
964         PatchedName = IsVCMP ? "vcmpps" : "cmpps";
965       } else {
966         assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
967         PatchedName = IsVCMP ? "vcmppd" : "cmppd";
968       }
969     }
970   }
971
972   Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
973
974   if (ExtraImmOp)
975     Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
976
977
978   // Determine whether this is an instruction prefix.
979   bool isPrefix =
980     Name == "lock" || Name == "rep" ||
981     Name == "repe" || Name == "repz" ||
982     Name == "repne" || Name == "repnz" ||
983     Name == "rex64" || Name == "data16";
984
985
986   // This does the actual operand parsing.  Don't parse any more if we have a
987   // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
988   // just want to parse the "lock" as the first instruction and the "incl" as
989   // the next one.
990   if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
991
992     // Parse '*' modifier.
993     if (getLexer().is(AsmToken::Star)) {
994       SMLoc Loc = Parser.getTok().getLoc();
995       Operands.push_back(X86Operand::CreateToken("*", Loc));
996       Parser.Lex(); // Eat the star.
997     }
998
999     // Read the first operand.
1000     if (X86Operand *Op = ParseOperand())
1001       Operands.push_back(Op);
1002     else {
1003       Parser.EatToEndOfStatement();
1004       return true;
1005     }
1006
1007     while (getLexer().is(AsmToken::Comma)) {
1008       Parser.Lex();  // Eat the comma.
1009
1010       // Parse and remember the operand.
1011       if (X86Operand *Op = ParseOperand())
1012         Operands.push_back(Op);
1013       else {
1014         Parser.EatToEndOfStatement();
1015         return true;
1016       }
1017     }
1018
1019     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1020       SMLoc Loc = getLexer().getLoc();
1021       Parser.EatToEndOfStatement();
1022       return Error(Loc, "unexpected token in argument list");
1023     }
1024   }
1025
1026   if (getLexer().is(AsmToken::EndOfStatement))
1027     Parser.Lex(); // Consume the EndOfStatement
1028   else if (isPrefix && getLexer().is(AsmToken::Slash))
1029     Parser.Lex(); // Consume the prefix separator Slash
1030
1031   // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1032   // "outb %al, %dx".  Out doesn't take a memory form, but this is a widely
1033   // documented form in various unofficial manuals, so a lot of code uses it.
1034   if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1035       Operands.size() == 3) {
1036     X86Operand &Op = *(X86Operand*)Operands.back();
1037     if (Op.isMem() && Op.Mem.SegReg == 0 &&
1038         isa<MCConstantExpr>(Op.Mem.Disp) &&
1039         cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1040         Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1041       SMLoc Loc = Op.getEndLoc();
1042       Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1043       delete &Op;
1044     }
1045   }
1046   // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1047   if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1048       Operands.size() == 3) {
1049     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1050     if (Op.isMem() && Op.Mem.SegReg == 0 &&
1051         isa<MCConstantExpr>(Op.Mem.Disp) &&
1052         cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1053         Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1054       SMLoc Loc = Op.getEndLoc();
1055       Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1056       delete &Op;
1057     }
1058   }
1059   // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1060   if (Name.startswith("ins") && Operands.size() == 3 &&
1061       (Name == "insb" || Name == "insw" || Name == "insl")) {
1062     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1063     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1064     if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1065       Operands.pop_back();
1066       Operands.pop_back();
1067       delete &Op;
1068       delete &Op2;
1069     }
1070   }
1071
1072   // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1073   if (Name.startswith("outs") && Operands.size() == 3 &&
1074       (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1075     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1076     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1077     if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1078       Operands.pop_back();
1079       Operands.pop_back();
1080       delete &Op;
1081       delete &Op2;
1082     }
1083   }
1084
1085   // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1086   if (Name.startswith("movs") && Operands.size() == 3 &&
1087       (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1088        (is64BitMode() && Name == "movsq"))) {
1089     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1090     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1091     if (isSrcOp(Op) && isDstOp(Op2)) {
1092       Operands.pop_back();
1093       Operands.pop_back();
1094       delete &Op;
1095       delete &Op2;
1096     }
1097   }
1098   // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1099   if (Name.startswith("lods") && Operands.size() == 3 &&
1100       (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1101        Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1102     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1103     X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1104     if (isSrcOp(*Op1) && Op2->isReg()) {
1105       const char *ins;
1106       unsigned reg = Op2->getReg();
1107       bool isLods = Name == "lods";
1108       if (reg == X86::AL && (isLods || Name == "lodsb"))
1109         ins = "lodsb";
1110       else if (reg == X86::AX && (isLods || Name == "lodsw"))
1111         ins = "lodsw";
1112       else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1113         ins = "lodsl";
1114       else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1115         ins = "lodsq";
1116       else
1117         ins = NULL;
1118       if (ins != NULL) {
1119         Operands.pop_back();
1120         Operands.pop_back();
1121         delete Op1;
1122         delete Op2;
1123         if (Name != ins)
1124           static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1125       }
1126     }
1127   }
1128   // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1129   if (Name.startswith("stos") && Operands.size() == 3 &&
1130       (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1131        Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1132     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1133     X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1134     if (isDstOp(*Op2) && Op1->isReg()) {
1135       const char *ins;
1136       unsigned reg = Op1->getReg();
1137       bool isStos = Name == "stos";
1138       if (reg == X86::AL && (isStos || Name == "stosb"))
1139         ins = "stosb";
1140       else if (reg == X86::AX && (isStos || Name == "stosw"))
1141         ins = "stosw";
1142       else if (reg == X86::EAX && (isStos || Name == "stosl"))
1143         ins = "stosl";
1144       else if (reg == X86::RAX && (isStos || Name == "stosq"))
1145         ins = "stosq";
1146       else
1147         ins = NULL;
1148       if (ins != NULL) {
1149         Operands.pop_back();
1150         Operands.pop_back();
1151         delete Op1;
1152         delete Op2;
1153         if (Name != ins)
1154           static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1155       }
1156     }
1157   }
1158
1159   // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>.  Canonicalize to
1160   // "shift <op>".
1161   if ((Name.startswith("shr") || Name.startswith("sar") ||
1162        Name.startswith("shl") || Name.startswith("sal") ||
1163        Name.startswith("rcl") || Name.startswith("rcr") ||
1164        Name.startswith("rol") || Name.startswith("ror")) &&
1165       Operands.size() == 3) {
1166     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1167     if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1168         cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1169       delete Operands[1];
1170       Operands.erase(Operands.begin() + 1);
1171     }
1172   }
1173   
1174   // Transforms "int $3" into "int3" as a size optimization.  We can't write an
1175   // instalias with an immediate operand yet.
1176   if (Name == "int" && Operands.size() == 2) {
1177     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1178     if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1179         cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1180       delete Operands[1];
1181       Operands.erase(Operands.begin() + 1);
1182       static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1183     }
1184   }
1185
1186   return false;
1187 }
1188
1189 bool X86AsmParser::
1190 processInstruction(MCInst &Inst,
1191                    const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1192   switch (Inst.getOpcode()) {
1193   default: return false;
1194   case X86::AND16i16: {
1195     if (!Inst.getOperand(0).isImm() ||
1196         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1197       return false;
1198
1199     MCInst TmpInst;
1200     TmpInst.setOpcode(X86::AND16ri8);
1201     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1202     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1203     TmpInst.addOperand(Inst.getOperand(0));
1204     Inst = TmpInst;
1205     return true;
1206   }
1207   case X86::AND32i32: {
1208     if (!Inst.getOperand(0).isImm() ||
1209         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1210       return false;
1211
1212     MCInst TmpInst;
1213     TmpInst.setOpcode(X86::AND32ri8);
1214     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1215     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1216     TmpInst.addOperand(Inst.getOperand(0));
1217     Inst = TmpInst;
1218     return true;
1219   }
1220   case X86::AND64i32: {
1221     if (!Inst.getOperand(0).isImm() ||
1222         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1223       return false;
1224
1225     MCInst TmpInst;
1226     TmpInst.setOpcode(X86::AND64ri8);
1227     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1228     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1229     TmpInst.addOperand(Inst.getOperand(0));
1230     Inst = TmpInst;
1231     return true;
1232   }
1233   case X86::XOR16i16: {
1234     if (!Inst.getOperand(0).isImm() ||
1235         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1236       return false;
1237
1238     MCInst TmpInst;
1239     TmpInst.setOpcode(X86::XOR16ri8);
1240     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1241     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1242     TmpInst.addOperand(Inst.getOperand(0));
1243     Inst = TmpInst;
1244     return true;
1245   }
1246   case X86::XOR32i32: {
1247     if (!Inst.getOperand(0).isImm() ||
1248         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1249       return false;
1250
1251     MCInst TmpInst;
1252     TmpInst.setOpcode(X86::XOR32ri8);
1253     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1254     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1255     TmpInst.addOperand(Inst.getOperand(0));
1256     Inst = TmpInst;
1257     return true;
1258   }
1259   case X86::XOR64i32: {
1260     if (!Inst.getOperand(0).isImm() ||
1261         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1262       return false;
1263
1264     MCInst TmpInst;
1265     TmpInst.setOpcode(X86::XOR64ri8);
1266     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1267     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1268     TmpInst.addOperand(Inst.getOperand(0));
1269     Inst = TmpInst;
1270     return true;
1271   }
1272   case X86::OR16i16: {
1273     if (!Inst.getOperand(0).isImm() ||
1274         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1275       return false;
1276
1277     MCInst TmpInst;
1278     TmpInst.setOpcode(X86::OR16ri8);
1279     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1280     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1281     TmpInst.addOperand(Inst.getOperand(0));
1282     Inst = TmpInst;
1283     return true;
1284   }
1285   case X86::OR32i32: {
1286     if (!Inst.getOperand(0).isImm() ||
1287         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1288       return false;
1289
1290     MCInst TmpInst;
1291     TmpInst.setOpcode(X86::OR32ri8);
1292     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1293     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1294     TmpInst.addOperand(Inst.getOperand(0));
1295     Inst = TmpInst;
1296     return true;
1297   }
1298   case X86::OR64i32: {
1299     if (!Inst.getOperand(0).isImm() ||
1300         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1301       return false;
1302
1303     MCInst TmpInst;
1304     TmpInst.setOpcode(X86::OR64ri8);
1305     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1306     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1307     TmpInst.addOperand(Inst.getOperand(0));
1308     Inst = TmpInst;
1309     return true;
1310   }
1311   case X86::CMP16i16: {
1312     if (!Inst.getOperand(0).isImm() ||
1313         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1314       return false;
1315
1316     MCInst TmpInst;
1317     TmpInst.setOpcode(X86::CMP16ri8);
1318     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1319     TmpInst.addOperand(Inst.getOperand(0));
1320     Inst = TmpInst;
1321     return true;
1322   }
1323   case X86::CMP32i32: {
1324     if (!Inst.getOperand(0).isImm() ||
1325         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1326       return false;
1327
1328     MCInst TmpInst;
1329     TmpInst.setOpcode(X86::CMP32ri8);
1330     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1331     TmpInst.addOperand(Inst.getOperand(0));
1332     Inst = TmpInst;
1333     return true;
1334   }
1335   case X86::CMP64i32: {
1336     if (!Inst.getOperand(0).isImm() ||
1337         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1338       return false;
1339
1340     MCInst TmpInst;
1341     TmpInst.setOpcode(X86::CMP64ri8);
1342     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1343     TmpInst.addOperand(Inst.getOperand(0));
1344     Inst = TmpInst;
1345     return true;
1346   }
1347   case X86::ADD16i16: {
1348     if (!Inst.getOperand(0).isImm() ||
1349         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1350       return false;
1351
1352     MCInst TmpInst;
1353     TmpInst.setOpcode(X86::ADD16ri8);
1354     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1355     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1356     TmpInst.addOperand(Inst.getOperand(0));
1357     Inst = TmpInst;
1358     return true;
1359   }
1360   case X86::ADD32i32: {
1361     if (!Inst.getOperand(0).isImm() ||
1362         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1363       return false;
1364
1365     MCInst TmpInst;
1366     TmpInst.setOpcode(X86::ADD32ri8);
1367     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1368     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1369     TmpInst.addOperand(Inst.getOperand(0));
1370     Inst = TmpInst;
1371     return true;
1372   }
1373   case X86::ADD64i32: {
1374     if (!Inst.getOperand(0).isImm() ||
1375         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1376       return false;
1377
1378     MCInst TmpInst;
1379     TmpInst.setOpcode(X86::ADD64ri8);
1380     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1381     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1382     TmpInst.addOperand(Inst.getOperand(0));
1383     Inst = TmpInst;
1384     return true;
1385   }
1386   case X86::SUB16i16: {
1387     if (!Inst.getOperand(0).isImm() ||
1388         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1389       return false;
1390
1391     MCInst TmpInst;
1392     TmpInst.setOpcode(X86::SUB16ri8);
1393     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1394     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1395     TmpInst.addOperand(Inst.getOperand(0));
1396     Inst = TmpInst;
1397     return true;
1398   }
1399   case X86::SUB32i32: {
1400     if (!Inst.getOperand(0).isImm() ||
1401         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1402       return false;
1403
1404     MCInst TmpInst;
1405     TmpInst.setOpcode(X86::SUB32ri8);
1406     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1407     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1408     TmpInst.addOperand(Inst.getOperand(0));
1409     Inst = TmpInst;
1410     return true;
1411   }
1412   case X86::SUB64i32: {
1413     if (!Inst.getOperand(0).isImm() ||
1414         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1415       return false;
1416
1417     MCInst TmpInst;
1418     TmpInst.setOpcode(X86::SUB64ri8);
1419     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1420     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1421     TmpInst.addOperand(Inst.getOperand(0));
1422     Inst = TmpInst;
1423     return true;
1424   }
1425   }
1426   return false;
1427 }
1428
1429 bool X86AsmParser::
1430 MatchAndEmitInstruction(SMLoc IDLoc,
1431                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1432                         MCStreamer &Out) {
1433   assert(!Operands.empty() && "Unexpect empty operand list!");
1434   X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1435   assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1436
1437   // First, handle aliases that expand to multiple instructions.
1438   // FIXME: This should be replaced with a real .td file alias mechanism.
1439   // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
1440   // call.
1441   if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1442       Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1443       Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1444       Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1445     MCInst Inst;
1446     Inst.setOpcode(X86::WAIT);
1447     Out.EmitInstruction(Inst);
1448
1449     const char *Repl =
1450       StringSwitch<const char*>(Op->getToken())
1451         .Case("finit",  "fninit")
1452         .Case("fsave",  "fnsave")
1453         .Case("fstcw",  "fnstcw")
1454         .Case("fstcww",  "fnstcw")
1455         .Case("fstenv", "fnstenv")
1456         .Case("fstsw",  "fnstsw")
1457         .Case("fstsww", "fnstsw")
1458         .Case("fclex",  "fnclex")
1459         .Default(0);
1460     assert(Repl && "Unknown wait-prefixed instruction");
1461     delete Operands[0];
1462     Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1463   }
1464
1465   bool WasOriginallyInvalidOperand = false;
1466   unsigned OrigErrorInfo;
1467   MCInst Inst;
1468
1469   // First, try a direct match.
1470   switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo, 
1471                                getParser().getAssemblerDialect())) {
1472   default: break;
1473   case Match_Success:
1474     // Some instructions need post-processing to, for example, tweak which
1475     // encoding is selected. Loop on it while changes happen so the
1476     // individual transformations can chain off each other. 
1477     while (processInstruction(Inst, Operands))
1478       ;
1479
1480     Out.EmitInstruction(Inst);
1481     return false;
1482   case Match_MissingFeature:
1483     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1484     return true;
1485   case Match_ConversionFail:
1486     return Error(IDLoc, "unable to convert operands to instruction");
1487   case Match_InvalidOperand:
1488     WasOriginallyInvalidOperand = true;
1489     break;
1490   case Match_MnemonicFail:
1491     break;
1492   }
1493
1494   // FIXME: Ideally, we would only attempt suffix matches for things which are
1495   // valid prefixes, and we could just infer the right unambiguous
1496   // type. However, that requires substantially more matcher support than the
1497   // following hack.
1498
1499   // Change the operand to point to a temporary token.
1500   StringRef Base = Op->getToken();
1501   SmallString<16> Tmp;
1502   Tmp += Base;
1503   Tmp += ' ';
1504   Op->setTokenValue(Tmp.str());
1505
1506   // If this instruction starts with an 'f', then it is a floating point stack
1507   // instruction.  These come in up to three forms for 32-bit, 64-bit, and
1508   // 80-bit floating point, which use the suffixes s,l,t respectively.
1509   //
1510   // Otherwise, we assume that this may be an integer instruction, which comes
1511   // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1512   const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1513   
1514   // Check for the various suffix matches.
1515   Tmp[Base.size()] = Suffixes[0];
1516   unsigned ErrorInfoIgnore;
1517   unsigned Match1, Match2, Match3, Match4;
1518   
1519   Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1520   Tmp[Base.size()] = Suffixes[1];
1521   Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1522   Tmp[Base.size()] = Suffixes[2];
1523   Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1524   Tmp[Base.size()] = Suffixes[3];
1525   Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1526
1527   // Restore the old token.
1528   Op->setTokenValue(Base);
1529
1530   // If exactly one matched, then we treat that as a successful match (and the
1531   // instruction will already have been filled in correctly, since the failing
1532   // matches won't have modified it).
1533   unsigned NumSuccessfulMatches =
1534     (Match1 == Match_Success) + (Match2 == Match_Success) +
1535     (Match3 == Match_Success) + (Match4 == Match_Success);
1536   if (NumSuccessfulMatches == 1) {
1537     Out.EmitInstruction(Inst);
1538     return false;
1539   }
1540
1541   // Otherwise, the match failed, try to produce a decent error message.
1542
1543   // If we had multiple suffix matches, then identify this as an ambiguous
1544   // match.
1545   if (NumSuccessfulMatches > 1) {
1546     char MatchChars[4];
1547     unsigned NumMatches = 0;
1548     if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1549     if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1550     if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1551     if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1552
1553     SmallString<126> Msg;
1554     raw_svector_ostream OS(Msg);
1555     OS << "ambiguous instructions require an explicit suffix (could be ";
1556     for (unsigned i = 0; i != NumMatches; ++i) {
1557       if (i != 0)
1558         OS << ", ";
1559       if (i + 1 == NumMatches)
1560         OS << "or ";
1561       OS << "'" << Base << MatchChars[i] << "'";
1562     }
1563     OS << ")";
1564     Error(IDLoc, OS.str());
1565     return true;
1566   }
1567
1568   // Okay, we know that none of the variants matched successfully.
1569
1570   // If all of the instructions reported an invalid mnemonic, then the original
1571   // mnemonic was invalid.
1572   if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1573       (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1574     if (!WasOriginallyInvalidOperand) {
1575       return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1576                    Op->getLocRange());
1577     }
1578
1579     // Recover location info for the operand if we know which was the problem.
1580     if (OrigErrorInfo != ~0U) {
1581       if (OrigErrorInfo >= Operands.size())
1582         return Error(IDLoc, "too few operands for instruction");
1583
1584       X86Operand *Operand = (X86Operand*)Operands[OrigErrorInfo];
1585       if (Operand->getStartLoc().isValid()) {
1586         SMRange OperandRange = Operand->getLocRange();
1587         return Error(Operand->getStartLoc(), "invalid operand for instruction",
1588                      OperandRange);
1589       }
1590     }
1591
1592     return Error(IDLoc, "invalid operand for instruction");
1593   }
1594
1595   // If one instruction matched with a missing feature, report this as a
1596   // missing feature.
1597   if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1598       (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1599     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1600     return true;
1601   }
1602
1603   // If one instruction matched with an invalid operand, report this as an
1604   // operand failure.
1605   if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1606       (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1607     Error(IDLoc, "invalid operand for instruction");
1608     return true;
1609   }
1610
1611   // If all of these were an outright failure, report it in a useless way.
1612   Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
1613   return true;
1614 }
1615
1616
1617 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1618   StringRef IDVal = DirectiveID.getIdentifier();
1619   if (IDVal == ".word")
1620     return ParseDirectiveWord(2, DirectiveID.getLoc());
1621   else if (IDVal.startswith(".code"))
1622     return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1623   return true;
1624 }
1625
1626 /// ParseDirectiveWord
1627 ///  ::= .word [ expression (, expression)* ]
1628 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1629   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1630     for (;;) {
1631       const MCExpr *Value;
1632       if (getParser().ParseExpression(Value))
1633         return true;
1634       
1635       getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1636       
1637       if (getLexer().is(AsmToken::EndOfStatement))
1638         break;
1639       
1640       // FIXME: Improve diagnostic.
1641       if (getLexer().isNot(AsmToken::Comma))
1642         return Error(L, "unexpected token in directive");
1643       Parser.Lex();
1644     }
1645   }
1646   
1647   Parser.Lex();
1648   return false;
1649 }
1650
1651 /// ParseDirectiveCode
1652 ///  ::= .code32 | .code64
1653 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1654   if (IDVal == ".code32") {
1655     Parser.Lex();
1656     if (is64BitMode()) {
1657       SwitchMode();
1658       getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1659     }
1660   } else if (IDVal == ".code64") {
1661     Parser.Lex();
1662     if (!is64BitMode()) {
1663       SwitchMode();
1664       getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1665     }
1666   } else {
1667     return Error(L, "unexpected directive " + IDVal);
1668   }
1669
1670   return false;
1671 }
1672
1673
1674 extern "C" void LLVMInitializeX86AsmLexer();
1675
1676 // Force static initialization.
1677 extern "C" void LLVMInitializeX86AsmParser() {
1678   RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1679   RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1680   LLVMInitializeX86AsmLexer();
1681 }
1682
1683 #define GET_REGISTER_MATCHER
1684 #define GET_MATCHER_IMPLEMENTATION
1685 #include "X86GenAsmMatcher.inc"