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