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