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