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