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