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