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