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