Intel syntax: Robustify register parsing.
[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 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 Size) {
597   unsigned SegReg = 0, BaseReg = 0, IndexReg = 0, Scale = 1;
598   const AsmToken &Tok = Parser.getTok();
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       // Handle '[' number ']'
622       const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
623       if (getParser().ParseExpression(Disp, End)) return 0;
624       if (getLexer().isNot(AsmToken::RBrac))
625         return ErrorOperand(Start, "Expected ']' token!");
626       Parser.Lex();
627       return X86Operand::CreateMem(Disp, Start, End, Size);
628   }
629
630   if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
631     bool isPlus = getLexer().is(AsmToken::Plus);
632     Parser.Lex();
633     SMLoc PlusLoc = Parser.getTok().getLoc();
634     if (getLexer().is(AsmToken::Integer)) {
635       int64_t Val = Parser.getTok().getIntVal();
636       Parser.Lex();
637       if (getLexer().is(AsmToken::Star)) {
638         Parser.Lex();
639         SMLoc IdxRegLoc = Parser.getTok().getLoc();
640         if (ParseRegister(IndexReg, IdxRegLoc, End))
641           return ErrorOperand(IdxRegLoc, "Expected register");
642         Scale = Val;
643       } else if (getLexer().is(AsmToken::RBrac)) {
644         const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
645         Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
646       } else
647         return ErrorOperand(PlusLoc, "unexpected token after +");
648     } else if (getLexer().is(AsmToken::Identifier))
649       ParseRegister(IndexReg, Start, End);
650   }
651
652   if (getLexer().isNot(AsmToken::RBrac))
653     if (getParser().ParseExpression(Disp, End)) return 0;
654
655   End = Parser.getTok().getLoc();
656   if (getLexer().isNot(AsmToken::RBrac))
657     return ErrorOperand(End, "expected ']' token!");
658   Parser.Lex();
659   End = Parser.getTok().getLoc();
660
661   // handle [-42]
662   if (!BaseReg && !IndexReg)
663     return X86Operand::CreateMem(Disp, Start, End, Size);
664
665   return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
666                                Start, End, Size);
667 }
668
669 /// ParseIntelMemOperand - Parse intel style memory operand.
670 X86Operand *X86AsmParser::ParseIntelMemOperand() {
671   const AsmToken &Tok = Parser.getTok();
672   SMLoc Start = Parser.getTok().getLoc(), End;
673
674   unsigned Size = getIntelMemOperandSize(Tok.getString());
675   if (Size) {
676     Parser.Lex();
677     assert (Tok.getString() == "PTR" && "Unexpected token!");
678     Parser.Lex();
679   }
680
681   if (getLexer().is(AsmToken::LBrac))
682     return ParseIntelBracExpression(Size);
683
684   const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
685   if (getParser().ParseExpression(Disp, End)) return 0;
686   return X86Operand::CreateMem(Disp, Start, End, Size);
687 }
688
689 X86Operand *X86AsmParser::ParseIntelOperand() {
690   StringRef TokenString = Parser.getTok().getString();
691   SMLoc Start = Parser.getTok().getLoc(), End;
692
693   // immediate.
694   if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
695       getLexer().is(AsmToken::Minus)) {
696     const MCExpr *Val;
697     if (!getParser().ParseExpression(Val, End)) {
698       End = Parser.getTok().getLoc();
699       return X86Operand::CreateImm(Val, Start, End);
700     }
701   }
702
703   // register
704   unsigned RegNo = 0;
705   if (!ParseRegister(RegNo, Start, End)) {
706     End = Parser.getTok().getLoc();
707     return X86Operand::CreateReg(RegNo, Start, End);
708   }
709
710   // mem operand
711   return ParseIntelMemOperand();
712 }
713
714 X86Operand *X86AsmParser::ParseATTOperand() {
715   switch (getLexer().getKind()) {
716   default:
717     // Parse a memory operand with no segment register.
718     return ParseMemOperand(0, Parser.getTok().getLoc());
719   case AsmToken::Percent: {
720     // Read the register.
721     unsigned RegNo;
722     SMLoc Start, End;
723     if (ParseRegister(RegNo, Start, End)) return 0;
724     if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
725       Error(Start, "%eiz and %riz can only be used as index registers",
726             SMRange(Start, End));
727       return 0;
728     }
729
730     // If this is a segment register followed by a ':', then this is the start
731     // of a memory reference, otherwise this is a normal register reference.
732     if (getLexer().isNot(AsmToken::Colon))
733       return X86Operand::CreateReg(RegNo, Start, End);
734
735
736     getParser().Lex(); // Eat the colon.
737     return ParseMemOperand(RegNo, Start);
738   }
739   case AsmToken::Dollar: {
740     // $42 -> immediate.
741     SMLoc Start = Parser.getTok().getLoc(), End;
742     Parser.Lex();
743     const MCExpr *Val;
744     if (getParser().ParseExpression(Val, End))
745       return 0;
746     return X86Operand::CreateImm(Val, Start, End);
747   }
748   }
749 }
750
751 /// ParseMemOperand: segment: disp(basereg, indexreg, scale).  The '%ds:' prefix
752 /// has already been parsed if present.
753 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
754
755   // We have to disambiguate a parenthesized expression "(4+5)" from the start
756   // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)".  The
757   // only way to do this without lookahead is to eat the '(' and see what is
758   // after it.
759   const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
760   if (getLexer().isNot(AsmToken::LParen)) {
761     SMLoc ExprEnd;
762     if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
763
764     // After parsing the base expression we could either have a parenthesized
765     // memory address or not.  If not, return now.  If so, eat the (.
766     if (getLexer().isNot(AsmToken::LParen)) {
767       // Unless we have a segment register, treat this as an immediate.
768       if (SegReg == 0)
769         return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
770       return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
771     }
772
773     // Eat the '('.
774     Parser.Lex();
775   } else {
776     // Okay, we have a '('.  We don't know if this is an expression or not, but
777     // so we have to eat the ( to see beyond it.
778     SMLoc LParenLoc = Parser.getTok().getLoc();
779     Parser.Lex(); // Eat the '('.
780
781     if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
782       // Nothing to do here, fall into the code below with the '(' part of the
783       // memory operand consumed.
784     } else {
785       SMLoc ExprEnd;
786
787       // It must be an parenthesized expression, parse it now.
788       if (getParser().ParseParenExpression(Disp, ExprEnd))
789         return 0;
790
791       // After parsing the base expression we could either have a parenthesized
792       // memory address or not.  If not, return now.  If so, eat the (.
793       if (getLexer().isNot(AsmToken::LParen)) {
794         // Unless we have a segment register, treat this as an immediate.
795         if (SegReg == 0)
796           return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
797         return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
798       }
799
800       // Eat the '('.
801       Parser.Lex();
802     }
803   }
804
805   // If we reached here, then we just ate the ( of the memory operand.  Process
806   // the rest of the memory operand.
807   unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
808
809   if (getLexer().is(AsmToken::Percent)) {
810     SMLoc StartLoc, EndLoc;
811     if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
812     if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
813       Error(StartLoc, "eiz and riz can only be used as index registers",
814             SMRange(StartLoc, EndLoc));
815       return 0;
816     }
817   }
818
819   if (getLexer().is(AsmToken::Comma)) {
820     Parser.Lex(); // Eat the comma.
821
822     // Following the comma we should have either an index register, or a scale
823     // value. We don't support the later form, but we want to parse it
824     // correctly.
825     //
826     // Not that even though it would be completely consistent to support syntax
827     // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
828     if (getLexer().is(AsmToken::Percent)) {
829       SMLoc L;
830       if (ParseRegister(IndexReg, L, L)) return 0;
831
832       if (getLexer().isNot(AsmToken::RParen)) {
833         // Parse the scale amount:
834         //  ::= ',' [scale-expression]
835         if (getLexer().isNot(AsmToken::Comma)) {
836           Error(Parser.getTok().getLoc(),
837                 "expected comma in scale expression");
838           return 0;
839         }
840         Parser.Lex(); // Eat the comma.
841
842         if (getLexer().isNot(AsmToken::RParen)) {
843           SMLoc Loc = Parser.getTok().getLoc();
844
845           int64_t ScaleVal;
846           if (getParser().ParseAbsoluteExpression(ScaleVal))
847             return 0;
848
849           // Validate the scale amount.
850           if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
851             Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
852             return 0;
853           }
854           Scale = (unsigned)ScaleVal;
855         }
856       }
857     } else if (getLexer().isNot(AsmToken::RParen)) {
858       // A scale amount without an index is ignored.
859       // index.
860       SMLoc Loc = Parser.getTok().getLoc();
861
862       int64_t Value;
863       if (getParser().ParseAbsoluteExpression(Value))
864         return 0;
865
866       if (Value != 1)
867         Warning(Loc, "scale factor without index register is ignored");
868       Scale = 1;
869     }
870   }
871
872   // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
873   if (getLexer().isNot(AsmToken::RParen)) {
874     Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
875     return 0;
876   }
877   SMLoc MemEnd = Parser.getTok().getLoc();
878   Parser.Lex(); // Eat the ')'.
879
880   return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
881                                MemStart, MemEnd);
882 }
883
884 bool X86AsmParser::
885 ParseInstruction(StringRef Name, SMLoc NameLoc,
886                  SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
887   StringRef PatchedName = Name;
888
889   // FIXME: Hack to recognize setneb as setne.
890   if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
891       PatchedName != "setb" && PatchedName != "setnb")
892     PatchedName = PatchedName.substr(0, Name.size()-1);
893   
894   // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
895   const MCExpr *ExtraImmOp = 0;
896   if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
897       (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
898        PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
899     bool IsVCMP = PatchedName.startswith("vcmp");
900     unsigned SSECCIdx = IsVCMP ? 4 : 3;
901     unsigned SSEComparisonCode = StringSwitch<unsigned>(
902       PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
903       .Case("eq",          0)
904       .Case("lt",          1)
905       .Case("le",          2)
906       .Case("unord",       3)
907       .Case("neq",         4)
908       .Case("nlt",         5)
909       .Case("nle",         6)
910       .Case("ord",         7)
911       .Case("eq_uq",       8)
912       .Case("nge",         9)
913       .Case("ngt",      0x0A)
914       .Case("false",    0x0B)
915       .Case("neq_oq",   0x0C)
916       .Case("ge",       0x0D)
917       .Case("gt",       0x0E)
918       .Case("true",     0x0F)
919       .Case("eq_os",    0x10)
920       .Case("lt_oq",    0x11)
921       .Case("le_oq",    0x12)
922       .Case("unord_s",  0x13)
923       .Case("neq_us",   0x14)
924       .Case("nlt_uq",   0x15)
925       .Case("nle_uq",   0x16)
926       .Case("ord_s",    0x17)
927       .Case("eq_us",    0x18)
928       .Case("nge_uq",   0x19)
929       .Case("ngt_uq",   0x1A)
930       .Case("false_os", 0x1B)
931       .Case("neq_os",   0x1C)
932       .Case("ge_oq",    0x1D)
933       .Case("gt_oq",    0x1E)
934       .Case("true_us",  0x1F)
935       .Default(~0U);
936     if (SSEComparisonCode != ~0U) {
937       ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
938                                           getParser().getContext());
939       if (PatchedName.endswith("ss")) {
940         PatchedName = IsVCMP ? "vcmpss" : "cmpss";
941       } else if (PatchedName.endswith("sd")) {
942         PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
943       } else if (PatchedName.endswith("ps")) {
944         PatchedName = IsVCMP ? "vcmpps" : "cmpps";
945       } else {
946         assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
947         PatchedName = IsVCMP ? "vcmppd" : "cmppd";
948       }
949     }
950   }
951
952   Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
953
954   if (ExtraImmOp)
955     Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
956
957
958   // Determine whether this is an instruction prefix.
959   bool isPrefix =
960     Name == "lock" || Name == "rep" ||
961     Name == "repe" || Name == "repz" ||
962     Name == "repne" || Name == "repnz" ||
963     Name == "rex64" || Name == "data16";
964
965
966   // This does the actual operand parsing.  Don't parse any more if we have a
967   // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
968   // just want to parse the "lock" as the first instruction and the "incl" as
969   // the next one.
970   if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
971
972     // Parse '*' modifier.
973     if (getLexer().is(AsmToken::Star)) {
974       SMLoc Loc = Parser.getTok().getLoc();
975       Operands.push_back(X86Operand::CreateToken("*", Loc));
976       Parser.Lex(); // Eat the star.
977     }
978
979     // Read the first operand.
980     if (X86Operand *Op = ParseOperand())
981       Operands.push_back(Op);
982     else {
983       Parser.EatToEndOfStatement();
984       return true;
985     }
986
987     while (getLexer().is(AsmToken::Comma)) {
988       Parser.Lex();  // Eat the comma.
989
990       // Parse and remember the operand.
991       if (X86Operand *Op = ParseOperand())
992         Operands.push_back(Op);
993       else {
994         Parser.EatToEndOfStatement();
995         return true;
996       }
997     }
998
999     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1000       SMLoc Loc = getLexer().getLoc();
1001       Parser.EatToEndOfStatement();
1002       return Error(Loc, "unexpected token in argument list");
1003     }
1004   }
1005
1006   if (getLexer().is(AsmToken::EndOfStatement))
1007     Parser.Lex(); // Consume the EndOfStatement
1008   else if (isPrefix && getLexer().is(AsmToken::Slash))
1009     Parser.Lex(); // Consume the prefix separator Slash
1010
1011   // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1012   // "outb %al, %dx".  Out doesn't take a memory form, but this is a widely
1013   // documented form in various unofficial manuals, so a lot of code uses it.
1014   if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1015       Operands.size() == 3) {
1016     X86Operand &Op = *(X86Operand*)Operands.back();
1017     if (Op.isMem() && Op.Mem.SegReg == 0 &&
1018         isa<MCConstantExpr>(Op.Mem.Disp) &&
1019         cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1020         Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1021       SMLoc Loc = Op.getEndLoc();
1022       Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1023       delete &Op;
1024     }
1025   }
1026   // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1027   if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1028       Operands.size() == 3) {
1029     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1030     if (Op.isMem() && Op.Mem.SegReg == 0 &&
1031         isa<MCConstantExpr>(Op.Mem.Disp) &&
1032         cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1033         Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1034       SMLoc Loc = Op.getEndLoc();
1035       Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1036       delete &Op;
1037     }
1038   }
1039   // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1040   if (Name.startswith("ins") && Operands.size() == 3 &&
1041       (Name == "insb" || Name == "insw" || Name == "insl")) {
1042     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1043     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1044     if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1045       Operands.pop_back();
1046       Operands.pop_back();
1047       delete &Op;
1048       delete &Op2;
1049     }
1050   }
1051
1052   // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1053   if (Name.startswith("outs") && Operands.size() == 3 &&
1054       (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1055     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1056     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1057     if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1058       Operands.pop_back();
1059       Operands.pop_back();
1060       delete &Op;
1061       delete &Op2;
1062     }
1063   }
1064
1065   // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1066   if (Name.startswith("movs") && Operands.size() == 3 &&
1067       (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1068        (is64BitMode() && Name == "movsq"))) {
1069     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1070     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1071     if (isSrcOp(Op) && isDstOp(Op2)) {
1072       Operands.pop_back();
1073       Operands.pop_back();
1074       delete &Op;
1075       delete &Op2;
1076     }
1077   }
1078   // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1079   if (Name.startswith("lods") && Operands.size() == 3 &&
1080       (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1081        Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1082     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1083     X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1084     if (isSrcOp(*Op1) && Op2->isReg()) {
1085       const char *ins;
1086       unsigned reg = Op2->getReg();
1087       bool isLods = Name == "lods";
1088       if (reg == X86::AL && (isLods || Name == "lodsb"))
1089         ins = "lodsb";
1090       else if (reg == X86::AX && (isLods || Name == "lodsw"))
1091         ins = "lodsw";
1092       else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1093         ins = "lodsl";
1094       else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1095         ins = "lodsq";
1096       else
1097         ins = NULL;
1098       if (ins != NULL) {
1099         Operands.pop_back();
1100         Operands.pop_back();
1101         delete Op1;
1102         delete Op2;
1103         if (Name != ins)
1104           static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1105       }
1106     }
1107   }
1108   // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1109   if (Name.startswith("stos") && Operands.size() == 3 &&
1110       (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1111        Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1112     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1113     X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1114     if (isDstOp(*Op2) && Op1->isReg()) {
1115       const char *ins;
1116       unsigned reg = Op1->getReg();
1117       bool isStos = Name == "stos";
1118       if (reg == X86::AL && (isStos || Name == "stosb"))
1119         ins = "stosb";
1120       else if (reg == X86::AX && (isStos || Name == "stosw"))
1121         ins = "stosw";
1122       else if (reg == X86::EAX && (isStos || Name == "stosl"))
1123         ins = "stosl";
1124       else if (reg == X86::RAX && (isStos || Name == "stosq"))
1125         ins = "stosq";
1126       else
1127         ins = NULL;
1128       if (ins != NULL) {
1129         Operands.pop_back();
1130         Operands.pop_back();
1131         delete Op1;
1132         delete Op2;
1133         if (Name != ins)
1134           static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1135       }
1136     }
1137   }
1138
1139   // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>.  Canonicalize to
1140   // "shift <op>".
1141   if ((Name.startswith("shr") || Name.startswith("sar") ||
1142        Name.startswith("shl") || Name.startswith("sal") ||
1143        Name.startswith("rcl") || Name.startswith("rcr") ||
1144        Name.startswith("rol") || Name.startswith("ror")) &&
1145       Operands.size() == 3) {
1146     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1147     if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1148         cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1149       delete Operands[1];
1150       Operands.erase(Operands.begin() + 1);
1151     }
1152   }
1153   
1154   // Transforms "int $3" into "int3" as a size optimization.  We can't write an
1155   // instalias with an immediate operand yet.
1156   if (Name == "int" && Operands.size() == 2) {
1157     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1158     if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1159         cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1160       delete Operands[1];
1161       Operands.erase(Operands.begin() + 1);
1162       static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1163     }
1164   }
1165
1166   return false;
1167 }
1168
1169 bool X86AsmParser::
1170 processInstruction(MCInst &Inst,
1171                    const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1172   switch (Inst.getOpcode()) {
1173   default: return false;
1174   case X86::AND16i16: {
1175     if (!Inst.getOperand(0).isImm() ||
1176         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1177       return false;
1178
1179     MCInst TmpInst;
1180     TmpInst.setOpcode(X86::AND16ri8);
1181     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1182     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1183     TmpInst.addOperand(Inst.getOperand(0));
1184     Inst = TmpInst;
1185     return true;
1186   }
1187   case X86::AND32i32: {
1188     if (!Inst.getOperand(0).isImm() ||
1189         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1190       return false;
1191
1192     MCInst TmpInst;
1193     TmpInst.setOpcode(X86::AND32ri8);
1194     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1195     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1196     TmpInst.addOperand(Inst.getOperand(0));
1197     Inst = TmpInst;
1198     return true;
1199   }
1200   case X86::AND64i32: {
1201     if (!Inst.getOperand(0).isImm() ||
1202         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1203       return false;
1204
1205     MCInst TmpInst;
1206     TmpInst.setOpcode(X86::AND64ri8);
1207     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1208     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1209     TmpInst.addOperand(Inst.getOperand(0));
1210     Inst = TmpInst;
1211     return true;
1212   }
1213   case X86::XOR16i16: {
1214     if (!Inst.getOperand(0).isImm() ||
1215         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1216       return false;
1217
1218     MCInst TmpInst;
1219     TmpInst.setOpcode(X86::XOR16ri8);
1220     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1221     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1222     TmpInst.addOperand(Inst.getOperand(0));
1223     Inst = TmpInst;
1224     return true;
1225   }
1226   case X86::XOR32i32: {
1227     if (!Inst.getOperand(0).isImm() ||
1228         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1229       return false;
1230
1231     MCInst TmpInst;
1232     TmpInst.setOpcode(X86::XOR32ri8);
1233     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1234     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1235     TmpInst.addOperand(Inst.getOperand(0));
1236     Inst = TmpInst;
1237     return true;
1238   }
1239   case X86::XOR64i32: {
1240     if (!Inst.getOperand(0).isImm() ||
1241         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1242       return false;
1243
1244     MCInst TmpInst;
1245     TmpInst.setOpcode(X86::XOR64ri8);
1246     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1247     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1248     TmpInst.addOperand(Inst.getOperand(0));
1249     Inst = TmpInst;
1250     return true;
1251   }
1252   case X86::OR16i16: {
1253     if (!Inst.getOperand(0).isImm() ||
1254         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1255       return false;
1256
1257     MCInst TmpInst;
1258     TmpInst.setOpcode(X86::OR16ri8);
1259     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1260     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1261     TmpInst.addOperand(Inst.getOperand(0));
1262     Inst = TmpInst;
1263     return true;
1264   }
1265   case X86::OR32i32: {
1266     if (!Inst.getOperand(0).isImm() ||
1267         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1268       return false;
1269
1270     MCInst TmpInst;
1271     TmpInst.setOpcode(X86::OR32ri8);
1272     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1273     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1274     TmpInst.addOperand(Inst.getOperand(0));
1275     Inst = TmpInst;
1276     return true;
1277   }
1278   case X86::OR64i32: {
1279     if (!Inst.getOperand(0).isImm() ||
1280         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1281       return false;
1282
1283     MCInst TmpInst;
1284     TmpInst.setOpcode(X86::OR64ri8);
1285     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1286     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1287     TmpInst.addOperand(Inst.getOperand(0));
1288     Inst = TmpInst;
1289     return true;
1290   }
1291   case X86::CMP16i16: {
1292     if (!Inst.getOperand(0).isImm() ||
1293         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1294       return false;
1295
1296     MCInst TmpInst;
1297     TmpInst.setOpcode(X86::CMP16ri8);
1298     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1299     TmpInst.addOperand(Inst.getOperand(0));
1300     Inst = TmpInst;
1301     return true;
1302   }
1303   case X86::CMP32i32: {
1304     if (!Inst.getOperand(0).isImm() ||
1305         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1306       return false;
1307
1308     MCInst TmpInst;
1309     TmpInst.setOpcode(X86::CMP32ri8);
1310     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1311     TmpInst.addOperand(Inst.getOperand(0));
1312     Inst = TmpInst;
1313     return true;
1314   }
1315   case X86::CMP64i32: {
1316     if (!Inst.getOperand(0).isImm() ||
1317         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1318       return false;
1319
1320     MCInst TmpInst;
1321     TmpInst.setOpcode(X86::CMP64ri8);
1322     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1323     TmpInst.addOperand(Inst.getOperand(0));
1324     Inst = TmpInst;
1325     return true;
1326   }
1327   case X86::ADD16i16: {
1328     if (!Inst.getOperand(0).isImm() ||
1329         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1330       return false;
1331
1332     MCInst TmpInst;
1333     TmpInst.setOpcode(X86::ADD16ri8);
1334     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1335     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1336     TmpInst.addOperand(Inst.getOperand(0));
1337     Inst = TmpInst;
1338     return true;
1339   }
1340   case X86::ADD32i32: {
1341     if (!Inst.getOperand(0).isImm() ||
1342         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1343       return false;
1344
1345     MCInst TmpInst;
1346     TmpInst.setOpcode(X86::ADD32ri8);
1347     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1348     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1349     TmpInst.addOperand(Inst.getOperand(0));
1350     Inst = TmpInst;
1351     return true;
1352   }
1353   case X86::ADD64i32: {
1354     if (!Inst.getOperand(0).isImm() ||
1355         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1356       return false;
1357
1358     MCInst TmpInst;
1359     TmpInst.setOpcode(X86::ADD64ri8);
1360     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1361     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1362     TmpInst.addOperand(Inst.getOperand(0));
1363     Inst = TmpInst;
1364     return true;
1365   }
1366   case X86::SUB16i16: {
1367     if (!Inst.getOperand(0).isImm() ||
1368         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1369       return false;
1370
1371     MCInst TmpInst;
1372     TmpInst.setOpcode(X86::SUB16ri8);
1373     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1374     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1375     TmpInst.addOperand(Inst.getOperand(0));
1376     Inst = TmpInst;
1377     return true;
1378   }
1379   case X86::SUB32i32: {
1380     if (!Inst.getOperand(0).isImm() ||
1381         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1382       return false;
1383
1384     MCInst TmpInst;
1385     TmpInst.setOpcode(X86::SUB32ri8);
1386     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1387     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1388     TmpInst.addOperand(Inst.getOperand(0));
1389     Inst = TmpInst;
1390     return true;
1391   }
1392   case X86::SUB64i32: {
1393     if (!Inst.getOperand(0).isImm() ||
1394         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1395       return false;
1396
1397     MCInst TmpInst;
1398     TmpInst.setOpcode(X86::SUB64ri8);
1399     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1400     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1401     TmpInst.addOperand(Inst.getOperand(0));
1402     Inst = TmpInst;
1403     return true;
1404   }
1405   }
1406   return false;
1407 }
1408
1409 bool X86AsmParser::
1410 MatchAndEmitInstruction(SMLoc IDLoc,
1411                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1412                         MCStreamer &Out) {
1413   assert(!Operands.empty() && "Unexpect empty operand list!");
1414   X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1415   assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1416
1417   // First, handle aliases that expand to multiple instructions.
1418   // FIXME: This should be replaced with a real .td file alias mechanism.
1419   // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
1420   // call.
1421   if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1422       Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1423       Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1424       Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1425     MCInst Inst;
1426     Inst.setOpcode(X86::WAIT);
1427     Out.EmitInstruction(Inst);
1428
1429     const char *Repl =
1430       StringSwitch<const char*>(Op->getToken())
1431         .Case("finit",  "fninit")
1432         .Case("fsave",  "fnsave")
1433         .Case("fstcw",  "fnstcw")
1434         .Case("fstcww",  "fnstcw")
1435         .Case("fstenv", "fnstenv")
1436         .Case("fstsw",  "fnstsw")
1437         .Case("fstsww", "fnstsw")
1438         .Case("fclex",  "fnclex")
1439         .Default(0);
1440     assert(Repl && "Unknown wait-prefixed instruction");
1441     delete Operands[0];
1442     Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1443   }
1444
1445   bool WasOriginallyInvalidOperand = false;
1446   unsigned OrigErrorInfo;
1447   MCInst Inst;
1448
1449   // First, try a direct match.
1450   switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo, 
1451                                getParser().getAssemblerDialect())) {
1452   default: break;
1453   case Match_Success:
1454     // Some instructions need post-processing to, for example, tweak which
1455     // encoding is selected. Loop on it while changes happen so the
1456     // individual transformations can chain off each other. 
1457     while (processInstruction(Inst, Operands))
1458       ;
1459
1460     Out.EmitInstruction(Inst);
1461     return false;
1462   case Match_MissingFeature:
1463     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1464     return true;
1465   case Match_ConversionFail:
1466     return Error(IDLoc, "unable to convert operands to instruction");
1467   case Match_InvalidOperand:
1468     WasOriginallyInvalidOperand = true;
1469     break;
1470   case Match_MnemonicFail:
1471     break;
1472   }
1473
1474   // FIXME: Ideally, we would only attempt suffix matches for things which are
1475   // valid prefixes, and we could just infer the right unambiguous
1476   // type. However, that requires substantially more matcher support than the
1477   // following hack.
1478
1479   // Change the operand to point to a temporary token.
1480   StringRef Base = Op->getToken();
1481   SmallString<16> Tmp;
1482   Tmp += Base;
1483   Tmp += ' ';
1484   Op->setTokenValue(Tmp.str());
1485
1486   // If this instruction starts with an 'f', then it is a floating point stack
1487   // instruction.  These come in up to three forms for 32-bit, 64-bit, and
1488   // 80-bit floating point, which use the suffixes s,l,t respectively.
1489   //
1490   // Otherwise, we assume that this may be an integer instruction, which comes
1491   // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1492   const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1493   
1494   // Check for the various suffix matches.
1495   Tmp[Base.size()] = Suffixes[0];
1496   unsigned ErrorInfoIgnore;
1497   unsigned Match1, Match2, Match3, Match4;
1498   
1499   Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1500   Tmp[Base.size()] = Suffixes[1];
1501   Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1502   Tmp[Base.size()] = Suffixes[2];
1503   Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1504   Tmp[Base.size()] = Suffixes[3];
1505   Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1506
1507   // Restore the old token.
1508   Op->setTokenValue(Base);
1509
1510   // If exactly one matched, then we treat that as a successful match (and the
1511   // instruction will already have been filled in correctly, since the failing
1512   // matches won't have modified it).
1513   unsigned NumSuccessfulMatches =
1514     (Match1 == Match_Success) + (Match2 == Match_Success) +
1515     (Match3 == Match_Success) + (Match4 == Match_Success);
1516   if (NumSuccessfulMatches == 1) {
1517     Out.EmitInstruction(Inst);
1518     return false;
1519   }
1520
1521   // Otherwise, the match failed, try to produce a decent error message.
1522
1523   // If we had multiple suffix matches, then identify this as an ambiguous
1524   // match.
1525   if (NumSuccessfulMatches > 1) {
1526     char MatchChars[4];
1527     unsigned NumMatches = 0;
1528     if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1529     if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1530     if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1531     if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1532
1533     SmallString<126> Msg;
1534     raw_svector_ostream OS(Msg);
1535     OS << "ambiguous instructions require an explicit suffix (could be ";
1536     for (unsigned i = 0; i != NumMatches; ++i) {
1537       if (i != 0)
1538         OS << ", ";
1539       if (i + 1 == NumMatches)
1540         OS << "or ";
1541       OS << "'" << Base << MatchChars[i] << "'";
1542     }
1543     OS << ")";
1544     Error(IDLoc, OS.str());
1545     return true;
1546   }
1547
1548   // Okay, we know that none of the variants matched successfully.
1549
1550   // If all of the instructions reported an invalid mnemonic, then the original
1551   // mnemonic was invalid.
1552   if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1553       (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1554     if (!WasOriginallyInvalidOperand) {
1555       return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1556                    Op->getLocRange());
1557     }
1558
1559     // Recover location info for the operand if we know which was the problem.
1560     if (OrigErrorInfo != ~0U) {
1561       if (OrigErrorInfo >= Operands.size())
1562         return Error(IDLoc, "too few operands for instruction");
1563
1564       X86Operand *Operand = (X86Operand*)Operands[OrigErrorInfo];
1565       if (Operand->getStartLoc().isValid()) {
1566         SMRange OperandRange = Operand->getLocRange();
1567         return Error(Operand->getStartLoc(), "invalid operand for instruction",
1568                      OperandRange);
1569       }
1570     }
1571
1572     return Error(IDLoc, "invalid operand for instruction");
1573   }
1574
1575   // If one instruction matched with a missing feature, report this as a
1576   // missing feature.
1577   if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1578       (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1579     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1580     return true;
1581   }
1582
1583   // If one instruction matched with an invalid operand, report this as an
1584   // operand failure.
1585   if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1586       (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1587     Error(IDLoc, "invalid operand for instruction");
1588     return true;
1589   }
1590
1591   // If all of these were an outright failure, report it in a useless way.
1592   Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
1593   return true;
1594 }
1595
1596
1597 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1598   StringRef IDVal = DirectiveID.getIdentifier();
1599   if (IDVal == ".word")
1600     return ParseDirectiveWord(2, DirectiveID.getLoc());
1601   else if (IDVal.startswith(".code"))
1602     return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1603   return true;
1604 }
1605
1606 /// ParseDirectiveWord
1607 ///  ::= .word [ expression (, expression)* ]
1608 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1609   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1610     for (;;) {
1611       const MCExpr *Value;
1612       if (getParser().ParseExpression(Value))
1613         return true;
1614       
1615       getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1616       
1617       if (getLexer().is(AsmToken::EndOfStatement))
1618         break;
1619       
1620       // FIXME: Improve diagnostic.
1621       if (getLexer().isNot(AsmToken::Comma))
1622         return Error(L, "unexpected token in directive");
1623       Parser.Lex();
1624     }
1625   }
1626   
1627   Parser.Lex();
1628   return false;
1629 }
1630
1631 /// ParseDirectiveCode
1632 ///  ::= .code32 | .code64
1633 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1634   if (IDVal == ".code32") {
1635     Parser.Lex();
1636     if (is64BitMode()) {
1637       SwitchMode();
1638       getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1639     }
1640   } else if (IDVal == ".code64") {
1641     Parser.Lex();
1642     if (!is64BitMode()) {
1643       SwitchMode();
1644       getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1645     }
1646   } else {
1647     return Error(L, "unexpected directive " + IDVal);
1648   }
1649
1650   return false;
1651 }
1652
1653
1654 extern "C" void LLVMInitializeX86AsmLexer();
1655
1656 // Force static initialization.
1657 extern "C" void LLVMInitializeX86AsmParser() {
1658   RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1659   RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1660   LLVMInitializeX86AsmLexer();
1661 }
1662
1663 #define GET_REGISTER_MATCHER
1664 #define GET_MATCHER_IMPLEMENTATION
1665 #include "X86GenAsmMatcher.inc"