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