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