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