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