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