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