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