Process instructions after match to select alternative encoding which may be more...
[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   const AsmToken &TokPercent = Parser.getTok();
474   if (!getParser().getAssemblerDialect()) {
475     assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
476     StartLoc = TokPercent.getLoc();
477     Parser.Lex(); // Eat percent token.
478   }
479
480   const AsmToken &Tok = Parser.getTok();
481   if (Tok.isNot(AsmToken::Identifier))
482     return Error(StartLoc, "invalid register name",
483                  SMRange(StartLoc, Tok.getEndLoc()));
484
485   RegNo = MatchRegisterName(Tok.getString());
486
487   // If the match failed, try the register name as lowercase.
488   if (RegNo == 0)
489     RegNo = MatchRegisterName(Tok.getString().lower());
490
491   if (!is64BitMode()) {
492     // FIXME: This should be done using Requires<In32BitMode> and
493     // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
494     // checked.
495     // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
496     // REX prefix.
497     if (RegNo == X86::RIZ ||
498         X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
499         X86II::isX86_64NonExtLowByteReg(RegNo) ||
500         X86II::isX86_64ExtendedReg(RegNo))
501       return Error(StartLoc, "register %"
502                    + Tok.getString() + " is only available in 64-bit mode",
503                    SMRange(StartLoc, Tok.getEndLoc()));
504   }
505
506   // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
507   if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
508     RegNo = X86::ST0;
509     EndLoc = Tok.getLoc();
510     Parser.Lex(); // Eat 'st'
511
512     // Check to see if we have '(4)' after %st.
513     if (getLexer().isNot(AsmToken::LParen))
514       return false;
515     // Lex the paren.
516     getParser().Lex();
517
518     const AsmToken &IntTok = Parser.getTok();
519     if (IntTok.isNot(AsmToken::Integer))
520       return Error(IntTok.getLoc(), "expected stack index");
521     switch (IntTok.getIntVal()) {
522     case 0: RegNo = X86::ST0; break;
523     case 1: RegNo = X86::ST1; break;
524     case 2: RegNo = X86::ST2; break;
525     case 3: RegNo = X86::ST3; break;
526     case 4: RegNo = X86::ST4; break;
527     case 5: RegNo = X86::ST5; break;
528     case 6: RegNo = X86::ST6; break;
529     case 7: RegNo = X86::ST7; break;
530     default: return Error(IntTok.getLoc(), "invalid stack index");
531     }
532
533     if (getParser().Lex().isNot(AsmToken::RParen))
534       return Error(Parser.getTok().getLoc(), "expected ')'");
535
536     EndLoc = Tok.getLoc();
537     Parser.Lex(); // Eat ')'
538     return false;
539   }
540
541   // If this is "db[0-7]", match it as an alias
542   // for dr[0-7].
543   if (RegNo == 0 && Tok.getString().size() == 3 &&
544       Tok.getString().startswith("db")) {
545     switch (Tok.getString()[2]) {
546     case '0': RegNo = X86::DR0; break;
547     case '1': RegNo = X86::DR1; break;
548     case '2': RegNo = X86::DR2; break;
549     case '3': RegNo = X86::DR3; break;
550     case '4': RegNo = X86::DR4; break;
551     case '5': RegNo = X86::DR5; break;
552     case '6': RegNo = X86::DR6; break;
553     case '7': RegNo = X86::DR7; break;
554     }
555
556     if (RegNo != 0) {
557       EndLoc = Tok.getLoc();
558       Parser.Lex(); // Eat it.
559       return false;
560     }
561   }
562
563   if (RegNo == 0)
564     return Error(StartLoc, "invalid register name",
565                  SMRange(StartLoc, Tok.getEndLoc()));
566
567   EndLoc = Tok.getEndLoc();
568   Parser.Lex(); // Eat identifier token.
569   return false;
570 }
571
572 X86Operand *X86AsmParser::ParseOperand() {
573   if (getParser().getAssemblerDialect())
574     return ParseIntelOperand();
575   return ParseATTOperand();
576 }
577
578 /// getIntelRegister - If this is an intel register operand
579 /// then return register number, otherwise return 0;
580 static unsigned getIntelRegisterOperand(StringRef Str) {
581   unsigned RegNo = MatchRegisterName(Str);
582   // If the match failed, try the register name as lowercase.
583   if (RegNo == 0)
584     RegNo = MatchRegisterName(Str.lower());
585   return RegNo;
586 }
587
588 /// getIntelMemOperandSize - Return intel memory operand size.
589 static unsigned getIntelMemOperandSize(StringRef OpStr) {
590   unsigned Size = 0;
591   if (OpStr == "BYTE") Size = 8;
592   if (OpStr == "WORD") Size = 16;
593   if (OpStr == "DWORD") Size = 32;
594   if (OpStr == "QWORD") Size = 64;
595   if (OpStr == "XWORD") Size = 80;
596   if (OpStr == "XMMWORD") Size = 128;
597   if (OpStr == "YMMWORD") Size = 256;
598   return Size;
599 }
600
601 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned Size) {
602   unsigned SegReg = 0, BaseReg = 0, IndexReg = 0, Scale = 1;
603   const AsmToken &Tok = Parser.getTok();
604   SMLoc Start = Parser.getTok().getLoc(), End;
605
606   const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
607   // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
608
609   // Eat '['
610   if (getLexer().isNot(AsmToken::LBrac))
611     return ErrorOperand(Start, "Expected '[' token!");
612   Parser.Lex();
613   
614   if (getLexer().is(AsmToken::Identifier)) {
615     // Parse BaseReg
616     BaseReg = getIntelRegisterOperand(Tok.getString());
617     if (BaseReg)
618       Parser.Lex();
619     else {
620       // Handle '[' 'symbol' ']'
621       const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
622       if (getParser().ParseExpression(Disp, End)) return 0;
623       if (getLexer().isNot(AsmToken::RBrac))
624         return ErrorOperand(Start, "Expected ']' token!");
625       Parser.Lex();
626       return X86Operand::CreateMem(Disp, Start, End, Size);
627     }
628   } else if (getLexer().is(AsmToken::Integer)) {
629       // Handle '[' number ']'
630       const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
631       if (getParser().ParseExpression(Disp, End)) return 0;
632       if (getLexer().isNot(AsmToken::RBrac))
633         return ErrorOperand(Start, "Expected ']' token!");
634       Parser.Lex();
635       return X86Operand::CreateMem(Disp, Start, End, Size);
636   }
637
638   if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
639     bool isPlus = getLexer().is(AsmToken::Plus);
640     Parser.Lex();
641     SMLoc PlusLoc = Parser.getTok().getLoc();
642     if (getLexer().is(AsmToken::Integer)) {
643       int64_t Val = Parser.getTok().getIntVal();
644       Parser.Lex();
645       if (getLexer().is(AsmToken::Star)) {
646         Parser.Lex();
647         SMLoc IdxRegLoc = Parser.getTok().getLoc();
648         IndexReg = getIntelRegisterOperand(Parser.getTok().getString());
649         if (!IndexReg) return ErrorOperand(IdxRegLoc, "Expected register");
650         Parser.Lex(); // Eat register
651         Scale = Val;
652       } else if (getLexer().is(AsmToken::RBrac)) {
653         const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
654         Disp = isPlus ? ValExpr : MCUnaryExpr::CreateMinus(ValExpr, getContext());
655       } else
656         return ErrorOperand(PlusLoc, "unexpected token after +");
657     } else if (getLexer().is(AsmToken::Identifier)) {
658       IndexReg = getIntelRegisterOperand(Tok.getString());
659       if (IndexReg)
660         Parser.Lex();
661     }
662   }
663
664   if (getLexer().isNot(AsmToken::RBrac))
665     if (getParser().ParseExpression(Disp, End)) return 0;
666
667   End = Parser.getTok().getLoc();
668   if (getLexer().isNot(AsmToken::RBrac))
669     return ErrorOperand(End, "expected ']' token!");
670   Parser.Lex();
671   End = Parser.getTok().getLoc();
672   return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
673                                Start, End, Size);
674 }
675
676 /// ParseIntelMemOperand - Parse intel style memory operand.
677 X86Operand *X86AsmParser::ParseIntelMemOperand() {
678   const AsmToken &Tok = Parser.getTok();
679   SMLoc Start = Parser.getTok().getLoc(), End;
680
681   unsigned Size = getIntelMemOperandSize(Tok.getString());
682   if (Size) {
683     Parser.Lex();
684     assert (Tok.getString() == "PTR" && "Unexpected token!");
685     Parser.Lex();
686   }
687
688   if (getLexer().is(AsmToken::LBrac))
689     return ParseIntelBracExpression(Size);
690
691   const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
692   if (getParser().ParseExpression(Disp, End)) return 0;
693   return X86Operand::CreateMem(Disp, Start, End, Size);
694 }
695
696 X86Operand *X86AsmParser::ParseIntelOperand() {
697   StringRef TokenString = Parser.getTok().getString();
698   SMLoc Start = Parser.getTok().getLoc(), End;
699
700   // immediate.
701   if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
702       getLexer().is(AsmToken::Minus)) {
703     const MCExpr *Val;
704     if (!getParser().ParseExpression(Val, End)) {
705       End = Parser.getTok().getLoc();
706       return X86Operand::CreateImm(Val, Start, End);
707     }
708   }
709
710   // register
711   if(unsigned RegNo = getIntelRegisterOperand(TokenString)) {
712     Parser.Lex();
713     End = Parser.getTok().getLoc();
714     return X86Operand::CreateReg(RegNo, Start, End);
715   }
716
717   // mem operand
718   return ParseIntelMemOperand();
719 }
720
721 X86Operand *X86AsmParser::ParseATTOperand() {
722   switch (getLexer().getKind()) {
723   default:
724     // Parse a memory operand with no segment register.
725     return ParseMemOperand(0, Parser.getTok().getLoc());
726   case AsmToken::Percent: {
727     // Read the register.
728     unsigned RegNo;
729     SMLoc Start, End;
730     if (ParseRegister(RegNo, Start, End)) return 0;
731     if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
732       Error(Start, "%eiz and %riz can only be used as index registers",
733             SMRange(Start, End));
734       return 0;
735     }
736
737     // If this is a segment register followed by a ':', then this is the start
738     // of a memory reference, otherwise this is a normal register reference.
739     if (getLexer().isNot(AsmToken::Colon))
740       return X86Operand::CreateReg(RegNo, Start, End);
741
742
743     getParser().Lex(); // Eat the colon.
744     return ParseMemOperand(RegNo, Start);
745   }
746   case AsmToken::Dollar: {
747     // $42 -> immediate.
748     SMLoc Start = Parser.getTok().getLoc(), End;
749     Parser.Lex();
750     const MCExpr *Val;
751     if (getParser().ParseExpression(Val, End))
752       return 0;
753     return X86Operand::CreateImm(Val, Start, End);
754   }
755   }
756 }
757
758 /// ParseMemOperand: segment: disp(basereg, indexreg, scale).  The '%ds:' prefix
759 /// has already been parsed if present.
760 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
761
762   // We have to disambiguate a parenthesized expression "(4+5)" from the start
763   // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)".  The
764   // only way to do this without lookahead is to eat the '(' and see what is
765   // after it.
766   const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
767   if (getLexer().isNot(AsmToken::LParen)) {
768     SMLoc ExprEnd;
769     if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
770
771     // After parsing the base expression we could either have a parenthesized
772     // memory address or not.  If not, return now.  If so, eat the (.
773     if (getLexer().isNot(AsmToken::LParen)) {
774       // Unless we have a segment register, treat this as an immediate.
775       if (SegReg == 0)
776         return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
777       return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
778     }
779
780     // Eat the '('.
781     Parser.Lex();
782   } else {
783     // Okay, we have a '('.  We don't know if this is an expression or not, but
784     // so we have to eat the ( to see beyond it.
785     SMLoc LParenLoc = Parser.getTok().getLoc();
786     Parser.Lex(); // Eat the '('.
787
788     if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
789       // Nothing to do here, fall into the code below with the '(' part of the
790       // memory operand consumed.
791     } else {
792       SMLoc ExprEnd;
793
794       // It must be an parenthesized expression, parse it now.
795       if (getParser().ParseParenExpression(Disp, ExprEnd))
796         return 0;
797
798       // After parsing the base expression we could either have a parenthesized
799       // memory address or not.  If not, return now.  If so, eat the (.
800       if (getLexer().isNot(AsmToken::LParen)) {
801         // Unless we have a segment register, treat this as an immediate.
802         if (SegReg == 0)
803           return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
804         return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
805       }
806
807       // Eat the '('.
808       Parser.Lex();
809     }
810   }
811
812   // If we reached here, then we just ate the ( of the memory operand.  Process
813   // the rest of the memory operand.
814   unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
815
816   if (getLexer().is(AsmToken::Percent)) {
817     SMLoc StartLoc, EndLoc;
818     if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
819     if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
820       Error(StartLoc, "eiz and riz can only be used as index registers",
821             SMRange(StartLoc, EndLoc));
822       return 0;
823     }
824   }
825
826   if (getLexer().is(AsmToken::Comma)) {
827     Parser.Lex(); // Eat the comma.
828
829     // Following the comma we should have either an index register, or a scale
830     // value. We don't support the later form, but we want to parse it
831     // correctly.
832     //
833     // Not that even though it would be completely consistent to support syntax
834     // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
835     if (getLexer().is(AsmToken::Percent)) {
836       SMLoc L;
837       if (ParseRegister(IndexReg, L, L)) return 0;
838
839       if (getLexer().isNot(AsmToken::RParen)) {
840         // Parse the scale amount:
841         //  ::= ',' [scale-expression]
842         if (getLexer().isNot(AsmToken::Comma)) {
843           Error(Parser.getTok().getLoc(),
844                 "expected comma in scale expression");
845           return 0;
846         }
847         Parser.Lex(); // Eat the comma.
848
849         if (getLexer().isNot(AsmToken::RParen)) {
850           SMLoc Loc = Parser.getTok().getLoc();
851
852           int64_t ScaleVal;
853           if (getParser().ParseAbsoluteExpression(ScaleVal))
854             return 0;
855
856           // Validate the scale amount.
857           if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
858             Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
859             return 0;
860           }
861           Scale = (unsigned)ScaleVal;
862         }
863       }
864     } else if (getLexer().isNot(AsmToken::RParen)) {
865       // A scale amount without an index is ignored.
866       // index.
867       SMLoc Loc = Parser.getTok().getLoc();
868
869       int64_t Value;
870       if (getParser().ParseAbsoluteExpression(Value))
871         return 0;
872
873       if (Value != 1)
874         Warning(Loc, "scale factor without index register is ignored");
875       Scale = 1;
876     }
877   }
878
879   // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
880   if (getLexer().isNot(AsmToken::RParen)) {
881     Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
882     return 0;
883   }
884   SMLoc MemEnd = Parser.getTok().getLoc();
885   Parser.Lex(); // Eat the ')'.
886
887   return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
888                                MemStart, MemEnd);
889 }
890
891 bool X86AsmParser::
892 ParseInstruction(StringRef Name, SMLoc NameLoc,
893                  SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
894   StringRef PatchedName = Name;
895
896   // FIXME: Hack to recognize setneb as setne.
897   if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
898       PatchedName != "setb" && PatchedName != "setnb")
899     PatchedName = PatchedName.substr(0, Name.size()-1);
900   
901   // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
902   const MCExpr *ExtraImmOp = 0;
903   if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
904       (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
905        PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
906     bool IsVCMP = PatchedName.startswith("vcmp");
907     unsigned SSECCIdx = IsVCMP ? 4 : 3;
908     unsigned SSEComparisonCode = StringSwitch<unsigned>(
909       PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
910       .Case("eq",          0)
911       .Case("lt",          1)
912       .Case("le",          2)
913       .Case("unord",       3)
914       .Case("neq",         4)
915       .Case("nlt",         5)
916       .Case("nle",         6)
917       .Case("ord",         7)
918       .Case("eq_uq",       8)
919       .Case("nge",         9)
920       .Case("ngt",      0x0A)
921       .Case("false",    0x0B)
922       .Case("neq_oq",   0x0C)
923       .Case("ge",       0x0D)
924       .Case("gt",       0x0E)
925       .Case("true",     0x0F)
926       .Case("eq_os",    0x10)
927       .Case("lt_oq",    0x11)
928       .Case("le_oq",    0x12)
929       .Case("unord_s",  0x13)
930       .Case("neq_us",   0x14)
931       .Case("nlt_uq",   0x15)
932       .Case("nle_uq",   0x16)
933       .Case("ord_s",    0x17)
934       .Case("eq_us",    0x18)
935       .Case("nge_uq",   0x19)
936       .Case("ngt_uq",   0x1A)
937       .Case("false_os", 0x1B)
938       .Case("neq_os",   0x1C)
939       .Case("ge_oq",    0x1D)
940       .Case("gt_oq",    0x1E)
941       .Case("true_us",  0x1F)
942       .Default(~0U);
943     if (SSEComparisonCode != ~0U) {
944       ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
945                                           getParser().getContext());
946       if (PatchedName.endswith("ss")) {
947         PatchedName = IsVCMP ? "vcmpss" : "cmpss";
948       } else if (PatchedName.endswith("sd")) {
949         PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
950       } else if (PatchedName.endswith("ps")) {
951         PatchedName = IsVCMP ? "vcmpps" : "cmpps";
952       } else {
953         assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
954         PatchedName = IsVCMP ? "vcmppd" : "cmppd";
955       }
956     }
957   }
958
959   Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
960
961   if (ExtraImmOp)
962     Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
963
964
965   // Determine whether this is an instruction prefix.
966   bool isPrefix =
967     Name == "lock" || Name == "rep" ||
968     Name == "repe" || Name == "repz" ||
969     Name == "repne" || Name == "repnz" ||
970     Name == "rex64" || Name == "data16";
971
972
973   // This does the actual operand parsing.  Don't parse any more if we have a
974   // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
975   // just want to parse the "lock" as the first instruction and the "incl" as
976   // the next one.
977   if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
978
979     // Parse '*' modifier.
980     if (getLexer().is(AsmToken::Star)) {
981       SMLoc Loc = Parser.getTok().getLoc();
982       Operands.push_back(X86Operand::CreateToken("*", Loc));
983       Parser.Lex(); // Eat the star.
984     }
985
986     // Read the first operand.
987     if (X86Operand *Op = ParseOperand())
988       Operands.push_back(Op);
989     else {
990       Parser.EatToEndOfStatement();
991       return true;
992     }
993
994     while (getLexer().is(AsmToken::Comma)) {
995       Parser.Lex();  // Eat the comma.
996
997       // Parse and remember the operand.
998       if (X86Operand *Op = ParseOperand())
999         Operands.push_back(Op);
1000       else {
1001         Parser.EatToEndOfStatement();
1002         return true;
1003       }
1004     }
1005
1006     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1007       SMLoc Loc = getLexer().getLoc();
1008       Parser.EatToEndOfStatement();
1009       return Error(Loc, "unexpected token in argument list");
1010     }
1011   }
1012
1013   if (getLexer().is(AsmToken::EndOfStatement))
1014     Parser.Lex(); // Consume the EndOfStatement
1015   else if (isPrefix && getLexer().is(AsmToken::Slash))
1016     Parser.Lex(); // Consume the prefix separator Slash
1017
1018   // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1019   // "outb %al, %dx".  Out doesn't take a memory form, but this is a widely
1020   // documented form in various unofficial manuals, so a lot of code uses it.
1021   if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1022       Operands.size() == 3) {
1023     X86Operand &Op = *(X86Operand*)Operands.back();
1024     if (Op.isMem() && Op.Mem.SegReg == 0 &&
1025         isa<MCConstantExpr>(Op.Mem.Disp) &&
1026         cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1027         Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1028       SMLoc Loc = Op.getEndLoc();
1029       Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1030       delete &Op;
1031     }
1032   }
1033   // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1034   if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1035       Operands.size() == 3) {
1036     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
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.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1043       delete &Op;
1044     }
1045   }
1046   // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1047   if (Name.startswith("ins") && Operands.size() == 3 &&
1048       (Name == "insb" || Name == "insw" || Name == "insl")) {
1049     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1050     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1051     if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1052       Operands.pop_back();
1053       Operands.pop_back();
1054       delete &Op;
1055       delete &Op2;
1056     }
1057   }
1058
1059   // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1060   if (Name.startswith("outs") && Operands.size() == 3 &&
1061       (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1062     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1063     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1064     if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1065       Operands.pop_back();
1066       Operands.pop_back();
1067       delete &Op;
1068       delete &Op2;
1069     }
1070   }
1071
1072   // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1073   if (Name.startswith("movs") && Operands.size() == 3 &&
1074       (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1075        (is64BitMode() && Name == "movsq"))) {
1076     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1077     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1078     if (isSrcOp(Op) && isDstOp(Op2)) {
1079       Operands.pop_back();
1080       Operands.pop_back();
1081       delete &Op;
1082       delete &Op2;
1083     }
1084   }
1085   // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1086   if (Name.startswith("lods") && Operands.size() == 3 &&
1087       (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1088        Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1089     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1090     X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1091     if (isSrcOp(*Op1) && Op2->isReg()) {
1092       const char *ins;
1093       unsigned reg = Op2->getReg();
1094       bool isLods = Name == "lods";
1095       if (reg == X86::AL && (isLods || Name == "lodsb"))
1096         ins = "lodsb";
1097       else if (reg == X86::AX && (isLods || Name == "lodsw"))
1098         ins = "lodsw";
1099       else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1100         ins = "lodsl";
1101       else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1102         ins = "lodsq";
1103       else
1104         ins = NULL;
1105       if (ins != NULL) {
1106         Operands.pop_back();
1107         Operands.pop_back();
1108         delete Op1;
1109         delete Op2;
1110         if (Name != ins)
1111           static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1112       }
1113     }
1114   }
1115   // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1116   if (Name.startswith("stos") && Operands.size() == 3 &&
1117       (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1118        Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1119     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1120     X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1121     if (isDstOp(*Op2) && Op1->isReg()) {
1122       const char *ins;
1123       unsigned reg = Op1->getReg();
1124       bool isStos = Name == "stos";
1125       if (reg == X86::AL && (isStos || Name == "stosb"))
1126         ins = "stosb";
1127       else if (reg == X86::AX && (isStos || Name == "stosw"))
1128         ins = "stosw";
1129       else if (reg == X86::EAX && (isStos || Name == "stosl"))
1130         ins = "stosl";
1131       else if (reg == X86::RAX && (isStos || Name == "stosq"))
1132         ins = "stosq";
1133       else
1134         ins = NULL;
1135       if (ins != NULL) {
1136         Operands.pop_back();
1137         Operands.pop_back();
1138         delete Op1;
1139         delete Op2;
1140         if (Name != ins)
1141           static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1142       }
1143     }
1144   }
1145
1146   // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>.  Canonicalize to
1147   // "shift <op>".
1148   if ((Name.startswith("shr") || Name.startswith("sar") ||
1149        Name.startswith("shl") || Name.startswith("sal") ||
1150        Name.startswith("rcl") || Name.startswith("rcr") ||
1151        Name.startswith("rol") || Name.startswith("ror")) &&
1152       Operands.size() == 3) {
1153     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1154     if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1155         cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1156       delete Operands[1];
1157       Operands.erase(Operands.begin() + 1);
1158     }
1159   }
1160   
1161   // Transforms "int $3" into "int3" as a size optimization.  We can't write an
1162   // instalias with an immediate operand yet.
1163   if (Name == "int" && Operands.size() == 2) {
1164     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1165     if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1166         cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1167       delete Operands[1];
1168       Operands.erase(Operands.begin() + 1);
1169       static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1170     }
1171   }
1172
1173   return false;
1174 }
1175
1176 bool X86AsmParser::
1177 processInstruction(MCInst &Inst,
1178                    const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1179   switch (Inst.getOpcode()) {
1180   default: return false;
1181   case X86::AND16i16: {
1182     if (!Inst.getOperand(0).isImm() ||
1183         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1184       return false;
1185
1186     MCInst TmpInst;
1187     TmpInst.setOpcode(X86::AND16ri8);
1188     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1189     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1190     TmpInst.addOperand(Inst.getOperand(0));
1191     Inst = TmpInst;
1192     return true;
1193   }
1194   case X86::AND32i32: {
1195     if (!Inst.getOperand(0).isImm() ||
1196         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1197       return false;
1198
1199     MCInst TmpInst;
1200     TmpInst.setOpcode(X86::AND32ri8);
1201     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1202     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1203     TmpInst.addOperand(Inst.getOperand(0));
1204     Inst = TmpInst;
1205     return true;
1206   }
1207   case X86::AND64i32: {
1208     if (!Inst.getOperand(0).isImm() ||
1209         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1210       return false;
1211
1212     MCInst TmpInst;
1213     TmpInst.setOpcode(X86::AND64ri8);
1214     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1215     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1216     TmpInst.addOperand(Inst.getOperand(0));
1217     Inst = TmpInst;
1218     return true;
1219   }
1220   }
1221   return false;
1222 }
1223
1224 bool X86AsmParser::
1225 MatchAndEmitInstruction(SMLoc IDLoc,
1226                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1227                         MCStreamer &Out) {
1228   assert(!Operands.empty() && "Unexpect empty operand list!");
1229   X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1230   assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1231
1232   // First, handle aliases that expand to multiple instructions.
1233   // FIXME: This should be replaced with a real .td file alias mechanism.
1234   // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
1235   // call.
1236   if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1237       Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1238       Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1239       Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1240     MCInst Inst;
1241     Inst.setOpcode(X86::WAIT);
1242     Out.EmitInstruction(Inst);
1243
1244     const char *Repl =
1245       StringSwitch<const char*>(Op->getToken())
1246         .Case("finit",  "fninit")
1247         .Case("fsave",  "fnsave")
1248         .Case("fstcw",  "fnstcw")
1249         .Case("fstcww",  "fnstcw")
1250         .Case("fstenv", "fnstenv")
1251         .Case("fstsw",  "fnstsw")
1252         .Case("fstsww", "fnstsw")
1253         .Case("fclex",  "fnclex")
1254         .Default(0);
1255     assert(Repl && "Unknown wait-prefixed instruction");
1256     delete Operands[0];
1257     Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1258   }
1259
1260   bool WasOriginallyInvalidOperand = false;
1261   unsigned OrigErrorInfo;
1262   MCInst Inst;
1263
1264   // First, try a direct match.
1265   switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo, 
1266                                getParser().getAssemblerDialect())) {
1267   default: break;
1268   case Match_Success:
1269     // Some instructions need post-processing to, for example, tweak which
1270     // encoding is selected. Loop on it while changes happen so the
1271     // individual transformations can chain off each other. 
1272     while (processInstruction(Inst, Operands))
1273       ;
1274
1275     Out.EmitInstruction(Inst);
1276     return false;
1277   case Match_MissingFeature:
1278     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1279     return true;
1280   case Match_ConversionFail:
1281     return Error(IDLoc, "unable to convert operands to instruction");
1282   case Match_InvalidOperand:
1283     WasOriginallyInvalidOperand = true;
1284     break;
1285   case Match_MnemonicFail:
1286     break;
1287   }
1288
1289   // FIXME: Ideally, we would only attempt suffix matches for things which are
1290   // valid prefixes, and we could just infer the right unambiguous
1291   // type. However, that requires substantially more matcher support than the
1292   // following hack.
1293
1294   // Change the operand to point to a temporary token.
1295   StringRef Base = Op->getToken();
1296   SmallString<16> Tmp;
1297   Tmp += Base;
1298   Tmp += ' ';
1299   Op->setTokenValue(Tmp.str());
1300
1301   // If this instruction starts with an 'f', then it is a floating point stack
1302   // instruction.  These come in up to three forms for 32-bit, 64-bit, and
1303   // 80-bit floating point, which use the suffixes s,l,t respectively.
1304   //
1305   // Otherwise, we assume that this may be an integer instruction, which comes
1306   // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1307   const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1308   
1309   // Check for the various suffix matches.
1310   Tmp[Base.size()] = Suffixes[0];
1311   unsigned ErrorInfoIgnore;
1312   unsigned Match1, Match2, Match3, Match4;
1313   
1314   Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1315   Tmp[Base.size()] = Suffixes[1];
1316   Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1317   Tmp[Base.size()] = Suffixes[2];
1318   Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1319   Tmp[Base.size()] = Suffixes[3];
1320   Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1321
1322   // Restore the old token.
1323   Op->setTokenValue(Base);
1324
1325   // If exactly one matched, then we treat that as a successful match (and the
1326   // instruction will already have been filled in correctly, since the failing
1327   // matches won't have modified it).
1328   unsigned NumSuccessfulMatches =
1329     (Match1 == Match_Success) + (Match2 == Match_Success) +
1330     (Match3 == Match_Success) + (Match4 == Match_Success);
1331   if (NumSuccessfulMatches == 1) {
1332     Out.EmitInstruction(Inst);
1333     return false;
1334   }
1335
1336   // Otherwise, the match failed, try to produce a decent error message.
1337
1338   // If we had multiple suffix matches, then identify this as an ambiguous
1339   // match.
1340   if (NumSuccessfulMatches > 1) {
1341     char MatchChars[4];
1342     unsigned NumMatches = 0;
1343     if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1344     if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1345     if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1346     if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1347
1348     SmallString<126> Msg;
1349     raw_svector_ostream OS(Msg);
1350     OS << "ambiguous instructions require an explicit suffix (could be ";
1351     for (unsigned i = 0; i != NumMatches; ++i) {
1352       if (i != 0)
1353         OS << ", ";
1354       if (i + 1 == NumMatches)
1355         OS << "or ";
1356       OS << "'" << Base << MatchChars[i] << "'";
1357     }
1358     OS << ")";
1359     Error(IDLoc, OS.str());
1360     return true;
1361   }
1362
1363   // Okay, we know that none of the variants matched successfully.
1364
1365   // If all of the instructions reported an invalid mnemonic, then the original
1366   // mnemonic was invalid.
1367   if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1368       (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1369     if (!WasOriginallyInvalidOperand) {
1370       return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1371                    Op->getLocRange());
1372     }
1373
1374     // Recover location info for the operand if we know which was the problem.
1375     if (OrigErrorInfo != ~0U) {
1376       if (OrigErrorInfo >= Operands.size())
1377         return Error(IDLoc, "too few operands for instruction");
1378
1379       X86Operand *Operand = (X86Operand*)Operands[OrigErrorInfo];
1380       if (Operand->getStartLoc().isValid()) {
1381         SMRange OperandRange = Operand->getLocRange();
1382         return Error(Operand->getStartLoc(), "invalid operand for instruction",
1383                      OperandRange);
1384       }
1385     }
1386
1387     return Error(IDLoc, "invalid operand for instruction");
1388   }
1389
1390   // If one instruction matched with a missing feature, report this as a
1391   // missing feature.
1392   if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1393       (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1394     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1395     return true;
1396   }
1397
1398   // If one instruction matched with an invalid operand, report this as an
1399   // operand failure.
1400   if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1401       (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1402     Error(IDLoc, "invalid operand for instruction");
1403     return true;
1404   }
1405
1406   // If all of these were an outright failure, report it in a useless way.
1407   Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
1408   return true;
1409 }
1410
1411
1412 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1413   StringRef IDVal = DirectiveID.getIdentifier();
1414   if (IDVal == ".word")
1415     return ParseDirectiveWord(2, DirectiveID.getLoc());
1416   else if (IDVal.startswith(".code"))
1417     return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1418   return true;
1419 }
1420
1421 /// ParseDirectiveWord
1422 ///  ::= .word [ expression (, expression)* ]
1423 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1424   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1425     for (;;) {
1426       const MCExpr *Value;
1427       if (getParser().ParseExpression(Value))
1428         return true;
1429       
1430       getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1431       
1432       if (getLexer().is(AsmToken::EndOfStatement))
1433         break;
1434       
1435       // FIXME: Improve diagnostic.
1436       if (getLexer().isNot(AsmToken::Comma))
1437         return Error(L, "unexpected token in directive");
1438       Parser.Lex();
1439     }
1440   }
1441   
1442   Parser.Lex();
1443   return false;
1444 }
1445
1446 /// ParseDirectiveCode
1447 ///  ::= .code32 | .code64
1448 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1449   if (IDVal == ".code32") {
1450     Parser.Lex();
1451     if (is64BitMode()) {
1452       SwitchMode();
1453       getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1454     }
1455   } else if (IDVal == ".code64") {
1456     Parser.Lex();
1457     if (!is64BitMode()) {
1458       SwitchMode();
1459       getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1460     }
1461   } else {
1462     return Error(L, "unexpected directive " + IDVal);
1463   }
1464
1465   return false;
1466 }
1467
1468
1469 extern "C" void LLVMInitializeX86AsmLexer();
1470
1471 // Force static initialization.
1472 extern "C" void LLVMInitializeX86AsmParser() {
1473   RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1474   RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1475   LLVMInitializeX86AsmLexer();
1476 }
1477
1478 #define GET_REGISTER_MATCHER
1479 #define GET_MATCHER_IMPLEMENTATION
1480 #include "X86GenAsmMatcher.inc"