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