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