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