1 //===-- X86AsmParser.cpp - Parse X86 assembly to MCInst instructions ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "MCTargetDesc/X86BaseInfo.h"
10 #include "MCTargetDesc/X86IntelInstPrinter.h"
11 #include "MCTargetDesc/X86MCExpr.h"
12 #include "MCTargetDesc/X86TargetStreamer.h"
13 #include "TargetInfo/X86TargetInfo.h"
14 #include "X86AsmParserCommon.h"
15 #include "X86Operand.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCParser/MCAsmLexer.h"
26 #include "llvm/MC/MCParser/MCAsmParser.h"
27 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
28 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
29 #include "llvm/MC/MCRegisterInfo.h"
30 #include "llvm/MC/MCSection.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSubtargetInfo.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm>
38 #include <memory>
39 
40 using namespace llvm;
41 
42 static bool checkScale(unsigned Scale, StringRef &ErrMsg) {
43   if (Scale != 1 && Scale != 2 && Scale != 4 && Scale != 8) {
44     ErrMsg = "scale factor in address must be 1, 2, 4 or 8";
45     return true;
46   }
47   return false;
48 }
49 
50 namespace {
51 
52 static const char OpPrecedence[] = {
53   0, // IC_OR
54   1, // IC_XOR
55   2, // IC_AND
56   3, // IC_LSHIFT
57   3, // IC_RSHIFT
58   4, // IC_PLUS
59   4, // IC_MINUS
60   5, // IC_MULTIPLY
61   5, // IC_DIVIDE
62   5, // IC_MOD
63   6, // IC_NOT
64   7, // IC_NEG
65   8, // IC_RPAREN
66   9, // IC_LPAREN
67   0, // IC_IMM
68   0  // IC_REGISTER
69 };
70 
71 class X86AsmParser : public MCTargetAsmParser {
72   ParseInstructionInfo *InstInfo;
73   bool Code16GCC;
74 
75   enum VEXEncoding {
76     VEXEncoding_Default,
77     VEXEncoding_VEX2,
78     VEXEncoding_VEX3,
79     VEXEncoding_EVEX,
80   };
81 
82   VEXEncoding ForcedVEXEncoding = VEXEncoding_Default;
83 
84 private:
85   SMLoc consumeToken() {
86     MCAsmParser &Parser = getParser();
87     SMLoc Result = Parser.getTok().getLoc();
88     Parser.Lex();
89     return Result;
90   }
91 
92   X86TargetStreamer &getTargetStreamer() {
93     assert(getParser().getStreamer().getTargetStreamer() &&
94            "do not have a target streamer");
95     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
96     return static_cast<X86TargetStreamer &>(TS);
97   }
98 
99   unsigned MatchInstruction(const OperandVector &Operands, MCInst &Inst,
100                             uint64_t &ErrorInfo, FeatureBitset &MissingFeatures,
101                             bool matchingInlineAsm, unsigned VariantID = 0) {
102     // In Code16GCC mode, match as 32-bit.
103     if (Code16GCC)
104       SwitchMode(X86::Mode32Bit);
105     unsigned rv = MatchInstructionImpl(Operands, Inst, ErrorInfo,
106                                        MissingFeatures, matchingInlineAsm,
107                                        VariantID);
108     if (Code16GCC)
109       SwitchMode(X86::Mode16Bit);
110     return rv;
111   }
112 
113   enum InfixCalculatorTok {
114     IC_OR = 0,
115     IC_XOR,
116     IC_AND,
117     IC_LSHIFT,
118     IC_RSHIFT,
119     IC_PLUS,
120     IC_MINUS,
121     IC_MULTIPLY,
122     IC_DIVIDE,
123     IC_MOD,
124     IC_NOT,
125     IC_NEG,
126     IC_RPAREN,
127     IC_LPAREN,
128     IC_IMM,
129     IC_REGISTER
130   };
131 
132   enum IntelOperatorKind {
133     IOK_INVALID = 0,
134     IOK_LENGTH,
135     IOK_SIZE,
136     IOK_TYPE,
137   };
138 
139   class InfixCalculator {
140     typedef std::pair< InfixCalculatorTok, int64_t > ICToken;
141     SmallVector<InfixCalculatorTok, 4> InfixOperatorStack;
142     SmallVector<ICToken, 4> PostfixStack;
143 
144     bool isUnaryOperator(const InfixCalculatorTok Op) {
145       return Op == IC_NEG || Op == IC_NOT;
146     }
147 
148   public:
149     int64_t popOperand() {
150       assert (!PostfixStack.empty() && "Poped an empty stack!");
151       ICToken Op = PostfixStack.pop_back_val();
152       if (!(Op.first == IC_IMM || Op.first == IC_REGISTER))
153         return -1; // The invalid Scale value will be caught later by checkScale
154       return Op.second;
155     }
156     void pushOperand(InfixCalculatorTok Op, int64_t Val = 0) {
157       assert ((Op == IC_IMM || Op == IC_REGISTER) &&
158               "Unexpected operand!");
159       PostfixStack.push_back(std::make_pair(Op, Val));
160     }
161 
162     void popOperator() { InfixOperatorStack.pop_back(); }
163     void pushOperator(InfixCalculatorTok Op) {
164       // Push the new operator if the stack is empty.
165       if (InfixOperatorStack.empty()) {
166         InfixOperatorStack.push_back(Op);
167         return;
168       }
169 
170       // Push the new operator if it has a higher precedence than the operator
171       // on the top of the stack or the operator on the top of the stack is a
172       // left parentheses.
173       unsigned Idx = InfixOperatorStack.size() - 1;
174       InfixCalculatorTok StackOp = InfixOperatorStack[Idx];
175       if (OpPrecedence[Op] > OpPrecedence[StackOp] || StackOp == IC_LPAREN) {
176         InfixOperatorStack.push_back(Op);
177         return;
178       }
179 
180       // The operator on the top of the stack has higher precedence than the
181       // new operator.
182       unsigned ParenCount = 0;
183       while (1) {
184         // Nothing to process.
185         if (InfixOperatorStack.empty())
186           break;
187 
188         Idx = InfixOperatorStack.size() - 1;
189         StackOp = InfixOperatorStack[Idx];
190         if (!(OpPrecedence[StackOp] >= OpPrecedence[Op] || ParenCount))
191           break;
192 
193         // If we have an even parentheses count and we see a left parentheses,
194         // then stop processing.
195         if (!ParenCount && StackOp == IC_LPAREN)
196           break;
197 
198         if (StackOp == IC_RPAREN) {
199           ++ParenCount;
200           InfixOperatorStack.pop_back();
201         } else if (StackOp == IC_LPAREN) {
202           --ParenCount;
203           InfixOperatorStack.pop_back();
204         } else {
205           InfixOperatorStack.pop_back();
206           PostfixStack.push_back(std::make_pair(StackOp, 0));
207         }
208       }
209       // Push the new operator.
210       InfixOperatorStack.push_back(Op);
211     }
212 
213     int64_t execute() {
214       // Push any remaining operators onto the postfix stack.
215       while (!InfixOperatorStack.empty()) {
216         InfixCalculatorTok StackOp = InfixOperatorStack.pop_back_val();
217         if (StackOp != IC_LPAREN && StackOp != IC_RPAREN)
218           PostfixStack.push_back(std::make_pair(StackOp, 0));
219       }
220 
221       if (PostfixStack.empty())
222         return 0;
223 
224       SmallVector<ICToken, 16> OperandStack;
225       for (unsigned i = 0, e = PostfixStack.size(); i != e; ++i) {
226         ICToken Op = PostfixStack[i];
227         if (Op.first == IC_IMM || Op.first == IC_REGISTER) {
228           OperandStack.push_back(Op);
229         } else if (isUnaryOperator(Op.first)) {
230           assert (OperandStack.size() > 0 && "Too few operands.");
231           ICToken Operand = OperandStack.pop_back_val();
232           assert (Operand.first == IC_IMM &&
233                   "Unary operation with a register!");
234           switch (Op.first) {
235           default:
236             report_fatal_error("Unexpected operator!");
237             break;
238           case IC_NEG:
239             OperandStack.push_back(std::make_pair(IC_IMM, -Operand.second));
240             break;
241           case IC_NOT:
242             OperandStack.push_back(std::make_pair(IC_IMM, ~Operand.second));
243             break;
244           }
245         } else {
246           assert (OperandStack.size() > 1 && "Too few operands.");
247           int64_t Val;
248           ICToken Op2 = OperandStack.pop_back_val();
249           ICToken Op1 = OperandStack.pop_back_val();
250           switch (Op.first) {
251           default:
252             report_fatal_error("Unexpected operator!");
253             break;
254           case IC_PLUS:
255             Val = Op1.second + Op2.second;
256             OperandStack.push_back(std::make_pair(IC_IMM, Val));
257             break;
258           case IC_MINUS:
259             Val = Op1.second - Op2.second;
260             OperandStack.push_back(std::make_pair(IC_IMM, Val));
261             break;
262           case IC_MULTIPLY:
263             assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
264                     "Multiply operation with an immediate and a register!");
265             Val = Op1.second * Op2.second;
266             OperandStack.push_back(std::make_pair(IC_IMM, Val));
267             break;
268           case IC_DIVIDE:
269             assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
270                     "Divide operation with an immediate and a register!");
271             assert (Op2.second != 0 && "Division by zero!");
272             Val = Op1.second / Op2.second;
273             OperandStack.push_back(std::make_pair(IC_IMM, Val));
274             break;
275           case IC_MOD:
276             assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
277                     "Modulo operation with an immediate and a register!");
278             Val = Op1.second % Op2.second;
279             OperandStack.push_back(std::make_pair(IC_IMM, Val));
280             break;
281           case IC_OR:
282             assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
283                     "Or operation with an immediate and a register!");
284             Val = Op1.second | Op2.second;
285             OperandStack.push_back(std::make_pair(IC_IMM, Val));
286             break;
287           case IC_XOR:
288             assert(Op1.first == IC_IMM && Op2.first == IC_IMM &&
289               "Xor operation with an immediate and a register!");
290             Val = Op1.second ^ Op2.second;
291             OperandStack.push_back(std::make_pair(IC_IMM, Val));
292             break;
293           case IC_AND:
294             assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
295                     "And operation with an immediate and a register!");
296             Val = Op1.second & Op2.second;
297             OperandStack.push_back(std::make_pair(IC_IMM, Val));
298             break;
299           case IC_LSHIFT:
300             assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
301                     "Left shift operation with an immediate and a register!");
302             Val = Op1.second << Op2.second;
303             OperandStack.push_back(std::make_pair(IC_IMM, Val));
304             break;
305           case IC_RSHIFT:
306             assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
307                     "Right shift operation with an immediate and a register!");
308             Val = Op1.second >> Op2.second;
309             OperandStack.push_back(std::make_pair(IC_IMM, Val));
310             break;
311           }
312         }
313       }
314       assert (OperandStack.size() == 1 && "Expected a single result.");
315       return OperandStack.pop_back_val().second;
316     }
317   };
318 
319   enum IntelExprState {
320     IES_INIT,
321     IES_OR,
322     IES_XOR,
323     IES_AND,
324     IES_LSHIFT,
325     IES_RSHIFT,
326     IES_PLUS,
327     IES_MINUS,
328     IES_OFFSET,
329     IES_NOT,
330     IES_MULTIPLY,
331     IES_DIVIDE,
332     IES_MOD,
333     IES_LBRAC,
334     IES_RBRAC,
335     IES_LPAREN,
336     IES_RPAREN,
337     IES_REGISTER,
338     IES_INTEGER,
339     IES_IDENTIFIER,
340     IES_ERROR
341   };
342 
343   class IntelExprStateMachine {
344     IntelExprState State, PrevState;
345     unsigned BaseReg, IndexReg, TmpReg, Scale;
346     int64_t Imm;
347     const MCExpr *Sym;
348     StringRef SymName;
349     InfixCalculator IC;
350     InlineAsmIdentifierInfo Info;
351     short BracCount;
352     bool MemExpr;
353     bool OffsetOperator;
354     SMLoc OffsetOperatorLoc;
355 
356     bool setSymRef(const MCExpr *Val, StringRef ID, StringRef &ErrMsg) {
357       if (Sym) {
358         ErrMsg = "cannot use more than one symbol in memory operand";
359         return true;
360       }
361       Sym = Val;
362       SymName = ID;
363       return false;
364     }
365 
366   public:
367     IntelExprStateMachine()
368         : State(IES_INIT), PrevState(IES_ERROR), BaseReg(0), IndexReg(0),
369           TmpReg(0), Scale(0), Imm(0), Sym(nullptr), BracCount(0),
370           MemExpr(false), OffsetOperator(false) {}
371 
372     void addImm(int64_t imm) { Imm += imm; }
373     short getBracCount() { return BracCount; }
374     bool isMemExpr() { return MemExpr; }
375     bool isOffsetOperator() { return OffsetOperator; }
376     SMLoc getOffsetLoc() { return OffsetOperatorLoc; }
377     unsigned getBaseReg() { return BaseReg; }
378     unsigned getIndexReg() { return IndexReg; }
379     unsigned getScale() { return Scale; }
380     const MCExpr *getSym() { return Sym; }
381     StringRef getSymName() { return SymName; }
382     int64_t getImm() { return Imm + IC.execute(); }
383     bool isValidEndState() {
384       return State == IES_RBRAC || State == IES_INTEGER;
385     }
386     bool hadError() { return State == IES_ERROR; }
387     InlineAsmIdentifierInfo &getIdentifierInfo() { return Info; }
388 
389     void onOr() {
390       IntelExprState CurrState = State;
391       switch (State) {
392       default:
393         State = IES_ERROR;
394         break;
395       case IES_INTEGER:
396       case IES_RPAREN:
397       case IES_REGISTER:
398         State = IES_OR;
399         IC.pushOperator(IC_OR);
400         break;
401       }
402       PrevState = CurrState;
403     }
404     void onXor() {
405       IntelExprState CurrState = State;
406       switch (State) {
407       default:
408         State = IES_ERROR;
409         break;
410       case IES_INTEGER:
411       case IES_RPAREN:
412       case IES_REGISTER:
413         State = IES_XOR;
414         IC.pushOperator(IC_XOR);
415         break;
416       }
417       PrevState = CurrState;
418     }
419     void onAnd() {
420       IntelExprState CurrState = State;
421       switch (State) {
422       default:
423         State = IES_ERROR;
424         break;
425       case IES_INTEGER:
426       case IES_RPAREN:
427       case IES_REGISTER:
428         State = IES_AND;
429         IC.pushOperator(IC_AND);
430         break;
431       }
432       PrevState = CurrState;
433     }
434     void onLShift() {
435       IntelExprState CurrState = State;
436       switch (State) {
437       default:
438         State = IES_ERROR;
439         break;
440       case IES_INTEGER:
441       case IES_RPAREN:
442       case IES_REGISTER:
443         State = IES_LSHIFT;
444         IC.pushOperator(IC_LSHIFT);
445         break;
446       }
447       PrevState = CurrState;
448     }
449     void onRShift() {
450       IntelExprState CurrState = State;
451       switch (State) {
452       default:
453         State = IES_ERROR;
454         break;
455       case IES_INTEGER:
456       case IES_RPAREN:
457       case IES_REGISTER:
458         State = IES_RSHIFT;
459         IC.pushOperator(IC_RSHIFT);
460         break;
461       }
462       PrevState = CurrState;
463     }
464     bool onPlus(StringRef &ErrMsg) {
465       IntelExprState CurrState = State;
466       switch (State) {
467       default:
468         State = IES_ERROR;
469         break;
470       case IES_INTEGER:
471       case IES_RPAREN:
472       case IES_REGISTER:
473       case IES_OFFSET:
474         State = IES_PLUS;
475         IC.pushOperator(IC_PLUS);
476         if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
477           // If we already have a BaseReg, then assume this is the IndexReg with
478           // no explicit scale.
479           if (!BaseReg) {
480             BaseReg = TmpReg;
481           } else {
482             if (IndexReg) {
483               ErrMsg = "BaseReg/IndexReg already set!";
484               return true;
485             }
486             IndexReg = TmpReg;
487             Scale = 0;
488           }
489         }
490         break;
491       }
492       PrevState = CurrState;
493       return false;
494     }
495     bool onMinus(StringRef &ErrMsg) {
496       IntelExprState CurrState = State;
497       switch (State) {
498       default:
499         State = IES_ERROR;
500         break;
501       case IES_OR:
502       case IES_XOR:
503       case IES_AND:
504       case IES_LSHIFT:
505       case IES_RSHIFT:
506       case IES_PLUS:
507       case IES_NOT:
508       case IES_MULTIPLY:
509       case IES_DIVIDE:
510       case IES_MOD:
511       case IES_LPAREN:
512       case IES_RPAREN:
513       case IES_LBRAC:
514       case IES_RBRAC:
515       case IES_INTEGER:
516       case IES_REGISTER:
517       case IES_INIT:
518       case IES_OFFSET:
519         State = IES_MINUS;
520         // push minus operator if it is not a negate operator
521         if (CurrState == IES_REGISTER || CurrState == IES_RPAREN ||
522             CurrState == IES_INTEGER  || CurrState == IES_RBRAC  ||
523             CurrState == IES_OFFSET)
524           IC.pushOperator(IC_MINUS);
525         else if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) {
526           // We have negate operator for Scale: it's illegal
527           ErrMsg = "Scale can't be negative";
528           return true;
529         } else
530           IC.pushOperator(IC_NEG);
531         if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
532           // If we already have a BaseReg, then assume this is the IndexReg with
533           // no explicit scale.
534           if (!BaseReg) {
535             BaseReg = TmpReg;
536           } else {
537             if (IndexReg) {
538               ErrMsg = "BaseReg/IndexReg already set!";
539               return true;
540             }
541             IndexReg = TmpReg;
542             Scale = 0;
543           }
544         }
545         break;
546       }
547       PrevState = CurrState;
548       return false;
549     }
550     void onNot() {
551       IntelExprState CurrState = State;
552       switch (State) {
553       default:
554         State = IES_ERROR;
555         break;
556       case IES_OR:
557       case IES_XOR:
558       case IES_AND:
559       case IES_LSHIFT:
560       case IES_RSHIFT:
561       case IES_PLUS:
562       case IES_MINUS:
563       case IES_NOT:
564       case IES_MULTIPLY:
565       case IES_DIVIDE:
566       case IES_MOD:
567       case IES_LPAREN:
568       case IES_LBRAC:
569       case IES_INIT:
570         State = IES_NOT;
571         IC.pushOperator(IC_NOT);
572         break;
573       }
574       PrevState = CurrState;
575     }
576     bool onRegister(unsigned Reg, StringRef &ErrMsg) {
577       IntelExprState CurrState = State;
578       switch (State) {
579       default:
580         State = IES_ERROR;
581         break;
582       case IES_PLUS:
583       case IES_LPAREN:
584       case IES_LBRAC:
585         State = IES_REGISTER;
586         TmpReg = Reg;
587         IC.pushOperand(IC_REGISTER);
588         break;
589       case IES_MULTIPLY:
590         // Index Register - Scale * Register
591         if (PrevState == IES_INTEGER) {
592           if (IndexReg) {
593             ErrMsg = "BaseReg/IndexReg already set!";
594             return true;
595           }
596           State = IES_REGISTER;
597           IndexReg = Reg;
598           // Get the scale and replace the 'Scale * Register' with '0'.
599           Scale = IC.popOperand();
600           if (checkScale(Scale, ErrMsg))
601             return true;
602           IC.pushOperand(IC_IMM);
603           IC.popOperator();
604         } else {
605           State = IES_ERROR;
606         }
607         break;
608       }
609       PrevState = CurrState;
610       return false;
611     }
612     bool onIdentifierExpr(const MCExpr *SymRef, StringRef SymRefName,
613                           const InlineAsmIdentifierInfo &IDInfo,
614                           bool ParsingMSInlineAsm, StringRef &ErrMsg) {
615       // InlineAsm: Treat an enum value as an integer
616       if (ParsingMSInlineAsm)
617         if (IDInfo.isKind(InlineAsmIdentifierInfo::IK_EnumVal))
618           return onInteger(IDInfo.Enum.EnumVal, ErrMsg);
619       // Treat a symbolic constant like an integer
620       if (auto *CE = dyn_cast<MCConstantExpr>(SymRef))
621         return onInteger(CE->getValue(), ErrMsg);
622       PrevState = State;
623       switch (State) {
624       default:
625         State = IES_ERROR;
626         break;
627       case IES_PLUS:
628       case IES_MINUS:
629       case IES_NOT:
630       case IES_INIT:
631       case IES_LBRAC:
632         if (setSymRef(SymRef, SymRefName, ErrMsg))
633           return true;
634         MemExpr = true;
635         State = IES_INTEGER;
636         IC.pushOperand(IC_IMM);
637         if (ParsingMSInlineAsm)
638           Info = IDInfo;
639         break;
640       }
641       return false;
642     }
643     bool onInteger(int64_t TmpInt, StringRef &ErrMsg) {
644       IntelExprState CurrState = State;
645       switch (State) {
646       default:
647         State = IES_ERROR;
648         break;
649       case IES_PLUS:
650       case IES_MINUS:
651       case IES_NOT:
652       case IES_OR:
653       case IES_XOR:
654       case IES_AND:
655       case IES_LSHIFT:
656       case IES_RSHIFT:
657       case IES_DIVIDE:
658       case IES_MOD:
659       case IES_MULTIPLY:
660       case IES_LPAREN:
661       case IES_INIT:
662       case IES_LBRAC:
663         State = IES_INTEGER;
664         if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) {
665           // Index Register - Register * Scale
666           if (IndexReg) {
667             ErrMsg = "BaseReg/IndexReg already set!";
668             return true;
669           }
670           IndexReg = TmpReg;
671           Scale = TmpInt;
672           if (checkScale(Scale, ErrMsg))
673             return true;
674           // Get the scale and replace the 'Register * Scale' with '0'.
675           IC.popOperator();
676         } else {
677           IC.pushOperand(IC_IMM, TmpInt);
678         }
679         break;
680       }
681       PrevState = CurrState;
682       return false;
683     }
684     void onStar() {
685       PrevState = State;
686       switch (State) {
687       default:
688         State = IES_ERROR;
689         break;
690       case IES_INTEGER:
691       case IES_REGISTER:
692       case IES_RPAREN:
693         State = IES_MULTIPLY;
694         IC.pushOperator(IC_MULTIPLY);
695         break;
696       }
697     }
698     void onDivide() {
699       PrevState = State;
700       switch (State) {
701       default:
702         State = IES_ERROR;
703         break;
704       case IES_INTEGER:
705       case IES_RPAREN:
706         State = IES_DIVIDE;
707         IC.pushOperator(IC_DIVIDE);
708         break;
709       }
710     }
711     void onMod() {
712       PrevState = State;
713       switch (State) {
714       default:
715         State = IES_ERROR;
716         break;
717       case IES_INTEGER:
718       case IES_RPAREN:
719         State = IES_MOD;
720         IC.pushOperator(IC_MOD);
721         break;
722       }
723     }
724     bool onLBrac() {
725       if (BracCount)
726         return true;
727       PrevState = State;
728       switch (State) {
729       default:
730         State = IES_ERROR;
731         break;
732       case IES_RBRAC:
733       case IES_INTEGER:
734       case IES_RPAREN:
735         State = IES_PLUS;
736         IC.pushOperator(IC_PLUS);
737         break;
738       case IES_INIT:
739         assert(!BracCount && "BracCount should be zero on parsing's start");
740         State = IES_LBRAC;
741         break;
742       }
743       MemExpr = true;
744       BracCount++;
745       return false;
746     }
747     bool onRBrac() {
748       IntelExprState CurrState = State;
749       switch (State) {
750       default:
751         State = IES_ERROR;
752         break;
753       case IES_INTEGER:
754       case IES_OFFSET:
755       case IES_REGISTER:
756       case IES_RPAREN:
757         if (BracCount-- != 1)
758           return true;
759         State = IES_RBRAC;
760         if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
761           // If we already have a BaseReg, then assume this is the IndexReg with
762           // no explicit scale.
763           if (!BaseReg) {
764             BaseReg = TmpReg;
765           } else {
766             assert (!IndexReg && "BaseReg/IndexReg already set!");
767             IndexReg = TmpReg;
768             Scale = 0;
769           }
770         }
771         break;
772       }
773       PrevState = CurrState;
774       return false;
775     }
776     void onLParen() {
777       IntelExprState CurrState = State;
778       switch (State) {
779       default:
780         State = IES_ERROR;
781         break;
782       case IES_PLUS:
783       case IES_MINUS:
784       case IES_NOT:
785       case IES_OR:
786       case IES_XOR:
787       case IES_AND:
788       case IES_LSHIFT:
789       case IES_RSHIFT:
790       case IES_MULTIPLY:
791       case IES_DIVIDE:
792       case IES_MOD:
793       case IES_LPAREN:
794       case IES_INIT:
795       case IES_LBRAC:
796         State = IES_LPAREN;
797         IC.pushOperator(IC_LPAREN);
798         break;
799       }
800       PrevState = CurrState;
801     }
802     void onRParen() {
803       PrevState = State;
804       switch (State) {
805       default:
806         State = IES_ERROR;
807         break;
808       case IES_INTEGER:
809       case IES_OFFSET:
810       case IES_REGISTER:
811       case IES_RPAREN:
812         State = IES_RPAREN;
813         IC.pushOperator(IC_RPAREN);
814         break;
815       }
816     }
817     bool onOffset(const MCExpr *Val, SMLoc OffsetLoc, StringRef ID,
818                   const InlineAsmIdentifierInfo &IDInfo, bool ParsingMSInlineAsm,
819                   StringRef &ErrMsg) {
820       PrevState = State;
821       switch (State) {
822       default:
823         ErrMsg = "unexpected offset operator expression";
824         return true;
825       case IES_PLUS:
826       case IES_INIT:
827       case IES_LBRAC:
828         if (setSymRef(Val, ID, ErrMsg))
829           return true;
830         OffsetOperator = true;
831         OffsetOperatorLoc = OffsetLoc;
832         State = IES_OFFSET;
833         // As we cannot yet resolve the actual value (offset), we retain
834         // the requested semantics by pushing a '0' to the operands stack
835         IC.pushOperand(IC_IMM);
836         if (ParsingMSInlineAsm) {
837           Info = IDInfo;
838         }
839         break;
840       }
841       return false;
842     }
843   };
844 
845   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None,
846              bool MatchingInlineAsm = false) {
847     MCAsmParser &Parser = getParser();
848     if (MatchingInlineAsm) {
849       if (!getLexer().isAtStartOfStatement())
850         Parser.eatToEndOfStatement();
851       return false;
852     }
853     return Parser.Error(L, Msg, Range);
854   }
855 
856   std::nullptr_t ErrorOperand(SMLoc Loc, StringRef Msg, SMRange R = SMRange()) {
857     Error(Loc, Msg, R);
858     return nullptr;
859   }
860 
861   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc,
862                      bool RestoreOnFailure);
863 
864   std::unique_ptr<X86Operand> DefaultMemSIOperand(SMLoc Loc);
865   std::unique_ptr<X86Operand> DefaultMemDIOperand(SMLoc Loc);
866   bool IsSIReg(unsigned Reg);
867   unsigned GetSIDIForRegClass(unsigned RegClassID, unsigned Reg, bool IsSIReg);
868   void
869   AddDefaultSrcDestOperands(OperandVector &Operands,
870                             std::unique_ptr<llvm::MCParsedAsmOperand> &&Src,
871                             std::unique_ptr<llvm::MCParsedAsmOperand> &&Dst);
872   bool VerifyAndAdjustOperands(OperandVector &OrigOperands,
873                                OperandVector &FinalOperands);
874   std::unique_ptr<X86Operand> ParseOperand();
875   std::unique_ptr<X86Operand> ParseATTOperand();
876   std::unique_ptr<X86Operand> ParseIntelOperand();
877   bool ParseIntelOffsetOperator(const MCExpr *&Val, StringRef &ID,
878                                 InlineAsmIdentifierInfo &Info, SMLoc &End);
879   bool ParseIntelDotOperator(IntelExprStateMachine &SM, SMLoc &End);
880   unsigned IdentifyIntelInlineAsmOperator(StringRef Name);
881   unsigned ParseIntelInlineAsmOperator(unsigned OpKind);
882   std::unique_ptr<X86Operand> ParseRoundingModeOp(SMLoc Start);
883   bool ParseIntelNamedOperator(StringRef Name, IntelExprStateMachine &SM,
884                                bool &ParseError, SMLoc &End);
885   void RewriteIntelExpression(IntelExprStateMachine &SM, SMLoc Start,
886                               SMLoc End);
887   bool ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End);
888   bool ParseIntelInlineAsmIdentifier(const MCExpr *&Val, StringRef &Identifier,
889                                      InlineAsmIdentifierInfo &Info,
890                                      bool IsUnevaluatedOperand, SMLoc &End,
891                                      bool IsParsingOffsetOperator = false);
892 
893   std::unique_ptr<X86Operand> ParseMemOperand(unsigned SegReg,
894                                               const MCExpr *&Disp,
895                                               const SMLoc &StartLoc,
896                                               SMLoc &EndLoc);
897 
898   X86::CondCode ParseConditionCode(StringRef CCode);
899 
900   bool ParseIntelMemoryOperandSize(unsigned &Size);
901   std::unique_ptr<X86Operand>
902   CreateMemForMSInlineAsm(unsigned SegReg, const MCExpr *Disp, unsigned BaseReg,
903                           unsigned IndexReg, unsigned Scale, SMLoc Start,
904                           SMLoc End, unsigned Size, StringRef Identifier,
905                           const InlineAsmIdentifierInfo &Info);
906 
907   bool parseDirectiveEven(SMLoc L);
908   bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
909 
910   /// CodeView FPO data directives.
911   bool parseDirectiveFPOProc(SMLoc L);
912   bool parseDirectiveFPOSetFrame(SMLoc L);
913   bool parseDirectiveFPOPushReg(SMLoc L);
914   bool parseDirectiveFPOStackAlloc(SMLoc L);
915   bool parseDirectiveFPOStackAlign(SMLoc L);
916   bool parseDirectiveFPOEndPrologue(SMLoc L);
917   bool parseDirectiveFPOEndProc(SMLoc L);
918   bool parseDirectiveFPOData(SMLoc L);
919 
920   /// SEH directives.
921   bool parseSEHRegisterNumber(unsigned RegClassID, unsigned &RegNo);
922   bool parseDirectiveSEHPushReg(SMLoc);
923   bool parseDirectiveSEHSetFrame(SMLoc);
924   bool parseDirectiveSEHSaveReg(SMLoc);
925   bool parseDirectiveSEHSaveXMM(SMLoc);
926   bool parseDirectiveSEHPushFrame(SMLoc);
927 
928   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
929 
930   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
931   bool processInstruction(MCInst &Inst, const OperandVector &Ops);
932 
933   /// Wrapper around MCStreamer::emitInstruction(). Possibly adds
934   /// instrumentation around Inst.
935   void emitInstruction(MCInst &Inst, OperandVector &Operands, MCStreamer &Out);
936 
937   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
938                                OperandVector &Operands, MCStreamer &Out,
939                                uint64_t &ErrorInfo,
940                                bool MatchingInlineAsm) override;
941 
942   void MatchFPUWaitAlias(SMLoc IDLoc, X86Operand &Op, OperandVector &Operands,
943                          MCStreamer &Out, bool MatchingInlineAsm);
944 
945   bool ErrorMissingFeature(SMLoc IDLoc, const FeatureBitset &MissingFeatures,
946                            bool MatchingInlineAsm);
947 
948   bool MatchAndEmitATTInstruction(SMLoc IDLoc, unsigned &Opcode,
949                                   OperandVector &Operands, MCStreamer &Out,
950                                   uint64_t &ErrorInfo,
951                                   bool MatchingInlineAsm);
952 
953   bool MatchAndEmitIntelInstruction(SMLoc IDLoc, unsigned &Opcode,
954                                     OperandVector &Operands, MCStreamer &Out,
955                                     uint64_t &ErrorInfo,
956                                     bool MatchingInlineAsm);
957 
958   bool OmitRegisterFromClobberLists(unsigned RegNo) override;
959 
960   /// Parses AVX512 specific operand primitives: masked registers ({%k<NUM>}, {z})
961   /// and memory broadcasting ({1to<NUM>}) primitives, updating Operands vector if required.
962   /// return false if no parsing errors occurred, true otherwise.
963   bool HandleAVX512Operand(OperandVector &Operands,
964                            const MCParsedAsmOperand &Op);
965 
966   bool ParseZ(std::unique_ptr<X86Operand> &Z, const SMLoc &StartLoc);
967 
968   bool is64BitMode() const {
969     // FIXME: Can tablegen auto-generate this?
970     return getSTI().getFeatureBits()[X86::Mode64Bit];
971   }
972   bool is32BitMode() const {
973     // FIXME: Can tablegen auto-generate this?
974     return getSTI().getFeatureBits()[X86::Mode32Bit];
975   }
976   bool is16BitMode() const {
977     // FIXME: Can tablegen auto-generate this?
978     return getSTI().getFeatureBits()[X86::Mode16Bit];
979   }
980   void SwitchMode(unsigned mode) {
981     MCSubtargetInfo &STI = copySTI();
982     FeatureBitset AllModes({X86::Mode64Bit, X86::Mode32Bit, X86::Mode16Bit});
983     FeatureBitset OldMode = STI.getFeatureBits() & AllModes;
984     FeatureBitset FB = ComputeAvailableFeatures(
985       STI.ToggleFeature(OldMode.flip(mode)));
986     setAvailableFeatures(FB);
987 
988     assert(FeatureBitset({mode}) == (STI.getFeatureBits() & AllModes));
989   }
990 
991   unsigned getPointerWidth() {
992     if (is16BitMode()) return 16;
993     if (is32BitMode()) return 32;
994     if (is64BitMode()) return 64;
995     llvm_unreachable("invalid mode");
996   }
997 
998   bool isParsingIntelSyntax() {
999     return getParser().getAssemblerDialect();
1000   }
1001 
1002   /// @name Auto-generated Matcher Functions
1003   /// {
1004 
1005 #define GET_ASSEMBLER_HEADER
1006 #include "X86GenAsmMatcher.inc"
1007 
1008   /// }
1009 
1010 public:
1011   enum X86MatchResultTy {
1012     Match_Unsupported = FIRST_TARGET_MATCH_RESULT_TY,
1013 #define GET_OPERAND_DIAGNOSTIC_TYPES
1014 #include "X86GenAsmMatcher.inc"
1015   };
1016 
1017   X86AsmParser(const MCSubtargetInfo &sti, MCAsmParser &Parser,
1018                const MCInstrInfo &mii, const MCTargetOptions &Options)
1019       : MCTargetAsmParser(Options, sti, mii),  InstInfo(nullptr),
1020         Code16GCC(false) {
1021 
1022     Parser.addAliasForDirective(".word", ".2byte");
1023 
1024     // Initialize the set of available features.
1025     setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));
1026   }
1027 
1028   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
1029   OperandMatchResultTy tryParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1030                                         SMLoc &EndLoc) override;
1031 
1032   bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
1033 
1034   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
1035                         SMLoc NameLoc, OperandVector &Operands) override;
1036 
1037   bool ParseDirective(AsmToken DirectiveID) override;
1038 };
1039 } // end anonymous namespace
1040 
1041 /// @name Auto-generated Match Functions
1042 /// {
1043 
1044 static unsigned MatchRegisterName(StringRef Name);
1045 
1046 /// }
1047 
1048 static bool CheckBaseRegAndIndexRegAndScale(unsigned BaseReg, unsigned IndexReg,
1049                                             unsigned Scale, bool Is64BitMode,
1050                                             StringRef &ErrMsg) {
1051   // If we have both a base register and an index register make sure they are
1052   // both 64-bit or 32-bit registers.
1053   // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1054 
1055   if (BaseReg != 0 &&
1056       !(BaseReg == X86::RIP || BaseReg == X86::EIP ||
1057         X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) ||
1058         X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) ||
1059         X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg))) {
1060     ErrMsg = "invalid base+index expression";
1061     return true;
1062   }
1063 
1064   if (IndexReg != 0 &&
1065       !(IndexReg == X86::EIZ || IndexReg == X86::RIZ ||
1066         X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1067         X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg) ||
1068         X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg) ||
1069         X86MCRegisterClasses[X86::VR128XRegClassID].contains(IndexReg) ||
1070         X86MCRegisterClasses[X86::VR256XRegClassID].contains(IndexReg) ||
1071         X86MCRegisterClasses[X86::VR512RegClassID].contains(IndexReg))) {
1072     ErrMsg = "invalid base+index expression";
1073     return true;
1074   }
1075 
1076   if (((BaseReg == X86::RIP || BaseReg == X86::EIP) && IndexReg != 0) ||
1077       IndexReg == X86::EIP || IndexReg == X86::RIP ||
1078       IndexReg == X86::ESP || IndexReg == X86::RSP) {
1079     ErrMsg = "invalid base+index expression";
1080     return true;
1081   }
1082 
1083   // Check for use of invalid 16-bit registers. Only BX/BP/SI/DI are allowed,
1084   // and then only in non-64-bit modes.
1085   if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) &&
1086       (Is64BitMode || (BaseReg != X86::BX && BaseReg != X86::BP &&
1087                        BaseReg != X86::SI && BaseReg != X86::DI))) {
1088     ErrMsg = "invalid 16-bit base register";
1089     return true;
1090   }
1091 
1092   if (BaseReg == 0 &&
1093       X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg)) {
1094     ErrMsg = "16-bit memory operand may not include only index register";
1095     return true;
1096   }
1097 
1098   if (BaseReg != 0 && IndexReg != 0) {
1099     if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1100         (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1101          X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg) ||
1102          IndexReg == X86::EIZ)) {
1103       ErrMsg = "base register is 64-bit, but index register is not";
1104       return true;
1105     }
1106     if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1107         (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1108          X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg) ||
1109          IndexReg == X86::RIZ)) {
1110       ErrMsg = "base register is 32-bit, but index register is not";
1111       return true;
1112     }
1113     if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg)) {
1114       if (X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg) ||
1115           X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) {
1116         ErrMsg = "base register is 16-bit, but index register is not";
1117         return true;
1118       }
1119       if ((BaseReg != X86::BX && BaseReg != X86::BP) ||
1120           (IndexReg != X86::SI && IndexReg != X86::DI)) {
1121         ErrMsg = "invalid 16-bit base/index register combination";
1122         return true;
1123       }
1124     }
1125   }
1126 
1127   // RIP/EIP-relative addressing is only supported in 64-bit mode.
1128   if (!Is64BitMode && BaseReg != 0 &&
1129       (BaseReg == X86::RIP || BaseReg == X86::EIP)) {
1130     ErrMsg = "IP-relative addressing requires 64-bit mode";
1131     return true;
1132   }
1133 
1134   return checkScale(Scale, ErrMsg);
1135 }
1136 
1137 bool X86AsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1138                                  SMLoc &EndLoc, bool RestoreOnFailure) {
1139   MCAsmParser &Parser = getParser();
1140   MCAsmLexer &Lexer = getLexer();
1141   RegNo = 0;
1142 
1143   SmallVector<AsmToken, 5> Tokens;
1144   auto OnFailure = [RestoreOnFailure, &Lexer, &Tokens]() {
1145     if (RestoreOnFailure) {
1146       while (!Tokens.empty()) {
1147         Lexer.UnLex(Tokens.pop_back_val());
1148       }
1149     }
1150   };
1151 
1152   const AsmToken &PercentTok = Parser.getTok();
1153   StartLoc = PercentTok.getLoc();
1154 
1155   // If we encounter a %, ignore it. This code handles registers with and
1156   // without the prefix, unprefixed registers can occur in cfi directives.
1157   if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent)) {
1158     Tokens.push_back(PercentTok);
1159     Parser.Lex(); // Eat percent token.
1160   }
1161 
1162   const AsmToken &Tok = Parser.getTok();
1163   EndLoc = Tok.getEndLoc();
1164 
1165   if (Tok.isNot(AsmToken::Identifier)) {
1166     OnFailure();
1167     if (isParsingIntelSyntax()) return true;
1168     return Error(StartLoc, "invalid register name",
1169                  SMRange(StartLoc, EndLoc));
1170   }
1171 
1172   RegNo = MatchRegisterName(Tok.getString());
1173 
1174   // If the match failed, try the register name as lowercase.
1175   if (RegNo == 0)
1176     RegNo = MatchRegisterName(Tok.getString().lower());
1177 
1178   // The "flags" and "mxcsr" registers cannot be referenced directly.
1179   // Treat it as an identifier instead.
1180   if (isParsingMSInlineAsm() && isParsingIntelSyntax() &&
1181       (RegNo == X86::EFLAGS || RegNo == X86::MXCSR))
1182     RegNo = 0;
1183 
1184   if (!is64BitMode()) {
1185     // FIXME: This should be done using Requires<Not64BitMode> and
1186     // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
1187     // checked.
1188     // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
1189     // REX prefix.
1190     if (RegNo == X86::RIZ || RegNo == X86::RIP ||
1191         X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
1192         X86II::isX86_64NonExtLowByteReg(RegNo) ||
1193         X86II::isX86_64ExtendedReg(RegNo)) {
1194       StringRef RegName = Tok.getString();
1195       OnFailure();
1196       if (!RestoreOnFailure) {
1197         Parser.Lex(); // Eat register name.
1198       }
1199       return Error(StartLoc,
1200                    "register %" + RegName + " is only available in 64-bit mode",
1201                    SMRange(StartLoc, EndLoc));
1202     }
1203   }
1204 
1205   // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
1206   if (RegNo == X86::ST0) {
1207     Tokens.push_back(Tok);
1208     Parser.Lex(); // Eat 'st'
1209 
1210     // Check to see if we have '(4)' after %st.
1211     if (Lexer.isNot(AsmToken::LParen))
1212       return false;
1213     // Lex the paren.
1214     Tokens.push_back(Parser.getTok());
1215     Parser.Lex();
1216 
1217     const AsmToken &IntTok = Parser.getTok();
1218     if (IntTok.isNot(AsmToken::Integer)) {
1219       OnFailure();
1220       return Error(IntTok.getLoc(), "expected stack index");
1221     }
1222     switch (IntTok.getIntVal()) {
1223     case 0: RegNo = X86::ST0; break;
1224     case 1: RegNo = X86::ST1; break;
1225     case 2: RegNo = X86::ST2; break;
1226     case 3: RegNo = X86::ST3; break;
1227     case 4: RegNo = X86::ST4; break;
1228     case 5: RegNo = X86::ST5; break;
1229     case 6: RegNo = X86::ST6; break;
1230     case 7: RegNo = X86::ST7; break;
1231     default:
1232       OnFailure();
1233       return Error(IntTok.getLoc(), "invalid stack index");
1234     }
1235 
1236     // Lex IntTok
1237     Tokens.push_back(IntTok);
1238     Parser.Lex();
1239     if (Lexer.isNot(AsmToken::RParen)) {
1240       OnFailure();
1241       return Error(Parser.getTok().getLoc(), "expected ')'");
1242     }
1243 
1244     EndLoc = Parser.getTok().getEndLoc();
1245     Parser.Lex(); // Eat ')'
1246     return false;
1247   }
1248 
1249   EndLoc = Parser.getTok().getEndLoc();
1250 
1251   // If this is "db[0-15]", match it as an alias
1252   // for dr[0-15].
1253   if (RegNo == 0 && Tok.getString().startswith("db")) {
1254     if (Tok.getString().size() == 3) {
1255       switch (Tok.getString()[2]) {
1256       case '0': RegNo = X86::DR0; break;
1257       case '1': RegNo = X86::DR1; break;
1258       case '2': RegNo = X86::DR2; break;
1259       case '3': RegNo = X86::DR3; break;
1260       case '4': RegNo = X86::DR4; break;
1261       case '5': RegNo = X86::DR5; break;
1262       case '6': RegNo = X86::DR6; break;
1263       case '7': RegNo = X86::DR7; break;
1264       case '8': RegNo = X86::DR8; break;
1265       case '9': RegNo = X86::DR9; break;
1266       }
1267     } else if (Tok.getString().size() == 4 && Tok.getString()[2] == '1') {
1268       switch (Tok.getString()[3]) {
1269       case '0': RegNo = X86::DR10; break;
1270       case '1': RegNo = X86::DR11; break;
1271       case '2': RegNo = X86::DR12; break;
1272       case '3': RegNo = X86::DR13; break;
1273       case '4': RegNo = X86::DR14; break;
1274       case '5': RegNo = X86::DR15; break;
1275       }
1276     }
1277 
1278     if (RegNo != 0) {
1279       EndLoc = Parser.getTok().getEndLoc();
1280       Parser.Lex(); // Eat it.
1281       return false;
1282     }
1283   }
1284 
1285   if (RegNo == 0) {
1286     OnFailure();
1287     if (isParsingIntelSyntax()) return true;
1288     return Error(StartLoc, "invalid register name",
1289                  SMRange(StartLoc, EndLoc));
1290   }
1291 
1292   Parser.Lex(); // Eat identifier token.
1293   return false;
1294 }
1295 
1296 bool X86AsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1297                                  SMLoc &EndLoc) {
1298   return ParseRegister(RegNo, StartLoc, EndLoc, /*RestoreOnFailure=*/false);
1299 }
1300 
1301 OperandMatchResultTy X86AsmParser::tryParseRegister(unsigned &RegNo,
1302                                                     SMLoc &StartLoc,
1303                                                     SMLoc &EndLoc) {
1304   bool Result =
1305       ParseRegister(RegNo, StartLoc, EndLoc, /*RestoreOnFailure=*/true);
1306   bool PendingErrors = getParser().hasPendingError();
1307   getParser().clearPendingErrors();
1308   if (PendingErrors)
1309     return MatchOperand_ParseFail;
1310   if (Result)
1311     return MatchOperand_NoMatch;
1312   return MatchOperand_Success;
1313 }
1314 
1315 std::unique_ptr<X86Operand> X86AsmParser::DefaultMemSIOperand(SMLoc Loc) {
1316   bool Parse32 = is32BitMode() || Code16GCC;
1317   unsigned Basereg = is64BitMode() ? X86::RSI : (Parse32 ? X86::ESI : X86::SI);
1318   const MCExpr *Disp = MCConstantExpr::create(0, getContext());
1319   return X86Operand::CreateMem(getPointerWidth(), /*SegReg=*/0, Disp,
1320                                /*BaseReg=*/Basereg, /*IndexReg=*/0, /*Scale=*/1,
1321                                Loc, Loc, 0);
1322 }
1323 
1324 std::unique_ptr<X86Operand> X86AsmParser::DefaultMemDIOperand(SMLoc Loc) {
1325   bool Parse32 = is32BitMode() || Code16GCC;
1326   unsigned Basereg = is64BitMode() ? X86::RDI : (Parse32 ? X86::EDI : X86::DI);
1327   const MCExpr *Disp = MCConstantExpr::create(0, getContext());
1328   return X86Operand::CreateMem(getPointerWidth(), /*SegReg=*/0, Disp,
1329                                /*BaseReg=*/Basereg, /*IndexReg=*/0, /*Scale=*/1,
1330                                Loc, Loc, 0);
1331 }
1332 
1333 bool X86AsmParser::IsSIReg(unsigned Reg) {
1334   switch (Reg) {
1335   default: llvm_unreachable("Only (R|E)SI and (R|E)DI are expected!");
1336   case X86::RSI:
1337   case X86::ESI:
1338   case X86::SI:
1339     return true;
1340   case X86::RDI:
1341   case X86::EDI:
1342   case X86::DI:
1343     return false;
1344   }
1345 }
1346 
1347 unsigned X86AsmParser::GetSIDIForRegClass(unsigned RegClassID, unsigned Reg,
1348                                           bool IsSIReg) {
1349   switch (RegClassID) {
1350   default: llvm_unreachable("Unexpected register class");
1351   case X86::GR64RegClassID:
1352     return IsSIReg ? X86::RSI : X86::RDI;
1353   case X86::GR32RegClassID:
1354     return IsSIReg ? X86::ESI : X86::EDI;
1355   case X86::GR16RegClassID:
1356     return IsSIReg ? X86::SI : X86::DI;
1357   }
1358 }
1359 
1360 void X86AsmParser::AddDefaultSrcDestOperands(
1361     OperandVector& Operands, std::unique_ptr<llvm::MCParsedAsmOperand> &&Src,
1362     std::unique_ptr<llvm::MCParsedAsmOperand> &&Dst) {
1363   if (isParsingIntelSyntax()) {
1364     Operands.push_back(std::move(Dst));
1365     Operands.push_back(std::move(Src));
1366   }
1367   else {
1368     Operands.push_back(std::move(Src));
1369     Operands.push_back(std::move(Dst));
1370   }
1371 }
1372 
1373 bool X86AsmParser::VerifyAndAdjustOperands(OperandVector &OrigOperands,
1374                                            OperandVector &FinalOperands) {
1375 
1376   if (OrigOperands.size() > 1) {
1377     // Check if sizes match, OrigOperands also contains the instruction name
1378     assert(OrigOperands.size() == FinalOperands.size() + 1 &&
1379            "Operand size mismatch");
1380 
1381     SmallVector<std::pair<SMLoc, std::string>, 2> Warnings;
1382     // Verify types match
1383     int RegClassID = -1;
1384     for (unsigned int i = 0; i < FinalOperands.size(); ++i) {
1385       X86Operand &OrigOp = static_cast<X86Operand &>(*OrigOperands[i + 1]);
1386       X86Operand &FinalOp = static_cast<X86Operand &>(*FinalOperands[i]);
1387 
1388       if (FinalOp.isReg() &&
1389           (!OrigOp.isReg() || FinalOp.getReg() != OrigOp.getReg()))
1390         // Return false and let a normal complaint about bogus operands happen
1391         return false;
1392 
1393       if (FinalOp.isMem()) {
1394 
1395         if (!OrigOp.isMem())
1396           // Return false and let a normal complaint about bogus operands happen
1397           return false;
1398 
1399         unsigned OrigReg = OrigOp.Mem.BaseReg;
1400         unsigned FinalReg = FinalOp.Mem.BaseReg;
1401 
1402         // If we've already encounterd a register class, make sure all register
1403         // bases are of the same register class
1404         if (RegClassID != -1 &&
1405             !X86MCRegisterClasses[RegClassID].contains(OrigReg)) {
1406           return Error(OrigOp.getStartLoc(),
1407                        "mismatching source and destination index registers");
1408         }
1409 
1410         if (X86MCRegisterClasses[X86::GR64RegClassID].contains(OrigReg))
1411           RegClassID = X86::GR64RegClassID;
1412         else if (X86MCRegisterClasses[X86::GR32RegClassID].contains(OrigReg))
1413           RegClassID = X86::GR32RegClassID;
1414         else if (X86MCRegisterClasses[X86::GR16RegClassID].contains(OrigReg))
1415           RegClassID = X86::GR16RegClassID;
1416         else
1417           // Unexpected register class type
1418           // Return false and let a normal complaint about bogus operands happen
1419           return false;
1420 
1421         bool IsSI = IsSIReg(FinalReg);
1422         FinalReg = GetSIDIForRegClass(RegClassID, FinalReg, IsSI);
1423 
1424         if (FinalReg != OrigReg) {
1425           std::string RegName = IsSI ? "ES:(R|E)SI" : "ES:(R|E)DI";
1426           Warnings.push_back(std::make_pair(
1427               OrigOp.getStartLoc(),
1428               "memory operand is only for determining the size, " + RegName +
1429                   " will be used for the location"));
1430         }
1431 
1432         FinalOp.Mem.Size = OrigOp.Mem.Size;
1433         FinalOp.Mem.SegReg = OrigOp.Mem.SegReg;
1434         FinalOp.Mem.BaseReg = FinalReg;
1435       }
1436     }
1437 
1438     // Produce warnings only if all the operands passed the adjustment - prevent
1439     // legal cases like "movsd (%rax), %xmm0" mistakenly produce warnings
1440     for (auto &WarningMsg : Warnings) {
1441       Warning(WarningMsg.first, WarningMsg.second);
1442     }
1443 
1444     // Remove old operands
1445     for (unsigned int i = 0; i < FinalOperands.size(); ++i)
1446       OrigOperands.pop_back();
1447   }
1448   // OrigOperands.append(FinalOperands.begin(), FinalOperands.end());
1449   for (unsigned int i = 0; i < FinalOperands.size(); ++i)
1450     OrigOperands.push_back(std::move(FinalOperands[i]));
1451 
1452   return false;
1453 }
1454 
1455 std::unique_ptr<X86Operand> X86AsmParser::ParseOperand() {
1456   if (isParsingIntelSyntax())
1457     return ParseIntelOperand();
1458   return ParseATTOperand();
1459 }
1460 
1461 std::unique_ptr<X86Operand> X86AsmParser::CreateMemForMSInlineAsm(
1462     unsigned SegReg, const MCExpr *Disp, unsigned BaseReg, unsigned IndexReg,
1463     unsigned Scale, SMLoc Start, SMLoc End, unsigned Size, StringRef Identifier,
1464     const InlineAsmIdentifierInfo &Info) {
1465   // If we found a decl other than a VarDecl, then assume it is a FuncDecl or
1466   // some other label reference.
1467   if (Info.isKind(InlineAsmIdentifierInfo::IK_Label)) {
1468     // Insert an explicit size if the user didn't have one.
1469     if (!Size) {
1470       Size = getPointerWidth();
1471       InstInfo->AsmRewrites->emplace_back(AOK_SizeDirective, Start,
1472                                           /*Len=*/0, Size);
1473     }
1474     // Create an absolute memory reference in order to match against
1475     // instructions taking a PC relative operand.
1476     return X86Operand::CreateMem(getPointerWidth(), Disp, Start, End, Size,
1477                                  Identifier, Info.Label.Decl);
1478   }
1479   // We either have a direct symbol reference, or an offset from a symbol.  The
1480   // parser always puts the symbol on the LHS, so look there for size
1481   // calculation purposes.
1482   unsigned FrontendSize = 0;
1483   void *Decl = nullptr;
1484   bool IsGlobalLV = false;
1485   if (Info.isKind(InlineAsmIdentifierInfo::IK_Var)) {
1486     // Size is in terms of bits in this context.
1487     FrontendSize = Info.Var.Type * 8;
1488     Decl = Info.Var.Decl;
1489     IsGlobalLV = Info.Var.IsGlobalLV;
1490   }
1491   // It is widely common for MS InlineAsm to use a global variable and one/two
1492   // registers in a mmory expression, and though unaccessible via rip/eip.
1493   if (IsGlobalLV && (BaseReg || IndexReg)) {
1494     return X86Operand::CreateMem(getPointerWidth(), Disp, Start, End);
1495   // Otherwise, we set the base register to a non-zero value
1496   // if we don't know the actual value at this time.  This is necessary to
1497   // get the matching correct in some cases.
1498   } else {
1499     BaseReg = BaseReg ? BaseReg : 1;
1500     return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, BaseReg,
1501                                  IndexReg, Scale, Start, End, Size, Identifier,
1502                                  Decl, FrontendSize);
1503   }
1504 }
1505 
1506 // Some binary bitwise operators have a named synonymous
1507 // Query a candidate string for being such a named operator
1508 // and if so - invoke the appropriate handler
1509 bool X86AsmParser::ParseIntelNamedOperator(StringRef Name,
1510                                            IntelExprStateMachine &SM,
1511                                            bool &ParseError, SMLoc &End) {
1512   // A named operator should be either lower or upper case, but not a mix
1513   if (Name.compare(Name.lower()) && Name.compare(Name.upper()))
1514     return false;
1515   if (Name.equals_lower("not")) {
1516     SM.onNot();
1517   } else if (Name.equals_lower("or")) {
1518     SM.onOr();
1519   } else if (Name.equals_lower("shl")) {
1520     SM.onLShift();
1521   } else if (Name.equals_lower("shr")) {
1522     SM.onRShift();
1523   } else if (Name.equals_lower("xor")) {
1524     SM.onXor();
1525   } else if (Name.equals_lower("and")) {
1526     SM.onAnd();
1527   } else if (Name.equals_lower("mod")) {
1528     SM.onMod();
1529   } else if (Name.equals_lower("offset")) {
1530     SMLoc OffsetLoc = getTok().getLoc();
1531     const MCExpr *Val = nullptr;
1532     StringRef ID;
1533     InlineAsmIdentifierInfo Info;
1534     ParseError = ParseIntelOffsetOperator(Val, ID, Info, End);
1535     if (ParseError)
1536       return true;
1537     StringRef ErrMsg;
1538     ParseError =
1539         SM.onOffset(Val, OffsetLoc, ID, Info, isParsingMSInlineAsm(), ErrMsg);
1540     if (ParseError)
1541       return Error(SMLoc::getFromPointer(Name.data()), ErrMsg);
1542   } else {
1543     return false;
1544   }
1545   if (!Name.equals_lower("offset"))
1546     End = consumeToken();
1547   return true;
1548 }
1549 
1550 bool X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) {
1551   MCAsmParser &Parser = getParser();
1552   const AsmToken &Tok = Parser.getTok();
1553   StringRef ErrMsg;
1554 
1555   AsmToken::TokenKind PrevTK = AsmToken::Error;
1556   bool Done = false;
1557   while (!Done) {
1558     bool UpdateLocLex = true;
1559     AsmToken::TokenKind TK = getLexer().getKind();
1560 
1561     switch (TK) {
1562     default:
1563       if ((Done = SM.isValidEndState()))
1564         break;
1565       return Error(Tok.getLoc(), "unknown token in expression");
1566     case AsmToken::EndOfStatement:
1567       Done = true;
1568       break;
1569     case AsmToken::Real:
1570       // DotOperator: [ebx].0
1571       UpdateLocLex = false;
1572       if (ParseIntelDotOperator(SM, End))
1573         return true;
1574       break;
1575     case AsmToken::At:
1576     case AsmToken::String:
1577     case AsmToken::Identifier: {
1578       SMLoc IdentLoc = Tok.getLoc();
1579       StringRef Identifier = Tok.getString();
1580       UpdateLocLex = false;
1581       // Register
1582       unsigned Reg;
1583       if (Tok.is(AsmToken::Identifier) && !ParseRegister(Reg, IdentLoc, End)) {
1584         if (SM.onRegister(Reg, ErrMsg))
1585           return Error(Tok.getLoc(), ErrMsg);
1586         break;
1587       }
1588       // Operator synonymous ("not", "or" etc.)
1589       bool ParseError = false;
1590       if (ParseIntelNamedOperator(Identifier, SM, ParseError, End)) {
1591         if (ParseError)
1592           return true;
1593         break;
1594       }
1595       // Symbol reference, when parsing assembly content
1596       InlineAsmIdentifierInfo Info;
1597       const MCExpr *Val;
1598       if (!isParsingMSInlineAsm()) {
1599         if (getParser().parsePrimaryExpr(Val, End)) {
1600           return Error(Tok.getLoc(), "Unexpected identifier!");
1601         } else if (SM.onIdentifierExpr(Val, Identifier, Info, false, ErrMsg)) {
1602           return Error(IdentLoc, ErrMsg);
1603         } else
1604           break;
1605       }
1606       // MS InlineAsm operators (TYPE/LENGTH/SIZE)
1607       if (unsigned OpKind = IdentifyIntelInlineAsmOperator(Identifier)) {
1608         if (int64_t Val = ParseIntelInlineAsmOperator(OpKind)) {
1609           if (SM.onInteger(Val, ErrMsg))
1610             return Error(IdentLoc, ErrMsg);
1611         } else
1612           return true;
1613         break;
1614       }
1615       // MS Dot Operator expression
1616       if (Identifier.count('.') && PrevTK == AsmToken::RBrac) {
1617         if (ParseIntelDotOperator(SM, End))
1618           return true;
1619         break;
1620       }
1621       // MS InlineAsm identifier
1622       // Call parseIdentifier() to combine @ with the identifier behind it.
1623       if (TK == AsmToken::At && Parser.parseIdentifier(Identifier))
1624         return Error(IdentLoc, "expected identifier");
1625       if (ParseIntelInlineAsmIdentifier(Val, Identifier, Info, false, End))
1626         return true;
1627       else if (SM.onIdentifierExpr(Val, Identifier, Info, true, ErrMsg))
1628         return Error(IdentLoc, ErrMsg);
1629       break;
1630     }
1631     case AsmToken::Integer: {
1632       // Look for 'b' or 'f' following an Integer as a directional label
1633       SMLoc Loc = getTok().getLoc();
1634       int64_t IntVal = getTok().getIntVal();
1635       End = consumeToken();
1636       UpdateLocLex = false;
1637       if (getLexer().getKind() == AsmToken::Identifier) {
1638         StringRef IDVal = getTok().getString();
1639         if (IDVal == "f" || IDVal == "b") {
1640           MCSymbol *Sym =
1641               getContext().getDirectionalLocalSymbol(IntVal, IDVal == "b");
1642           MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1643           const MCExpr *Val =
1644               MCSymbolRefExpr::create(Sym, Variant, getContext());
1645           if (IDVal == "b" && Sym->isUndefined())
1646             return Error(Loc, "invalid reference to undefined symbol");
1647           StringRef Identifier = Sym->getName();
1648           InlineAsmIdentifierInfo Info;
1649           if (SM.onIdentifierExpr(Val, Identifier, Info, isParsingMSInlineAsm(),
1650                                   ErrMsg))
1651             return Error(Loc, ErrMsg);
1652           End = consumeToken();
1653         } else {
1654           if (SM.onInteger(IntVal, ErrMsg))
1655             return Error(Loc, ErrMsg);
1656         }
1657       } else {
1658         if (SM.onInteger(IntVal, ErrMsg))
1659           return Error(Loc, ErrMsg);
1660       }
1661       break;
1662     }
1663     case AsmToken::Plus:
1664       if (SM.onPlus(ErrMsg))
1665         return Error(getTok().getLoc(), ErrMsg);
1666       break;
1667     case AsmToken::Minus:
1668       if (SM.onMinus(ErrMsg))
1669         return Error(getTok().getLoc(), ErrMsg);
1670       break;
1671     case AsmToken::Tilde:   SM.onNot(); break;
1672     case AsmToken::Star:    SM.onStar(); break;
1673     case AsmToken::Slash:   SM.onDivide(); break;
1674     case AsmToken::Percent: SM.onMod(); break;
1675     case AsmToken::Pipe:    SM.onOr(); break;
1676     case AsmToken::Caret:   SM.onXor(); break;
1677     case AsmToken::Amp:     SM.onAnd(); break;
1678     case AsmToken::LessLess:
1679                             SM.onLShift(); break;
1680     case AsmToken::GreaterGreater:
1681                             SM.onRShift(); break;
1682     case AsmToken::LBrac:
1683       if (SM.onLBrac())
1684         return Error(Tok.getLoc(), "unexpected bracket encountered");
1685       break;
1686     case AsmToken::RBrac:
1687       if (SM.onRBrac())
1688         return Error(Tok.getLoc(), "unexpected bracket encountered");
1689       break;
1690     case AsmToken::LParen:  SM.onLParen(); break;
1691     case AsmToken::RParen:  SM.onRParen(); break;
1692     }
1693     if (SM.hadError())
1694       return Error(Tok.getLoc(), "unknown token in expression");
1695 
1696     if (!Done && UpdateLocLex)
1697       End = consumeToken();
1698 
1699     PrevTK = TK;
1700   }
1701   return false;
1702 }
1703 
1704 void X86AsmParser::RewriteIntelExpression(IntelExprStateMachine &SM,
1705                                           SMLoc Start, SMLoc End) {
1706   SMLoc Loc = Start;
1707   unsigned ExprLen = End.getPointer() - Start.getPointer();
1708   // Skip everything before a symbol displacement (if we have one)
1709   if (SM.getSym() && !SM.isOffsetOperator()) {
1710     StringRef SymName = SM.getSymName();
1711     if (unsigned Len = SymName.data() - Start.getPointer())
1712       InstInfo->AsmRewrites->emplace_back(AOK_Skip, Start, Len);
1713     Loc = SMLoc::getFromPointer(SymName.data() + SymName.size());
1714     ExprLen = End.getPointer() - (SymName.data() + SymName.size());
1715     // If we have only a symbol than there's no need for complex rewrite,
1716     // simply skip everything after it
1717     if (!(SM.getBaseReg() || SM.getIndexReg() || SM.getImm())) {
1718       if (ExprLen)
1719         InstInfo->AsmRewrites->emplace_back(AOK_Skip, Loc, ExprLen);
1720       return;
1721     }
1722   }
1723   // Build an Intel Expression rewrite
1724   StringRef BaseRegStr;
1725   StringRef IndexRegStr;
1726   StringRef OffsetNameStr;
1727   if (SM.getBaseReg())
1728     BaseRegStr = X86IntelInstPrinter::getRegisterName(SM.getBaseReg());
1729   if (SM.getIndexReg())
1730     IndexRegStr = X86IntelInstPrinter::getRegisterName(SM.getIndexReg());
1731   if (SM.isOffsetOperator())
1732     OffsetNameStr = SM.getSymName();
1733   // Emit it
1734   IntelExpr Expr(BaseRegStr, IndexRegStr, SM.getScale(), OffsetNameStr,
1735                  SM.getImm(), SM.isMemExpr());
1736   InstInfo->AsmRewrites->emplace_back(Loc, ExprLen, Expr);
1737 }
1738 
1739 // Inline assembly may use variable names with namespace alias qualifiers.
1740 bool X86AsmParser::ParseIntelInlineAsmIdentifier(
1741     const MCExpr *&Val, StringRef &Identifier, InlineAsmIdentifierInfo &Info,
1742     bool IsUnevaluatedOperand, SMLoc &End, bool IsParsingOffsetOperator) {
1743   MCAsmParser &Parser = getParser();
1744   assert(isParsingMSInlineAsm() && "Expected to be parsing inline assembly.");
1745   Val = nullptr;
1746 
1747   StringRef LineBuf(Identifier.data());
1748   SemaCallback->LookupInlineAsmIdentifier(LineBuf, Info, IsUnevaluatedOperand);
1749 
1750   const AsmToken &Tok = Parser.getTok();
1751   SMLoc Loc = Tok.getLoc();
1752 
1753   // Advance the token stream until the end of the current token is
1754   // after the end of what the frontend claimed.
1755   const char *EndPtr = Tok.getLoc().getPointer() + LineBuf.size();
1756   do {
1757     End = Tok.getEndLoc();
1758     getLexer().Lex();
1759   } while (End.getPointer() < EndPtr);
1760   Identifier = LineBuf;
1761 
1762   // The frontend should end parsing on an assembler token boundary, unless it
1763   // failed parsing.
1764   assert((End.getPointer() == EndPtr ||
1765           Info.isKind(InlineAsmIdentifierInfo::IK_Invalid)) &&
1766           "frontend claimed part of a token?");
1767 
1768   // If the identifier lookup was unsuccessful, assume that we are dealing with
1769   // a label.
1770   if (Info.isKind(InlineAsmIdentifierInfo::IK_Invalid)) {
1771     StringRef InternalName =
1772       SemaCallback->LookupInlineAsmLabel(Identifier, getSourceManager(),
1773                                          Loc, false);
1774     assert(InternalName.size() && "We should have an internal name here.");
1775     // Push a rewrite for replacing the identifier name with the internal name,
1776     // unless we are parsing the operand of an offset operator
1777     if (!IsParsingOffsetOperator)
1778       InstInfo->AsmRewrites->emplace_back(AOK_Label, Loc, Identifier.size(),
1779                                           InternalName);
1780     else
1781       Identifier = InternalName;
1782   } else if (Info.isKind(InlineAsmIdentifierInfo::IK_EnumVal))
1783     return false;
1784   // Create the symbol reference.
1785   MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
1786   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1787   Val = MCSymbolRefExpr::create(Sym, Variant, getParser().getContext());
1788   return false;
1789 }
1790 
1791 //ParseRoundingModeOp - Parse AVX-512 rounding mode operand
1792 std::unique_ptr<X86Operand>
1793 X86AsmParser::ParseRoundingModeOp(SMLoc Start) {
1794   MCAsmParser &Parser = getParser();
1795   const AsmToken &Tok = Parser.getTok();
1796   // Eat "{" and mark the current place.
1797   const SMLoc consumedToken = consumeToken();
1798   if (Tok.isNot(AsmToken::Identifier))
1799     return ErrorOperand(Tok.getLoc(), "Expected an identifier after {");
1800   if (Tok.getIdentifier().startswith("r")){
1801     int rndMode = StringSwitch<int>(Tok.getIdentifier())
1802       .Case("rn", X86::STATIC_ROUNDING::TO_NEAREST_INT)
1803       .Case("rd", X86::STATIC_ROUNDING::TO_NEG_INF)
1804       .Case("ru", X86::STATIC_ROUNDING::TO_POS_INF)
1805       .Case("rz", X86::STATIC_ROUNDING::TO_ZERO)
1806       .Default(-1);
1807     if (-1 == rndMode)
1808       return ErrorOperand(Tok.getLoc(), "Invalid rounding mode.");
1809      Parser.Lex();  // Eat "r*" of r*-sae
1810     if (!getLexer().is(AsmToken::Minus))
1811       return ErrorOperand(Tok.getLoc(), "Expected - at this point");
1812     Parser.Lex();  // Eat "-"
1813     Parser.Lex();  // Eat the sae
1814     if (!getLexer().is(AsmToken::RCurly))
1815       return ErrorOperand(Tok.getLoc(), "Expected } at this point");
1816     SMLoc End = Tok.getEndLoc();
1817     Parser.Lex();  // Eat "}"
1818     const MCExpr *RndModeOp =
1819       MCConstantExpr::create(rndMode, Parser.getContext());
1820     return X86Operand::CreateImm(RndModeOp, Start, End);
1821   }
1822   if(Tok.getIdentifier().equals("sae")){
1823     Parser.Lex();  // Eat the sae
1824     if (!getLexer().is(AsmToken::RCurly))
1825       return ErrorOperand(Tok.getLoc(), "Expected } at this point");
1826     Parser.Lex();  // Eat "}"
1827     return X86Operand::CreateToken("{sae}", consumedToken);
1828   }
1829   return ErrorOperand(Tok.getLoc(), "unknown token in expression");
1830 }
1831 
1832 /// Parse the '.' operator.
1833 bool X86AsmParser::ParseIntelDotOperator(IntelExprStateMachine &SM, SMLoc &End) {
1834   const AsmToken &Tok = getTok();
1835   unsigned Offset;
1836 
1837   // Drop the optional '.'.
1838   StringRef DotDispStr = Tok.getString();
1839   if (DotDispStr.startswith("."))
1840     DotDispStr = DotDispStr.drop_front(1);
1841 
1842   // .Imm gets lexed as a real.
1843   if (Tok.is(AsmToken::Real)) {
1844     APInt DotDisp;
1845     DotDispStr.getAsInteger(10, DotDisp);
1846     Offset = DotDisp.getZExtValue();
1847   } else if (isParsingMSInlineAsm() && Tok.is(AsmToken::Identifier)) {
1848     std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
1849     if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second,
1850                                            Offset))
1851       return Error(Tok.getLoc(), "Unable to lookup field reference!");
1852   } else
1853     return Error(Tok.getLoc(), "Unexpected token type!");
1854 
1855   // Eat the DotExpression and update End
1856   End = SMLoc::getFromPointer(DotDispStr.data());
1857   const char *DotExprEndLoc = DotDispStr.data() + DotDispStr.size();
1858   while (Tok.getLoc().getPointer() < DotExprEndLoc)
1859     Lex();
1860   SM.addImm(Offset);
1861   return false;
1862 }
1863 
1864 /// Parse the 'offset' operator.
1865 /// This operator is used to specify the location of a given operand
1866 bool X86AsmParser::ParseIntelOffsetOperator(const MCExpr *&Val, StringRef &ID,
1867                                             InlineAsmIdentifierInfo &Info,
1868                                             SMLoc &End) {
1869   // Eat offset, mark start of identifier.
1870   SMLoc Start = Lex().getLoc();
1871   ID = getTok().getString();
1872   if (!isParsingMSInlineAsm()) {
1873     if ((getTok().isNot(AsmToken::Identifier) &&
1874          getTok().isNot(AsmToken::String)) ||
1875         getParser().parsePrimaryExpr(Val, End))
1876       return Error(Start, "unexpected token!");
1877   } else if (ParseIntelInlineAsmIdentifier(Val, ID, Info, false, End, true)) {
1878     return Error(Start, "unable to lookup expression");
1879   } else if (Info.isKind(InlineAsmIdentifierInfo::IK_EnumVal)) {
1880     return Error(Start, "offset operator cannot yet handle constants");
1881   }
1882   return false;
1883 }
1884 
1885 // Query a candidate string for being an Intel assembly operator
1886 // Report back its kind, or IOK_INVALID if does not evaluated as a known one
1887 unsigned X86AsmParser::IdentifyIntelInlineAsmOperator(StringRef Name) {
1888   return StringSwitch<unsigned>(Name)
1889     .Cases("TYPE","type",IOK_TYPE)
1890     .Cases("SIZE","size",IOK_SIZE)
1891     .Cases("LENGTH","length",IOK_LENGTH)
1892     .Default(IOK_INVALID);
1893 }
1894 
1895 /// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators.  The LENGTH operator
1896 /// returns the number of elements in an array.  It returns the value 1 for
1897 /// non-array variables.  The SIZE operator returns the size of a C or C++
1898 /// variable.  A variable's size is the product of its LENGTH and TYPE.  The
1899 /// TYPE operator returns the size of a C or C++ type or variable. If the
1900 /// variable is an array, TYPE returns the size of a single element.
1901 unsigned X86AsmParser::ParseIntelInlineAsmOperator(unsigned OpKind) {
1902   MCAsmParser &Parser = getParser();
1903   const AsmToken &Tok = Parser.getTok();
1904   Parser.Lex(); // Eat operator.
1905 
1906   const MCExpr *Val = nullptr;
1907   InlineAsmIdentifierInfo Info;
1908   SMLoc Start = Tok.getLoc(), End;
1909   StringRef Identifier = Tok.getString();
1910   if (ParseIntelInlineAsmIdentifier(Val, Identifier, Info,
1911                                     /*Unevaluated=*/true, End))
1912     return 0;
1913 
1914   if (!Info.isKind(InlineAsmIdentifierInfo::IK_Var)) {
1915     Error(Start, "unable to lookup expression");
1916     return 0;
1917   }
1918 
1919   unsigned CVal = 0;
1920   switch(OpKind) {
1921   default: llvm_unreachable("Unexpected operand kind!");
1922   case IOK_LENGTH: CVal = Info.Var.Length; break;
1923   case IOK_SIZE: CVal = Info.Var.Size; break;
1924   case IOK_TYPE: CVal = Info.Var.Type; break;
1925   }
1926 
1927   return CVal;
1928 }
1929 
1930 bool X86AsmParser::ParseIntelMemoryOperandSize(unsigned &Size) {
1931   Size = StringSwitch<unsigned>(getTok().getString())
1932     .Cases("BYTE", "byte", 8)
1933     .Cases("WORD", "word", 16)
1934     .Cases("DWORD", "dword", 32)
1935     .Cases("FLOAT", "float", 32)
1936     .Cases("LONG", "long", 32)
1937     .Cases("FWORD", "fword", 48)
1938     .Cases("DOUBLE", "double", 64)
1939     .Cases("QWORD", "qword", 64)
1940     .Cases("MMWORD","mmword", 64)
1941     .Cases("XWORD", "xword", 80)
1942     .Cases("TBYTE", "tbyte", 80)
1943     .Cases("XMMWORD", "xmmword", 128)
1944     .Cases("YMMWORD", "ymmword", 256)
1945     .Cases("ZMMWORD", "zmmword", 512)
1946     .Default(0);
1947   if (Size) {
1948     const AsmToken &Tok = Lex(); // Eat operand size (e.g., byte, word).
1949     if (!(Tok.getString().equals("PTR") || Tok.getString().equals("ptr")))
1950       return Error(Tok.getLoc(), "Expected 'PTR' or 'ptr' token!");
1951     Lex(); // Eat ptr.
1952   }
1953   return false;
1954 }
1955 
1956 std::unique_ptr<X86Operand> X86AsmParser::ParseIntelOperand() {
1957   MCAsmParser &Parser = getParser();
1958   const AsmToken &Tok = Parser.getTok();
1959   SMLoc Start, End;
1960 
1961   // Parse optional Size directive.
1962   unsigned Size;
1963   if (ParseIntelMemoryOperandSize(Size))
1964     return nullptr;
1965   bool PtrInOperand = bool(Size);
1966 
1967   Start = Tok.getLoc();
1968 
1969   // Rounding mode operand.
1970   if (getLexer().is(AsmToken::LCurly))
1971     return ParseRoundingModeOp(Start);
1972 
1973   // Register operand.
1974   unsigned RegNo = 0;
1975   if (Tok.is(AsmToken::Identifier) && !ParseRegister(RegNo, Start, End)) {
1976     if (RegNo == X86::RIP)
1977       return ErrorOperand(Start, "rip can only be used as a base register");
1978     // A Register followed by ':' is considered a segment override
1979     if (Tok.isNot(AsmToken::Colon))
1980       return !PtrInOperand ? X86Operand::CreateReg(RegNo, Start, End) :
1981         ErrorOperand(Start, "expected memory operand after 'ptr', "
1982                             "found register operand instead");
1983     // An alleged segment override. check if we have a valid segment register
1984     if (!X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains(RegNo))
1985       return ErrorOperand(Start, "invalid segment register");
1986     // Eat ':' and update Start location
1987     Start = Lex().getLoc();
1988   }
1989 
1990   // Immediates and Memory
1991   IntelExprStateMachine SM;
1992   if (ParseIntelExpression(SM, End))
1993     return nullptr;
1994 
1995   if (isParsingMSInlineAsm())
1996     RewriteIntelExpression(SM, Start, Tok.getLoc());
1997 
1998   int64_t Imm = SM.getImm();
1999   const MCExpr *Disp = SM.getSym();
2000   const MCExpr *ImmDisp = MCConstantExpr::create(Imm, getContext());
2001   if (Disp && Imm)
2002     Disp = MCBinaryExpr::createAdd(Disp, ImmDisp, getContext());
2003   if (!Disp)
2004     Disp = ImmDisp;
2005 
2006   // RegNo != 0 specifies a valid segment register,
2007   // and we are parsing a segment override
2008   if (!SM.isMemExpr() && !RegNo) {
2009     if (isParsingMSInlineAsm() && SM.isOffsetOperator()) {
2010       const InlineAsmIdentifierInfo Info = SM.getIdentifierInfo();
2011       if (Info.isKind(InlineAsmIdentifierInfo::IK_Var)) {
2012         // Disp includes the address of a variable; make sure this is recorded
2013         // for later handling.
2014         return X86Operand::CreateImm(Disp, Start, End, SM.getSymName(),
2015                                      Info.Var.Decl, Info.Var.IsGlobalLV);
2016       }
2017     }
2018 
2019     return X86Operand::CreateImm(Disp, Start, End);
2020   }
2021 
2022   StringRef ErrMsg;
2023   unsigned BaseReg = SM.getBaseReg();
2024   unsigned IndexReg = SM.getIndexReg();
2025   unsigned Scale = SM.getScale();
2026 
2027   if (Scale == 0 && BaseReg != X86::ESP && BaseReg != X86::RSP &&
2028       (IndexReg == X86::ESP || IndexReg == X86::RSP))
2029     std::swap(BaseReg, IndexReg);
2030 
2031   // If BaseReg is a vector register and IndexReg is not, swap them unless
2032   // Scale was specified in which case it would be an error.
2033   if (Scale == 0 &&
2034       !(X86MCRegisterClasses[X86::VR128XRegClassID].contains(IndexReg) ||
2035         X86MCRegisterClasses[X86::VR256XRegClassID].contains(IndexReg) ||
2036         X86MCRegisterClasses[X86::VR512RegClassID].contains(IndexReg)) &&
2037       (X86MCRegisterClasses[X86::VR128XRegClassID].contains(BaseReg) ||
2038        X86MCRegisterClasses[X86::VR256XRegClassID].contains(BaseReg) ||
2039        X86MCRegisterClasses[X86::VR512RegClassID].contains(BaseReg)))
2040     std::swap(BaseReg, IndexReg);
2041 
2042   if (Scale != 0 &&
2043       X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg))
2044     return ErrorOperand(Start, "16-bit addresses cannot have a scale");
2045 
2046   // If there was no explicit scale specified, change it to 1.
2047   if (Scale == 0)
2048     Scale = 1;
2049 
2050   // If this is a 16-bit addressing mode with the base and index in the wrong
2051   // order, swap them so CheckBaseRegAndIndexRegAndScale doesn't fail. It is
2052   // shared with att syntax where order matters.
2053   if ((BaseReg == X86::SI || BaseReg == X86::DI) &&
2054       (IndexReg == X86::BX || IndexReg == X86::BP))
2055     std::swap(BaseReg, IndexReg);
2056 
2057   if ((BaseReg || IndexReg) &&
2058       CheckBaseRegAndIndexRegAndScale(BaseReg, IndexReg, Scale, is64BitMode(),
2059                                       ErrMsg))
2060     return ErrorOperand(Start, ErrMsg);
2061   if (isParsingMSInlineAsm())
2062     return CreateMemForMSInlineAsm(RegNo, Disp, BaseReg, IndexReg, Scale, Start,
2063                                    End, Size, SM.getSymName(),
2064                                    SM.getIdentifierInfo());
2065   if (!(BaseReg || IndexReg || RegNo))
2066     return X86Operand::CreateMem(getPointerWidth(), Disp, Start, End, Size);
2067   return X86Operand::CreateMem(getPointerWidth(), RegNo, Disp,
2068                                BaseReg, IndexReg, Scale, Start, End, Size);
2069 }
2070 
2071 std::unique_ptr<X86Operand> X86AsmParser::ParseATTOperand() {
2072   MCAsmParser &Parser = getParser();
2073   switch (getLexer().getKind()) {
2074   case AsmToken::Dollar: {
2075     // $42 or $ID -> immediate.
2076     SMLoc Start = Parser.getTok().getLoc(), End;
2077     Parser.Lex();
2078     const MCExpr *Val;
2079     // This is an immediate, so we should not parse a register. Do a precheck
2080     // for '%' to supercede intra-register parse errors.
2081     SMLoc L = Parser.getTok().getLoc();
2082     if (check(getLexer().is(AsmToken::Percent), L,
2083               "expected immediate expression") ||
2084         getParser().parseExpression(Val, End) ||
2085         check(isa<X86MCExpr>(Val), L, "expected immediate expression"))
2086       return nullptr;
2087     return X86Operand::CreateImm(Val, Start, End);
2088   }
2089   case AsmToken::LCurly: {
2090     SMLoc Start = Parser.getTok().getLoc();
2091     return ParseRoundingModeOp(Start);
2092   }
2093   default: {
2094     // This a memory operand or a register. We have some parsing complications
2095     // as a '(' may be part of an immediate expression or the addressing mode
2096     // block. This is complicated by the fact that an assembler-level variable
2097     // may refer either to a register or an immediate expression.
2098 
2099     SMLoc Loc = Parser.getTok().getLoc(), EndLoc;
2100     const MCExpr *Expr = nullptr;
2101     unsigned Reg = 0;
2102     if (getLexer().isNot(AsmToken::LParen)) {
2103       // No '(' so this is either a displacement expression or a register.
2104       if (Parser.parseExpression(Expr, EndLoc))
2105         return nullptr;
2106       if (auto *RE = dyn_cast<X86MCExpr>(Expr)) {
2107         // Segment Register. Reset Expr and copy value to register.
2108         Expr = nullptr;
2109         Reg = RE->getRegNo();
2110 
2111         // Sanity check register.
2112         if (Reg == X86::EIZ || Reg == X86::RIZ)
2113           return ErrorOperand(
2114               Loc, "%eiz and %riz can only be used as index registers",
2115               SMRange(Loc, EndLoc));
2116         if (Reg == X86::RIP)
2117           return ErrorOperand(Loc, "%rip can only be used as a base register",
2118                               SMRange(Loc, EndLoc));
2119         // Return register that are not segment prefixes immediately.
2120         if (!Parser.parseOptionalToken(AsmToken::Colon))
2121           return X86Operand::CreateReg(Reg, Loc, EndLoc);
2122         if (!X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains(Reg))
2123           return ErrorOperand(Loc, "invalid segment register");
2124       }
2125     }
2126     // This is a Memory operand.
2127     return ParseMemOperand(Reg, Expr, Loc, EndLoc);
2128   }
2129   }
2130 }
2131 
2132 // X86::COND_INVALID if not a recognized condition code or alternate mnemonic,
2133 // otherwise the EFLAGS Condition Code enumerator.
2134 X86::CondCode X86AsmParser::ParseConditionCode(StringRef CC) {
2135   return StringSwitch<X86::CondCode>(CC)
2136       .Case("o", X86::COND_O)          // Overflow
2137       .Case("no", X86::COND_NO)        // No Overflow
2138       .Cases("b", "nae", X86::COND_B)  // Below/Neither Above nor Equal
2139       .Cases("ae", "nb", X86::COND_AE) // Above or Equal/Not Below
2140       .Cases("e", "z", X86::COND_E)    // Equal/Zero
2141       .Cases("ne", "nz", X86::COND_NE) // Not Equal/Not Zero
2142       .Cases("be", "na", X86::COND_BE) // Below or Equal/Not Above
2143       .Cases("a", "nbe", X86::COND_A)  // Above/Neither Below nor Equal
2144       .Case("s", X86::COND_S)          // Sign
2145       .Case("ns", X86::COND_NS)        // No Sign
2146       .Cases("p", "pe", X86::COND_P)   // Parity/Parity Even
2147       .Cases("np", "po", X86::COND_NP) // No Parity/Parity Odd
2148       .Cases("l", "nge", X86::COND_L)  // Less/Neither Greater nor Equal
2149       .Cases("ge", "nl", X86::COND_GE) // Greater or Equal/Not Less
2150       .Cases("le", "ng", X86::COND_LE) // Less or Equal/Not Greater
2151       .Cases("g", "nle", X86::COND_G)  // Greater/Neither Less nor Equal
2152       .Default(X86::COND_INVALID);
2153 }
2154 
2155 // true on failure, false otherwise
2156 // If no {z} mark was found - Parser doesn't advance
2157 bool X86AsmParser::ParseZ(std::unique_ptr<X86Operand> &Z,
2158                           const SMLoc &StartLoc) {
2159   MCAsmParser &Parser = getParser();
2160   // Assuming we are just pass the '{' mark, quering the next token
2161   // Searched for {z}, but none was found. Return false, as no parsing error was
2162   // encountered
2163   if (!(getLexer().is(AsmToken::Identifier) &&
2164         (getLexer().getTok().getIdentifier() == "z")))
2165     return false;
2166   Parser.Lex(); // Eat z
2167   // Query and eat the '}' mark
2168   if (!getLexer().is(AsmToken::RCurly))
2169     return Error(getLexer().getLoc(), "Expected } at this point");
2170   Parser.Lex(); // Eat '}'
2171   // Assign Z with the {z} mark opernad
2172   Z = X86Operand::CreateToken("{z}", StartLoc);
2173   return false;
2174 }
2175 
2176 // true on failure, false otherwise
2177 bool X86AsmParser::HandleAVX512Operand(OperandVector &Operands,
2178                                        const MCParsedAsmOperand &Op) {
2179   MCAsmParser &Parser = getParser();
2180   if (getLexer().is(AsmToken::LCurly)) {
2181     // Eat "{" and mark the current place.
2182     const SMLoc consumedToken = consumeToken();
2183     // Distinguish {1to<NUM>} from {%k<NUM>}.
2184     if(getLexer().is(AsmToken::Integer)) {
2185       // Parse memory broadcasting ({1to<NUM>}).
2186       if (getLexer().getTok().getIntVal() != 1)
2187         return TokError("Expected 1to<NUM> at this point");
2188       Parser.Lex();  // Eat "1" of 1to8
2189       if (!getLexer().is(AsmToken::Identifier) ||
2190           !getLexer().getTok().getIdentifier().startswith("to"))
2191         return TokError("Expected 1to<NUM> at this point");
2192       // Recognize only reasonable suffixes.
2193       const char *BroadcastPrimitive =
2194         StringSwitch<const char*>(getLexer().getTok().getIdentifier())
2195           .Case("to2",  "{1to2}")
2196           .Case("to4",  "{1to4}")
2197           .Case("to8",  "{1to8}")
2198           .Case("to16", "{1to16}")
2199           .Default(nullptr);
2200       if (!BroadcastPrimitive)
2201         return TokError("Invalid memory broadcast primitive.");
2202       Parser.Lex();  // Eat "toN" of 1toN
2203       if (!getLexer().is(AsmToken::RCurly))
2204         return TokError("Expected } at this point");
2205       Parser.Lex();  // Eat "}"
2206       Operands.push_back(X86Operand::CreateToken(BroadcastPrimitive,
2207                                                  consumedToken));
2208       // No AVX512 specific primitives can pass
2209       // after memory broadcasting, so return.
2210       return false;
2211     } else {
2212       // Parse either {k}{z}, {z}{k}, {k} or {z}
2213       // last one have no meaning, but GCC accepts it
2214       // Currently, we're just pass a '{' mark
2215       std::unique_ptr<X86Operand> Z;
2216       if (ParseZ(Z, consumedToken))
2217         return true;
2218       // Reaching here means that parsing of the allegadly '{z}' mark yielded
2219       // no errors.
2220       // Query for the need of further parsing for a {%k<NUM>} mark
2221       if (!Z || getLexer().is(AsmToken::LCurly)) {
2222         SMLoc StartLoc = Z ? consumeToken() : consumedToken;
2223         // Parse an op-mask register mark ({%k<NUM>}), which is now to be
2224         // expected
2225         unsigned RegNo;
2226         SMLoc RegLoc;
2227         if (!ParseRegister(RegNo, RegLoc, StartLoc) &&
2228             X86MCRegisterClasses[X86::VK1RegClassID].contains(RegNo)) {
2229           if (RegNo == X86::K0)
2230             return Error(RegLoc, "Register k0 can't be used as write mask");
2231           if (!getLexer().is(AsmToken::RCurly))
2232             return Error(getLexer().getLoc(), "Expected } at this point");
2233           Operands.push_back(X86Operand::CreateToken("{", StartLoc));
2234           Operands.push_back(
2235               X86Operand::CreateReg(RegNo, StartLoc, StartLoc));
2236           Operands.push_back(X86Operand::CreateToken("}", consumeToken()));
2237         } else
2238           return Error(getLexer().getLoc(),
2239                         "Expected an op-mask register at this point");
2240         // {%k<NUM>} mark is found, inquire for {z}
2241         if (getLexer().is(AsmToken::LCurly) && !Z) {
2242           // Have we've found a parsing error, or found no (expected) {z} mark
2243           // - report an error
2244           if (ParseZ(Z, consumeToken()) || !Z)
2245             return Error(getLexer().getLoc(),
2246                          "Expected a {z} mark at this point");
2247 
2248         }
2249         // '{z}' on its own is meaningless, hence should be ignored.
2250         // on the contrary - have it been accompanied by a K register,
2251         // allow it.
2252         if (Z)
2253           Operands.push_back(std::move(Z));
2254       }
2255     }
2256   }
2257   return false;
2258 }
2259 
2260 /// ParseMemOperand: 'seg : disp(basereg, indexreg, scale)'.  The '%ds:' prefix
2261 /// has already been parsed if present. disp may be provided as well.
2262 std::unique_ptr<X86Operand> X86AsmParser::ParseMemOperand(unsigned SegReg,
2263                                                           const MCExpr *&Disp,
2264                                                           const SMLoc &StartLoc,
2265                                                           SMLoc &EndLoc) {
2266   MCAsmParser &Parser = getParser();
2267   SMLoc Loc;
2268   // Based on the initial passed values, we may be in any of these cases, we are
2269   // in one of these cases (with current position (*)):
2270 
2271   //   1. seg : * disp  (base-index-scale-expr)
2272   //   2. seg : *(disp) (base-index-scale-expr)
2273   //   3. seg :       *(base-index-scale-expr)
2274   //   4.        disp  *(base-index-scale-expr)
2275   //   5.      *(disp)  (base-index-scale-expr)
2276   //   6.             *(base-index-scale-expr)
2277   //   7.  disp *
2278   //   8. *(disp)
2279 
2280   // If we do not have an displacement yet, check if we're in cases 4 or 6 by
2281   // checking if the first object after the parenthesis is a register (or an
2282   // identifier referring to a register) and parse the displacement or default
2283   // to 0 as appropriate.
2284   auto isAtMemOperand = [this]() {
2285     if (this->getLexer().isNot(AsmToken::LParen))
2286       return false;
2287     AsmToken Buf[2];
2288     StringRef Id;
2289     auto TokCount = this->getLexer().peekTokens(Buf, true);
2290     if (TokCount == 0)
2291       return false;
2292     switch (Buf[0].getKind()) {
2293     case AsmToken::Percent:
2294     case AsmToken::Comma:
2295       return true;
2296     // These lower cases are doing a peekIdentifier.
2297     case AsmToken::At:
2298     case AsmToken::Dollar:
2299       if ((TokCount > 1) &&
2300           (Buf[1].is(AsmToken::Identifier) || Buf[1].is(AsmToken::String)) &&
2301           (Buf[0].getLoc().getPointer() + 1 == Buf[1].getLoc().getPointer()))
2302         Id = StringRef(Buf[0].getLoc().getPointer(),
2303                        Buf[1].getIdentifier().size() + 1);
2304       break;
2305     case AsmToken::Identifier:
2306     case AsmToken::String:
2307       Id = Buf[0].getIdentifier();
2308       break;
2309     default:
2310       return false;
2311     }
2312     // We have an ID. Check if it is bound to a register.
2313     if (!Id.empty()) {
2314       MCSymbol *Sym = this->getContext().getOrCreateSymbol(Id);
2315       if (Sym->isVariable()) {
2316         auto V = Sym->getVariableValue(/*SetUsed*/ false);
2317         return isa<X86MCExpr>(V);
2318       }
2319     }
2320     return false;
2321   };
2322 
2323   if (!Disp) {
2324     // Parse immediate if we're not at a mem operand yet.
2325     if (!isAtMemOperand()) {
2326       if (Parser.parseTokenLoc(Loc) || Parser.parseExpression(Disp, EndLoc))
2327         return nullptr;
2328       assert(!isa<X86MCExpr>(Disp) && "Expected non-register here.");
2329     } else {
2330       // Disp is implicitly zero if we haven't parsed it yet.
2331       Disp = MCConstantExpr::create(0, Parser.getContext());
2332     }
2333   }
2334 
2335   // We are now either at the end of the operand or at the '(' at the start of a
2336   // base-index-scale-expr.
2337 
2338   if (!parseOptionalToken(AsmToken::LParen)) {
2339     if (SegReg == 0)
2340       return X86Operand::CreateMem(getPointerWidth(), Disp, StartLoc, EndLoc);
2341     return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, 0, 0, 1,
2342                                  StartLoc, EndLoc);
2343   }
2344 
2345   // If we reached here, then eat the '(' and Process
2346   // the rest of the memory operand.
2347   unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
2348   SMLoc BaseLoc = getLexer().getLoc();
2349   const MCExpr *E;
2350   StringRef ErrMsg;
2351 
2352   // Parse BaseReg if one is provided.
2353   if (getLexer().isNot(AsmToken::Comma) && getLexer().isNot(AsmToken::RParen)) {
2354     if (Parser.parseExpression(E, EndLoc) ||
2355         check(!isa<X86MCExpr>(E), BaseLoc, "expected register here"))
2356       return nullptr;
2357 
2358     // Sanity check register.
2359     BaseReg = cast<X86MCExpr>(E)->getRegNo();
2360     if (BaseReg == X86::EIZ || BaseReg == X86::RIZ)
2361       return ErrorOperand(BaseLoc,
2362                           "eiz and riz can only be used as index registers",
2363                           SMRange(BaseLoc, EndLoc));
2364   }
2365 
2366   if (parseOptionalToken(AsmToken::Comma)) {
2367     // Following the comma we should have either an index register, or a scale
2368     // value. We don't support the later form, but we want to parse it
2369     // correctly.
2370     //
2371     // Even though it would be completely consistent to support syntax like
2372     // "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
2373     if (getLexer().isNot(AsmToken::RParen)) {
2374       if (Parser.parseTokenLoc(Loc) || Parser.parseExpression(E, EndLoc))
2375         return nullptr;
2376 
2377       if (!isa<X86MCExpr>(E)) {
2378         // We've parsed an unexpected Scale Value instead of an index
2379         // register. Interpret it as an absolute.
2380         int64_t ScaleVal;
2381         if (!E->evaluateAsAbsolute(ScaleVal, getStreamer().getAssemblerPtr()))
2382           return ErrorOperand(Loc, "expected absolute expression");
2383         if (ScaleVal != 1)
2384           Warning(Loc, "scale factor without index register is ignored");
2385         Scale = 1;
2386       } else { // IndexReg Found.
2387         IndexReg = cast<X86MCExpr>(E)->getRegNo();
2388 
2389         if (BaseReg == X86::RIP)
2390           return ErrorOperand(
2391               Loc, "%rip as base register can not have an index register");
2392         if (IndexReg == X86::RIP)
2393           return ErrorOperand(Loc, "%rip is not allowed as an index register");
2394 
2395         if (parseOptionalToken(AsmToken::Comma)) {
2396           // Parse the scale amount:
2397           //  ::= ',' [scale-expression]
2398 
2399           // A scale amount without an index is ignored.
2400           if (getLexer().isNot(AsmToken::RParen)) {
2401             int64_t ScaleVal;
2402             if (Parser.parseTokenLoc(Loc) ||
2403                 Parser.parseAbsoluteExpression(ScaleVal))
2404               return ErrorOperand(Loc, "expected scale expression");
2405             Scale = (unsigned)ScaleVal;
2406             // Validate the scale amount.
2407             if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) &&
2408                 Scale != 1)
2409               return ErrorOperand(Loc,
2410                                   "scale factor in 16-bit address must be 1");
2411             if (checkScale(Scale, ErrMsg))
2412               return ErrorOperand(Loc, ErrMsg);
2413           }
2414         }
2415       }
2416     }
2417   }
2418 
2419   // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
2420   if (parseToken(AsmToken::RParen, "unexpected token in memory operand"))
2421     return nullptr;
2422 
2423   // This is to support otherwise illegal operand (%dx) found in various
2424   // unofficial manuals examples (e.g. "out[s]?[bwl]? %al, (%dx)") and must now
2425   // be supported. Mark such DX variants separately fix only in special cases.
2426   if (BaseReg == X86::DX && IndexReg == 0 && Scale == 1 && SegReg == 0 &&
2427       isa<MCConstantExpr>(Disp) && cast<MCConstantExpr>(Disp)->getValue() == 0)
2428     return X86Operand::CreateDXReg(BaseLoc, BaseLoc);
2429 
2430   if (CheckBaseRegAndIndexRegAndScale(BaseReg, IndexReg, Scale, is64BitMode(),
2431                                       ErrMsg))
2432     return ErrorOperand(BaseLoc, ErrMsg);
2433 
2434   if (SegReg || BaseReg || IndexReg)
2435     return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, BaseReg,
2436                                  IndexReg, Scale, StartLoc, EndLoc);
2437   return X86Operand::CreateMem(getPointerWidth(), Disp, StartLoc, EndLoc);
2438 }
2439 
2440 // Parse either a standard primary expression or a register.
2441 bool X86AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
2442   MCAsmParser &Parser = getParser();
2443   // See if this is a register first.
2444   if (getTok().is(AsmToken::Percent) ||
2445       (isParsingIntelSyntax() && getTok().is(AsmToken::Identifier) &&
2446        MatchRegisterName(Parser.getTok().getString()))) {
2447     SMLoc StartLoc = Parser.getTok().getLoc();
2448     unsigned RegNo;
2449     if (ParseRegister(RegNo, StartLoc, EndLoc))
2450       return true;
2451     Res = X86MCExpr::create(RegNo, Parser.getContext());
2452     return false;
2453   }
2454   return Parser.parsePrimaryExpr(Res, EndLoc);
2455 }
2456 
2457 bool X86AsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
2458                                     SMLoc NameLoc, OperandVector &Operands) {
2459   MCAsmParser &Parser = getParser();
2460   InstInfo = &Info;
2461 
2462   // Reset the forced VEX encoding.
2463   ForcedVEXEncoding = VEXEncoding_Default;
2464 
2465   // Parse pseudo prefixes.
2466   while (1) {
2467     if (Name == "{") {
2468       if (getLexer().isNot(AsmToken::Identifier))
2469         return Error(Parser.getTok().getLoc(), "Unexpected token after '{'");
2470       std::string Prefix = Parser.getTok().getString().lower();
2471       Parser.Lex(); // Eat identifier.
2472       if (getLexer().isNot(AsmToken::RCurly))
2473         return Error(Parser.getTok().getLoc(), "Expected '}'");
2474       Parser.Lex(); // Eat curly.
2475 
2476       if (Prefix == "vex2")
2477         ForcedVEXEncoding = VEXEncoding_VEX2;
2478       else if (Prefix == "vex3")
2479         ForcedVEXEncoding = VEXEncoding_VEX3;
2480       else if (Prefix == "evex")
2481         ForcedVEXEncoding = VEXEncoding_EVEX;
2482       else
2483         return Error(NameLoc, "unknown prefix");
2484 
2485       NameLoc = Parser.getTok().getLoc();
2486       if (getLexer().is(AsmToken::LCurly)) {
2487         Parser.Lex();
2488         Name = "{";
2489       } else {
2490         if (getLexer().isNot(AsmToken::Identifier))
2491           return Error(Parser.getTok().getLoc(), "Expected identifier");
2492         // FIXME: The mnemonic won't match correctly if its not in lower case.
2493         Name = Parser.getTok().getString();
2494         Parser.Lex();
2495       }
2496       continue;
2497     }
2498 
2499     break;
2500   }
2501 
2502   StringRef PatchedName = Name;
2503 
2504   // Hack to skip "short" following Jcc.
2505   if (isParsingIntelSyntax() &&
2506       (PatchedName == "jmp" || PatchedName == "jc" || PatchedName == "jnc" ||
2507        PatchedName == "jcxz" || PatchedName == "jexcz" ||
2508        (PatchedName.startswith("j") &&
2509         ParseConditionCode(PatchedName.substr(1)) != X86::COND_INVALID))) {
2510     StringRef NextTok = Parser.getTok().getString();
2511     if (NextTok == "short") {
2512       SMLoc NameEndLoc =
2513           NameLoc.getFromPointer(NameLoc.getPointer() + Name.size());
2514       // Eat the short keyword.
2515       Parser.Lex();
2516       // MS and GAS ignore the short keyword; they both determine the jmp type
2517       // based on the distance of the label. (NASM does emit different code with
2518       // and without "short," though.)
2519       InstInfo->AsmRewrites->emplace_back(AOK_Skip, NameEndLoc,
2520                                           NextTok.size() + 1);
2521     }
2522   }
2523 
2524   // FIXME: Hack to recognize setneb as setne.
2525   if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
2526       PatchedName != "setb" && PatchedName != "setnb")
2527     PatchedName = PatchedName.substr(0, Name.size()-1);
2528 
2529   unsigned ComparisonPredicate = ~0U;
2530 
2531   // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
2532   if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
2533       (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
2534        PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
2535     bool IsVCMP = PatchedName[0] == 'v';
2536     unsigned CCIdx = IsVCMP ? 4 : 3;
2537     unsigned CC = StringSwitch<unsigned>(
2538       PatchedName.slice(CCIdx, PatchedName.size() - 2))
2539       .Case("eq",       0x00)
2540       .Case("eq_oq",    0x00)
2541       .Case("lt",       0x01)
2542       .Case("lt_os",    0x01)
2543       .Case("le",       0x02)
2544       .Case("le_os",    0x02)
2545       .Case("unord",    0x03)
2546       .Case("unord_q",  0x03)
2547       .Case("neq",      0x04)
2548       .Case("neq_uq",   0x04)
2549       .Case("nlt",      0x05)
2550       .Case("nlt_us",   0x05)
2551       .Case("nle",      0x06)
2552       .Case("nle_us",   0x06)
2553       .Case("ord",      0x07)
2554       .Case("ord_q",    0x07)
2555       /* AVX only from here */
2556       .Case("eq_uq",    0x08)
2557       .Case("nge",      0x09)
2558       .Case("nge_us",   0x09)
2559       .Case("ngt",      0x0A)
2560       .Case("ngt_us",   0x0A)
2561       .Case("false",    0x0B)
2562       .Case("false_oq", 0x0B)
2563       .Case("neq_oq",   0x0C)
2564       .Case("ge",       0x0D)
2565       .Case("ge_os",    0x0D)
2566       .Case("gt",       0x0E)
2567       .Case("gt_os",    0x0E)
2568       .Case("true",     0x0F)
2569       .Case("true_uq",  0x0F)
2570       .Case("eq_os",    0x10)
2571       .Case("lt_oq",    0x11)
2572       .Case("le_oq",    0x12)
2573       .Case("unord_s",  0x13)
2574       .Case("neq_us",   0x14)
2575       .Case("nlt_uq",   0x15)
2576       .Case("nle_uq",   0x16)
2577       .Case("ord_s",    0x17)
2578       .Case("eq_us",    0x18)
2579       .Case("nge_uq",   0x19)
2580       .Case("ngt_uq",   0x1A)
2581       .Case("false_os", 0x1B)
2582       .Case("neq_os",   0x1C)
2583       .Case("ge_oq",    0x1D)
2584       .Case("gt_oq",    0x1E)
2585       .Case("true_us",  0x1F)
2586       .Default(~0U);
2587     if (CC != ~0U && (IsVCMP || CC < 8)) {
2588       if (PatchedName.endswith("ss"))
2589         PatchedName = IsVCMP ? "vcmpss" : "cmpss";
2590       else if (PatchedName.endswith("sd"))
2591         PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
2592       else if (PatchedName.endswith("ps"))
2593         PatchedName = IsVCMP ? "vcmpps" : "cmpps";
2594       else if (PatchedName.endswith("pd"))
2595         PatchedName = IsVCMP ? "vcmppd" : "cmppd";
2596       else
2597         llvm_unreachable("Unexpected suffix!");
2598 
2599       ComparisonPredicate = CC;
2600     }
2601   }
2602 
2603   // FIXME: Hack to recognize vpcmp<comparison code>{ub,uw,ud,uq,b,w,d,q}.
2604   if (PatchedName.startswith("vpcmp") &&
2605       (PatchedName.back() == 'b' || PatchedName.back() == 'w' ||
2606        PatchedName.back() == 'd' || PatchedName.back() == 'q')) {
2607     unsigned SuffixSize = PatchedName.drop_back().back() == 'u' ? 2 : 1;
2608     unsigned CC = StringSwitch<unsigned>(
2609       PatchedName.slice(5, PatchedName.size() - SuffixSize))
2610       .Case("eq",    0x0) // Only allowed on unsigned. Checked below.
2611       .Case("lt",    0x1)
2612       .Case("le",    0x2)
2613       //.Case("false", 0x3) // Not a documented alias.
2614       .Case("neq",   0x4)
2615       .Case("nlt",   0x5)
2616       .Case("nle",   0x6)
2617       //.Case("true",  0x7) // Not a documented alias.
2618       .Default(~0U);
2619     if (CC != ~0U && (CC != 0 || SuffixSize == 2)) {
2620       switch (PatchedName.back()) {
2621       default: llvm_unreachable("Unexpected character!");
2622       case 'b': PatchedName = SuffixSize == 2 ? "vpcmpub" : "vpcmpb"; break;
2623       case 'w': PatchedName = SuffixSize == 2 ? "vpcmpuw" : "vpcmpw"; break;
2624       case 'd': PatchedName = SuffixSize == 2 ? "vpcmpud" : "vpcmpd"; break;
2625       case 'q': PatchedName = SuffixSize == 2 ? "vpcmpuq" : "vpcmpq"; break;
2626       }
2627       // Set up the immediate to push into the operands later.
2628       ComparisonPredicate = CC;
2629     }
2630   }
2631 
2632   // FIXME: Hack to recognize vpcom<comparison code>{ub,uw,ud,uq,b,w,d,q}.
2633   if (PatchedName.startswith("vpcom") &&
2634       (PatchedName.back() == 'b' || PatchedName.back() == 'w' ||
2635        PatchedName.back() == 'd' || PatchedName.back() == 'q')) {
2636     unsigned SuffixSize = PatchedName.drop_back().back() == 'u' ? 2 : 1;
2637     unsigned CC = StringSwitch<unsigned>(
2638       PatchedName.slice(5, PatchedName.size() - SuffixSize))
2639       .Case("lt",    0x0)
2640       .Case("le",    0x1)
2641       .Case("gt",    0x2)
2642       .Case("ge",    0x3)
2643       .Case("eq",    0x4)
2644       .Case("neq",   0x5)
2645       .Case("false", 0x6)
2646       .Case("true",  0x7)
2647       .Default(~0U);
2648     if (CC != ~0U) {
2649       switch (PatchedName.back()) {
2650       default: llvm_unreachable("Unexpected character!");
2651       case 'b': PatchedName = SuffixSize == 2 ? "vpcomub" : "vpcomb"; break;
2652       case 'w': PatchedName = SuffixSize == 2 ? "vpcomuw" : "vpcomw"; break;
2653       case 'd': PatchedName = SuffixSize == 2 ? "vpcomud" : "vpcomd"; break;
2654       case 'q': PatchedName = SuffixSize == 2 ? "vpcomuq" : "vpcomq"; break;
2655       }
2656       // Set up the immediate to push into the operands later.
2657       ComparisonPredicate = CC;
2658     }
2659   }
2660 
2661 
2662   // Determine whether this is an instruction prefix.
2663   // FIXME:
2664   // Enhance prefixes integrity robustness. for example, following forms
2665   // are currently tolerated:
2666   // repz repnz <insn>    ; GAS errors for the use of two similar prefixes
2667   // lock addq %rax, %rbx ; Destination operand must be of memory type
2668   // xacquire <insn>      ; xacquire must be accompanied by 'lock'
2669   bool isPrefix = StringSwitch<bool>(Name)
2670                       .Cases("rex64", "data32", "data16", true)
2671                       .Cases("xacquire", "xrelease", true)
2672                       .Cases("acquire", "release", isParsingIntelSyntax())
2673                       .Default(false);
2674 
2675   auto isLockRepeatNtPrefix = [](StringRef N) {
2676     return StringSwitch<bool>(N)
2677         .Cases("lock", "rep", "repe", "repz", "repne", "repnz", "notrack", true)
2678         .Default(false);
2679   };
2680 
2681   bool CurlyAsEndOfStatement = false;
2682 
2683   unsigned Flags = X86::IP_NO_PREFIX;
2684   while (isLockRepeatNtPrefix(Name.lower())) {
2685     unsigned Prefix =
2686         StringSwitch<unsigned>(Name)
2687             .Cases("lock", "lock", X86::IP_HAS_LOCK)
2688             .Cases("rep", "repe", "repz", X86::IP_HAS_REPEAT)
2689             .Cases("repne", "repnz", X86::IP_HAS_REPEAT_NE)
2690             .Cases("notrack", "notrack", X86::IP_HAS_NOTRACK)
2691             .Default(X86::IP_NO_PREFIX); // Invalid prefix (impossible)
2692     Flags |= Prefix;
2693     if (getLexer().is(AsmToken::EndOfStatement)) {
2694       // We don't have real instr with the given prefix
2695       //  let's use the prefix as the instr.
2696       // TODO: there could be several prefixes one after another
2697       Flags = X86::IP_NO_PREFIX;
2698       break;
2699     }
2700     // FIXME: The mnemonic won't match correctly if its not in lower case.
2701     Name = Parser.getTok().getString();
2702     Parser.Lex(); // eat the prefix
2703     // Hack: we could have something like "rep # some comment" or
2704     //    "lock; cmpxchg16b $1" or "lock\0A\09incl" or "lock/incl"
2705     while (Name.startswith(";") || Name.startswith("\n") ||
2706            Name.startswith("#") || Name.startswith("\t") ||
2707            Name.startswith("/")) {
2708       // FIXME: The mnemonic won't match correctly if its not in lower case.
2709       Name = Parser.getTok().getString();
2710       Parser.Lex(); // go to next prefix or instr
2711     }
2712   }
2713 
2714   if (Flags)
2715     PatchedName = Name;
2716 
2717   // Hacks to handle 'data16' and 'data32'
2718   if (PatchedName == "data16" && is16BitMode()) {
2719     return Error(NameLoc, "redundant data16 prefix");
2720   }
2721   if (PatchedName == "data32") {
2722     if (is32BitMode())
2723       return Error(NameLoc, "redundant data32 prefix");
2724     if (is64BitMode())
2725       return Error(NameLoc, "'data32' is not supported in 64-bit mode");
2726     // Hack to 'data16' for the table lookup.
2727     PatchedName = "data16";
2728   }
2729 
2730   Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
2731 
2732   // Push the immediate if we extracted one from the mnemonic.
2733   if (ComparisonPredicate != ~0U && !isParsingIntelSyntax()) {
2734     const MCExpr *ImmOp = MCConstantExpr::create(ComparisonPredicate,
2735                                                  getParser().getContext());
2736     Operands.push_back(X86Operand::CreateImm(ImmOp, NameLoc, NameLoc));
2737   }
2738 
2739   // This does the actual operand parsing.  Don't parse any more if we have a
2740   // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
2741   // just want to parse the "lock" as the first instruction and the "incl" as
2742   // the next one.
2743   if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
2744     // Parse '*' modifier.
2745     if (getLexer().is(AsmToken::Star))
2746       Operands.push_back(X86Operand::CreateToken("*", consumeToken()));
2747 
2748     // Read the operands.
2749     while(1) {
2750       if (std::unique_ptr<X86Operand> Op = ParseOperand()) {
2751         Operands.push_back(std::move(Op));
2752         if (HandleAVX512Operand(Operands, *Operands.back()))
2753           return true;
2754       } else {
2755          return true;
2756       }
2757       // check for comma and eat it
2758       if (getLexer().is(AsmToken::Comma))
2759         Parser.Lex();
2760       else
2761         break;
2762      }
2763 
2764     // In MS inline asm curly braces mark the beginning/end of a block,
2765     // therefore they should be interepreted as end of statement
2766     CurlyAsEndOfStatement =
2767         isParsingIntelSyntax() && isParsingMSInlineAsm() &&
2768         (getLexer().is(AsmToken::LCurly) || getLexer().is(AsmToken::RCurly));
2769     if (getLexer().isNot(AsmToken::EndOfStatement) && !CurlyAsEndOfStatement)
2770       return TokError("unexpected token in argument list");
2771   }
2772 
2773   // Push the immediate if we extracted one from the mnemonic.
2774   if (ComparisonPredicate != ~0U && isParsingIntelSyntax()) {
2775     const MCExpr *ImmOp = MCConstantExpr::create(ComparisonPredicate,
2776                                                  getParser().getContext());
2777     Operands.push_back(X86Operand::CreateImm(ImmOp, NameLoc, NameLoc));
2778   }
2779 
2780   // Consume the EndOfStatement or the prefix separator Slash
2781   if (getLexer().is(AsmToken::EndOfStatement) ||
2782       (isPrefix && getLexer().is(AsmToken::Slash)))
2783     Parser.Lex();
2784   else if (CurlyAsEndOfStatement)
2785     // Add an actual EndOfStatement before the curly brace
2786     Info.AsmRewrites->emplace_back(AOK_EndOfStatement,
2787                                    getLexer().getTok().getLoc(), 0);
2788 
2789   // This is for gas compatibility and cannot be done in td.
2790   // Adding "p" for some floating point with no argument.
2791   // For example: fsub --> fsubp
2792   bool IsFp =
2793     Name == "fsub" || Name == "fdiv" || Name == "fsubr" || Name == "fdivr";
2794   if (IsFp && Operands.size() == 1) {
2795     const char *Repl = StringSwitch<const char *>(Name)
2796       .Case("fsub", "fsubp")
2797       .Case("fdiv", "fdivp")
2798       .Case("fsubr", "fsubrp")
2799       .Case("fdivr", "fdivrp");
2800     static_cast<X86Operand &>(*Operands[0]).setTokenValue(Repl);
2801   }
2802 
2803   if ((Name == "mov" || Name == "movw" || Name == "movl") &&
2804       (Operands.size() == 3)) {
2805     X86Operand &Op1 = (X86Operand &)*Operands[1];
2806     X86Operand &Op2 = (X86Operand &)*Operands[2];
2807     SMLoc Loc = Op1.getEndLoc();
2808     // Moving a 32 or 16 bit value into a segment register has the same
2809     // behavior. Modify such instructions to always take shorter form.
2810     if (Op1.isReg() && Op2.isReg() &&
2811         X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains(
2812             Op2.getReg()) &&
2813         (X86MCRegisterClasses[X86::GR16RegClassID].contains(Op1.getReg()) ||
2814          X86MCRegisterClasses[X86::GR32RegClassID].contains(Op1.getReg()))) {
2815       // Change instruction name to match new instruction.
2816       if (Name != "mov" && Name[3] == (is16BitMode() ? 'l' : 'w')) {
2817         Name = is16BitMode() ? "movw" : "movl";
2818         Operands[0] = X86Operand::CreateToken(Name, NameLoc);
2819       }
2820       // Select the correct equivalent 16-/32-bit source register.
2821       unsigned Reg =
2822           getX86SubSuperRegisterOrZero(Op1.getReg(), is16BitMode() ? 16 : 32);
2823       Operands[1] = X86Operand::CreateReg(Reg, Loc, Loc);
2824     }
2825   }
2826 
2827   // This is a terrible hack to handle "out[s]?[bwl]? %al, (%dx)" ->
2828   // "outb %al, %dx".  Out doesn't take a memory form, but this is a widely
2829   // documented form in various unofficial manuals, so a lot of code uses it.
2830   if ((Name == "outb" || Name == "outsb" || Name == "outw" || Name == "outsw" ||
2831        Name == "outl" || Name == "outsl" || Name == "out" || Name == "outs") &&
2832       Operands.size() == 3) {
2833     X86Operand &Op = (X86Operand &)*Operands.back();
2834     if (Op.isDXReg())
2835       Operands.back() = X86Operand::CreateReg(X86::DX, Op.getStartLoc(),
2836                                               Op.getEndLoc());
2837   }
2838   // Same hack for "in[s]?[bwl]? (%dx), %al" -> "inb %dx, %al".
2839   if ((Name == "inb" || Name == "insb" || Name == "inw" || Name == "insw" ||
2840        Name == "inl" || Name == "insl" || Name == "in" || Name == "ins") &&
2841       Operands.size() == 3) {
2842     X86Operand &Op = (X86Operand &)*Operands[1];
2843     if (Op.isDXReg())
2844       Operands[1] = X86Operand::CreateReg(X86::DX, Op.getStartLoc(),
2845                                           Op.getEndLoc());
2846   }
2847 
2848   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 2> TmpOperands;
2849   bool HadVerifyError = false;
2850 
2851   // Append default arguments to "ins[bwld]"
2852   if (Name.startswith("ins") &&
2853       (Operands.size() == 1 || Operands.size() == 3) &&
2854       (Name == "insb" || Name == "insw" || Name == "insl" || Name == "insd" ||
2855        Name == "ins")) {
2856 
2857     AddDefaultSrcDestOperands(TmpOperands,
2858                               X86Operand::CreateReg(X86::DX, NameLoc, NameLoc),
2859                               DefaultMemDIOperand(NameLoc));
2860     HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
2861   }
2862 
2863   // Append default arguments to "outs[bwld]"
2864   if (Name.startswith("outs") &&
2865       (Operands.size() == 1 || Operands.size() == 3) &&
2866       (Name == "outsb" || Name == "outsw" || Name == "outsl" ||
2867        Name == "outsd" || Name == "outs")) {
2868     AddDefaultSrcDestOperands(TmpOperands, DefaultMemSIOperand(NameLoc),
2869                               X86Operand::CreateReg(X86::DX, NameLoc, NameLoc));
2870     HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
2871   }
2872 
2873   // Transform "lods[bwlq]" into "lods[bwlq] ($SIREG)" for appropriate
2874   // values of $SIREG according to the mode. It would be nice if this
2875   // could be achieved with InstAlias in the tables.
2876   if (Name.startswith("lods") &&
2877       (Operands.size() == 1 || Operands.size() == 2) &&
2878       (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
2879        Name == "lodsl" || Name == "lodsd" || Name == "lodsq")) {
2880     TmpOperands.push_back(DefaultMemSIOperand(NameLoc));
2881     HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
2882   }
2883 
2884   // Transform "stos[bwlq]" into "stos[bwlq] ($DIREG)" for appropriate
2885   // values of $DIREG according to the mode. It would be nice if this
2886   // could be achieved with InstAlias in the tables.
2887   if (Name.startswith("stos") &&
2888       (Operands.size() == 1 || Operands.size() == 2) &&
2889       (Name == "stos" || Name == "stosb" || Name == "stosw" ||
2890        Name == "stosl" || Name == "stosd" || Name == "stosq")) {
2891     TmpOperands.push_back(DefaultMemDIOperand(NameLoc));
2892     HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
2893   }
2894 
2895   // Transform "scas[bwlq]" into "scas[bwlq] ($DIREG)" for appropriate
2896   // values of $DIREG according to the mode. It would be nice if this
2897   // could be achieved with InstAlias in the tables.
2898   if (Name.startswith("scas") &&
2899       (Operands.size() == 1 || Operands.size() == 2) &&
2900       (Name == "scas" || Name == "scasb" || Name == "scasw" ||
2901        Name == "scasl" || Name == "scasd" || Name == "scasq")) {
2902     TmpOperands.push_back(DefaultMemDIOperand(NameLoc));
2903     HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
2904   }
2905 
2906   // Add default SI and DI operands to "cmps[bwlq]".
2907   if (Name.startswith("cmps") &&
2908       (Operands.size() == 1 || Operands.size() == 3) &&
2909       (Name == "cmps" || Name == "cmpsb" || Name == "cmpsw" ||
2910        Name == "cmpsl" || Name == "cmpsd" || Name == "cmpsq")) {
2911     AddDefaultSrcDestOperands(TmpOperands, DefaultMemDIOperand(NameLoc),
2912                               DefaultMemSIOperand(NameLoc));
2913     HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
2914   }
2915 
2916   // Add default SI and DI operands to "movs[bwlq]".
2917   if (((Name.startswith("movs") &&
2918         (Name == "movs" || Name == "movsb" || Name == "movsw" ||
2919          Name == "movsl" || Name == "movsd" || Name == "movsq")) ||
2920        (Name.startswith("smov") &&
2921         (Name == "smov" || Name == "smovb" || Name == "smovw" ||
2922          Name == "smovl" || Name == "smovd" || Name == "smovq"))) &&
2923       (Operands.size() == 1 || Operands.size() == 3)) {
2924     if (Name == "movsd" && Operands.size() == 1 && !isParsingIntelSyntax())
2925       Operands.back() = X86Operand::CreateToken("movsl", NameLoc);
2926     AddDefaultSrcDestOperands(TmpOperands, DefaultMemSIOperand(NameLoc),
2927                               DefaultMemDIOperand(NameLoc));
2928     HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
2929   }
2930 
2931   // Check if we encountered an error for one the string insturctions
2932   if (HadVerifyError) {
2933     return HadVerifyError;
2934   }
2935 
2936   // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>.  Canonicalize to
2937   // "shift <op>".
2938   if ((Name.startswith("shr") || Name.startswith("sar") ||
2939        Name.startswith("shl") || Name.startswith("sal") ||
2940        Name.startswith("rcl") || Name.startswith("rcr") ||
2941        Name.startswith("rol") || Name.startswith("ror")) &&
2942       Operands.size() == 3) {
2943     if (isParsingIntelSyntax()) {
2944       // Intel syntax
2945       X86Operand &Op1 = static_cast<X86Operand &>(*Operands[2]);
2946       if (Op1.isImm() && isa<MCConstantExpr>(Op1.getImm()) &&
2947           cast<MCConstantExpr>(Op1.getImm())->getValue() == 1)
2948         Operands.pop_back();
2949     } else {
2950       X86Operand &Op1 = static_cast<X86Operand &>(*Operands[1]);
2951       if (Op1.isImm() && isa<MCConstantExpr>(Op1.getImm()) &&
2952           cast<MCConstantExpr>(Op1.getImm())->getValue() == 1)
2953         Operands.erase(Operands.begin() + 1);
2954     }
2955   }
2956 
2957   // Transforms "int $3" into "int3" as a size optimization.  We can't write an
2958   // instalias with an immediate operand yet.
2959   if (Name == "int" && Operands.size() == 2) {
2960     X86Operand &Op1 = static_cast<X86Operand &>(*Operands[1]);
2961     if (Op1.isImm())
2962       if (auto *CE = dyn_cast<MCConstantExpr>(Op1.getImm()))
2963         if (CE->getValue() == 3) {
2964           Operands.erase(Operands.begin() + 1);
2965           static_cast<X86Operand &>(*Operands[0]).setTokenValue("int3");
2966         }
2967   }
2968 
2969   // Transforms "xlat mem8" into "xlatb"
2970   if ((Name == "xlat" || Name == "xlatb") && Operands.size() == 2) {
2971     X86Operand &Op1 = static_cast<X86Operand &>(*Operands[1]);
2972     if (Op1.isMem8()) {
2973       Warning(Op1.getStartLoc(), "memory operand is only for determining the "
2974                                  "size, (R|E)BX will be used for the location");
2975       Operands.pop_back();
2976       static_cast<X86Operand &>(*Operands[0]).setTokenValue("xlatb");
2977     }
2978   }
2979 
2980   if (Flags)
2981     Operands.push_back(X86Operand::CreatePrefix(Flags, NameLoc, NameLoc));
2982   return false;
2983 }
2984 
2985 bool X86AsmParser::processInstruction(MCInst &Inst, const OperandVector &Ops) {
2986   const MCRegisterInfo *MRI = getContext().getRegisterInfo();
2987 
2988   switch (Inst.getOpcode()) {
2989   default: return false;
2990   case X86::VMOVZPQILo2PQIrr:
2991   case X86::VMOVAPDrr:
2992   case X86::VMOVAPDYrr:
2993   case X86::VMOVAPSrr:
2994   case X86::VMOVAPSYrr:
2995   case X86::VMOVDQArr:
2996   case X86::VMOVDQAYrr:
2997   case X86::VMOVDQUrr:
2998   case X86::VMOVDQUYrr:
2999   case X86::VMOVUPDrr:
3000   case X86::VMOVUPDYrr:
3001   case X86::VMOVUPSrr:
3002   case X86::VMOVUPSYrr: {
3003     // We can get a smaller encoding by using VEX.R instead of VEX.B if one of
3004     // the registers is extended, but other isn't.
3005     if (ForcedVEXEncoding == VEXEncoding_VEX3 ||
3006         MRI->getEncodingValue(Inst.getOperand(0).getReg()) >= 8 ||
3007         MRI->getEncodingValue(Inst.getOperand(1).getReg()) < 8)
3008       return false;
3009 
3010     unsigned NewOpc;
3011     switch (Inst.getOpcode()) {
3012     default: llvm_unreachable("Invalid opcode");
3013     case X86::VMOVZPQILo2PQIrr: NewOpc = X86::VMOVPQI2QIrr;   break;
3014     case X86::VMOVAPDrr:        NewOpc = X86::VMOVAPDrr_REV;  break;
3015     case X86::VMOVAPDYrr:       NewOpc = X86::VMOVAPDYrr_REV; break;
3016     case X86::VMOVAPSrr:        NewOpc = X86::VMOVAPSrr_REV;  break;
3017     case X86::VMOVAPSYrr:       NewOpc = X86::VMOVAPSYrr_REV; break;
3018     case X86::VMOVDQArr:        NewOpc = X86::VMOVDQArr_REV;  break;
3019     case X86::VMOVDQAYrr:       NewOpc = X86::VMOVDQAYrr_REV; break;
3020     case X86::VMOVDQUrr:        NewOpc = X86::VMOVDQUrr_REV;  break;
3021     case X86::VMOVDQUYrr:       NewOpc = X86::VMOVDQUYrr_REV; break;
3022     case X86::VMOVUPDrr:        NewOpc = X86::VMOVUPDrr_REV;  break;
3023     case X86::VMOVUPDYrr:       NewOpc = X86::VMOVUPDYrr_REV; break;
3024     case X86::VMOVUPSrr:        NewOpc = X86::VMOVUPSrr_REV;  break;
3025     case X86::VMOVUPSYrr:       NewOpc = X86::VMOVUPSYrr_REV; break;
3026     }
3027     Inst.setOpcode(NewOpc);
3028     return true;
3029   }
3030   case X86::VMOVSDrr:
3031   case X86::VMOVSSrr: {
3032     // We can get a smaller encoding by using VEX.R instead of VEX.B if one of
3033     // the registers is extended, but other isn't.
3034     if (ForcedVEXEncoding == VEXEncoding_VEX3 ||
3035         MRI->getEncodingValue(Inst.getOperand(0).getReg()) >= 8 ||
3036         MRI->getEncodingValue(Inst.getOperand(2).getReg()) < 8)
3037       return false;
3038 
3039     unsigned NewOpc;
3040     switch (Inst.getOpcode()) {
3041     default: llvm_unreachable("Invalid opcode");
3042     case X86::VMOVSDrr: NewOpc = X86::VMOVSDrr_REV; break;
3043     case X86::VMOVSSrr: NewOpc = X86::VMOVSSrr_REV; break;
3044     }
3045     Inst.setOpcode(NewOpc);
3046     return true;
3047   }
3048   }
3049 }
3050 
3051 bool X86AsmParser::validateInstruction(MCInst &Inst, const OperandVector &Ops) {
3052   const MCRegisterInfo *MRI = getContext().getRegisterInfo();
3053 
3054   switch (Inst.getOpcode()) {
3055   case X86::VGATHERDPDYrm:
3056   case X86::VGATHERDPDrm:
3057   case X86::VGATHERDPSYrm:
3058   case X86::VGATHERDPSrm:
3059   case X86::VGATHERQPDYrm:
3060   case X86::VGATHERQPDrm:
3061   case X86::VGATHERQPSYrm:
3062   case X86::VGATHERQPSrm:
3063   case X86::VPGATHERDDYrm:
3064   case X86::VPGATHERDDrm:
3065   case X86::VPGATHERDQYrm:
3066   case X86::VPGATHERDQrm:
3067   case X86::VPGATHERQDYrm:
3068   case X86::VPGATHERQDrm:
3069   case X86::VPGATHERQQYrm:
3070   case X86::VPGATHERQQrm: {
3071     unsigned Dest = MRI->getEncodingValue(Inst.getOperand(0).getReg());
3072     unsigned Mask = MRI->getEncodingValue(Inst.getOperand(1).getReg());
3073     unsigned Index =
3074       MRI->getEncodingValue(Inst.getOperand(3 + X86::AddrIndexReg).getReg());
3075     if (Dest == Mask || Dest == Index || Mask == Index)
3076       return Warning(Ops[0]->getStartLoc(), "mask, index, and destination "
3077                                             "registers should be distinct");
3078     break;
3079   }
3080   case X86::VGATHERDPDZ128rm:
3081   case X86::VGATHERDPDZ256rm:
3082   case X86::VGATHERDPDZrm:
3083   case X86::VGATHERDPSZ128rm:
3084   case X86::VGATHERDPSZ256rm:
3085   case X86::VGATHERDPSZrm:
3086   case X86::VGATHERQPDZ128rm:
3087   case X86::VGATHERQPDZ256rm:
3088   case X86::VGATHERQPDZrm:
3089   case X86::VGATHERQPSZ128rm:
3090   case X86::VGATHERQPSZ256rm:
3091   case X86::VGATHERQPSZrm:
3092   case X86::VPGATHERDDZ128rm:
3093   case X86::VPGATHERDDZ256rm:
3094   case X86::VPGATHERDDZrm:
3095   case X86::VPGATHERDQZ128rm:
3096   case X86::VPGATHERDQZ256rm:
3097   case X86::VPGATHERDQZrm:
3098   case X86::VPGATHERQDZ128rm:
3099   case X86::VPGATHERQDZ256rm:
3100   case X86::VPGATHERQDZrm:
3101   case X86::VPGATHERQQZ128rm:
3102   case X86::VPGATHERQQZ256rm:
3103   case X86::VPGATHERQQZrm: {
3104     unsigned Dest = MRI->getEncodingValue(Inst.getOperand(0).getReg());
3105     unsigned Index =
3106       MRI->getEncodingValue(Inst.getOperand(4 + X86::AddrIndexReg).getReg());
3107     if (Dest == Index)
3108       return Warning(Ops[0]->getStartLoc(), "index and destination registers "
3109                                             "should be distinct");
3110     break;
3111   }
3112   case X86::V4FMADDPSrm:
3113   case X86::V4FMADDPSrmk:
3114   case X86::V4FMADDPSrmkz:
3115   case X86::V4FMADDSSrm:
3116   case X86::V4FMADDSSrmk:
3117   case X86::V4FMADDSSrmkz:
3118   case X86::V4FNMADDPSrm:
3119   case X86::V4FNMADDPSrmk:
3120   case X86::V4FNMADDPSrmkz:
3121   case X86::V4FNMADDSSrm:
3122   case X86::V4FNMADDSSrmk:
3123   case X86::V4FNMADDSSrmkz:
3124   case X86::VP4DPWSSDSrm:
3125   case X86::VP4DPWSSDSrmk:
3126   case X86::VP4DPWSSDSrmkz:
3127   case X86::VP4DPWSSDrm:
3128   case X86::VP4DPWSSDrmk:
3129   case X86::VP4DPWSSDrmkz: {
3130     unsigned Src2 = Inst.getOperand(Inst.getNumOperands() -
3131                                     X86::AddrNumOperands - 1).getReg();
3132     unsigned Src2Enc = MRI->getEncodingValue(Src2);
3133     if (Src2Enc % 4 != 0) {
3134       StringRef RegName = X86IntelInstPrinter::getRegisterName(Src2);
3135       unsigned GroupStart = (Src2Enc / 4) * 4;
3136       unsigned GroupEnd = GroupStart + 3;
3137       return Warning(Ops[0]->getStartLoc(),
3138                      "source register '" + RegName + "' implicitly denotes '" +
3139                      RegName.take_front(3) + Twine(GroupStart) + "' to '" +
3140                      RegName.take_front(3) + Twine(GroupEnd) +
3141                      "' source group");
3142     }
3143     break;
3144   }
3145   }
3146 
3147   return false;
3148 }
3149 
3150 static const char *getSubtargetFeatureName(uint64_t Val);
3151 
3152 void X86AsmParser::emitInstruction(MCInst &Inst, OperandVector &Operands,
3153                                    MCStreamer &Out) {
3154   Out.emitInstruction(Inst, getSTI());
3155 }
3156 
3157 bool X86AsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
3158                                            OperandVector &Operands,
3159                                            MCStreamer &Out, uint64_t &ErrorInfo,
3160                                            bool MatchingInlineAsm) {
3161   if (isParsingIntelSyntax())
3162     return MatchAndEmitIntelInstruction(IDLoc, Opcode, Operands, Out, ErrorInfo,
3163                                         MatchingInlineAsm);
3164   return MatchAndEmitATTInstruction(IDLoc, Opcode, Operands, Out, ErrorInfo,
3165                                     MatchingInlineAsm);
3166 }
3167 
3168 void X86AsmParser::MatchFPUWaitAlias(SMLoc IDLoc, X86Operand &Op,
3169                                      OperandVector &Operands, MCStreamer &Out,
3170                                      bool MatchingInlineAsm) {
3171   // FIXME: This should be replaced with a real .td file alias mechanism.
3172   // Also, MatchInstructionImpl should actually *do* the EmitInstruction
3173   // call.
3174   const char *Repl = StringSwitch<const char *>(Op.getToken())
3175                          .Case("finit", "fninit")
3176                          .Case("fsave", "fnsave")
3177                          .Case("fstcw", "fnstcw")
3178                          .Case("fstcww", "fnstcw")
3179                          .Case("fstenv", "fnstenv")
3180                          .Case("fstsw", "fnstsw")
3181                          .Case("fstsww", "fnstsw")
3182                          .Case("fclex", "fnclex")
3183                          .Default(nullptr);
3184   if (Repl) {
3185     MCInst Inst;
3186     Inst.setOpcode(X86::WAIT);
3187     Inst.setLoc(IDLoc);
3188     if (!MatchingInlineAsm)
3189       emitInstruction(Inst, Operands, Out);
3190     Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
3191   }
3192 }
3193 
3194 bool X86AsmParser::ErrorMissingFeature(SMLoc IDLoc,
3195                                        const FeatureBitset &MissingFeatures,
3196                                        bool MatchingInlineAsm) {
3197   assert(MissingFeatures.any() && "Unknown missing feature!");
3198   SmallString<126> Msg;
3199   raw_svector_ostream OS(Msg);
3200   OS << "instruction requires:";
3201   for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i) {
3202     if (MissingFeatures[i])
3203       OS << ' ' << getSubtargetFeatureName(i);
3204   }
3205   return Error(IDLoc, OS.str(), SMRange(), MatchingInlineAsm);
3206 }
3207 
3208 static unsigned getPrefixes(OperandVector &Operands) {
3209   unsigned Result = 0;
3210   X86Operand &Prefix = static_cast<X86Operand &>(*Operands.back());
3211   if (Prefix.isPrefix()) {
3212     Result = Prefix.getPrefix();
3213     Operands.pop_back();
3214   }
3215   return Result;
3216 }
3217 
3218 unsigned X86AsmParser::checkTargetMatchPredicate(MCInst &Inst) {
3219   unsigned Opc = Inst.getOpcode();
3220   const MCInstrDesc &MCID = MII.get(Opc);
3221 
3222   if (ForcedVEXEncoding == VEXEncoding_EVEX &&
3223       (MCID.TSFlags & X86II::EncodingMask) != X86II::EVEX)
3224     return Match_Unsupported;
3225 
3226   if ((ForcedVEXEncoding == VEXEncoding_VEX2 ||
3227        ForcedVEXEncoding == VEXEncoding_VEX3) &&
3228       (MCID.TSFlags & X86II::EncodingMask) != X86II::VEX)
3229     return Match_Unsupported;
3230 
3231   // These instructions match ambiguously with their VEX encoded counterparts
3232   // and appear first in the matching table. Reject them unless we're forcing
3233   // EVEX encoding.
3234   // FIXME: We really need a way to break the ambiguity.
3235   switch (Opc) {
3236   case X86::VCVTSD2SIZrm_Int:
3237   case X86::VCVTSD2SI64Zrm_Int:
3238   case X86::VCVTSS2SIZrm_Int:
3239   case X86::VCVTSS2SI64Zrm_Int:
3240   case X86::VCVTTSD2SIZrm:   case X86::VCVTTSD2SIZrm_Int:
3241   case X86::VCVTTSD2SI64Zrm: case X86::VCVTTSD2SI64Zrm_Int:
3242   case X86::VCVTTSS2SIZrm:   case X86::VCVTTSS2SIZrm_Int:
3243   case X86::VCVTTSS2SI64Zrm: case X86::VCVTTSS2SI64Zrm_Int:
3244     if (ForcedVEXEncoding != VEXEncoding_EVEX)
3245       return Match_Unsupported;
3246     break;
3247   }
3248 
3249   return Match_Success;
3250 }
3251 
3252 bool X86AsmParser::MatchAndEmitATTInstruction(SMLoc IDLoc, unsigned &Opcode,
3253                                               OperandVector &Operands,
3254                                               MCStreamer &Out,
3255                                               uint64_t &ErrorInfo,
3256                                               bool MatchingInlineAsm) {
3257   assert(!Operands.empty() && "Unexpect empty operand list!");
3258   assert((*Operands[0]).isToken() && "Leading operand should always be a mnemonic!");
3259   SMRange EmptyRange = None;
3260 
3261   // First, handle aliases that expand to multiple instructions.
3262   MatchFPUWaitAlias(IDLoc, static_cast<X86Operand &>(*Operands[0]), Operands,
3263                     Out, MatchingInlineAsm);
3264   X86Operand &Op = static_cast<X86Operand &>(*Operands[0]);
3265   unsigned Prefixes = getPrefixes(Operands);
3266 
3267   MCInst Inst;
3268 
3269   // If VEX3 encoding is forced, we need to pass the USE_VEX3 flag to the
3270   // encoder.
3271   if (ForcedVEXEncoding == VEXEncoding_VEX3)
3272     Prefixes |= X86::IP_USE_VEX3;
3273 
3274   if (Prefixes)
3275     Inst.setFlags(Prefixes);
3276 
3277   // First, try a direct match.
3278   FeatureBitset MissingFeatures;
3279   unsigned OriginalError = MatchInstruction(Operands, Inst, ErrorInfo,
3280                                             MissingFeatures, MatchingInlineAsm,
3281                                             isParsingIntelSyntax());
3282   switch (OriginalError) {
3283   default: llvm_unreachable("Unexpected match result!");
3284   case Match_Success:
3285     if (!MatchingInlineAsm && validateInstruction(Inst, Operands))
3286       return true;
3287     // Some instructions need post-processing to, for example, tweak which
3288     // encoding is selected. Loop on it while changes happen so the
3289     // individual transformations can chain off each other.
3290     if (!MatchingInlineAsm)
3291       while (processInstruction(Inst, Operands))
3292         ;
3293 
3294     Inst.setLoc(IDLoc);
3295     if (!MatchingInlineAsm)
3296       emitInstruction(Inst, Operands, Out);
3297     Opcode = Inst.getOpcode();
3298     return false;
3299   case Match_InvalidImmUnsignedi4: {
3300     SMLoc ErrorLoc = ((X86Operand &)*Operands[ErrorInfo]).getStartLoc();
3301     if (ErrorLoc == SMLoc())
3302       ErrorLoc = IDLoc;
3303     return Error(ErrorLoc, "immediate must be an integer in range [0, 15]",
3304                  EmptyRange, MatchingInlineAsm);
3305   }
3306   case Match_MissingFeature:
3307     return ErrorMissingFeature(IDLoc, MissingFeatures, MatchingInlineAsm);
3308   case Match_InvalidOperand:
3309   case Match_MnemonicFail:
3310   case Match_Unsupported:
3311     break;
3312   }
3313   if (Op.getToken().empty()) {
3314     Error(IDLoc, "instruction must have size higher than 0", EmptyRange,
3315           MatchingInlineAsm);
3316     return true;
3317   }
3318 
3319   // FIXME: Ideally, we would only attempt suffix matches for things which are
3320   // valid prefixes, and we could just infer the right unambiguous
3321   // type. However, that requires substantially more matcher support than the
3322   // following hack.
3323 
3324   // Change the operand to point to a temporary token.
3325   StringRef Base = Op.getToken();
3326   SmallString<16> Tmp;
3327   Tmp += Base;
3328   Tmp += ' ';
3329   Op.setTokenValue(Tmp);
3330 
3331   // If this instruction starts with an 'f', then it is a floating point stack
3332   // instruction.  These come in up to three forms for 32-bit, 64-bit, and
3333   // 80-bit floating point, which use the suffixes s,l,t respectively.
3334   //
3335   // Otherwise, we assume that this may be an integer instruction, which comes
3336   // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
3337   const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
3338 
3339   // Check for the various suffix matches.
3340   uint64_t ErrorInfoIgnore;
3341   FeatureBitset ErrorInfoMissingFeatures; // Init suppresses compiler warnings.
3342   unsigned Match[4];
3343 
3344   for (unsigned I = 0, E = array_lengthof(Match); I != E; ++I) {
3345     Tmp.back() = Suffixes[I];
3346     Match[I] = MatchInstruction(Operands, Inst, ErrorInfoIgnore,
3347                                 MissingFeatures, MatchingInlineAsm,
3348                                 isParsingIntelSyntax());
3349     // If this returned as a missing feature failure, remember that.
3350     if (Match[I] == Match_MissingFeature)
3351       ErrorInfoMissingFeatures = MissingFeatures;
3352   }
3353 
3354   // Restore the old token.
3355   Op.setTokenValue(Base);
3356 
3357   // If exactly one matched, then we treat that as a successful match (and the
3358   // instruction will already have been filled in correctly, since the failing
3359   // matches won't have modified it).
3360   unsigned NumSuccessfulMatches =
3361       std::count(std::begin(Match), std::end(Match), Match_Success);
3362   if (NumSuccessfulMatches == 1) {
3363     Inst.setLoc(IDLoc);
3364     if (!MatchingInlineAsm)
3365       emitInstruction(Inst, Operands, Out);
3366     Opcode = Inst.getOpcode();
3367     return false;
3368   }
3369 
3370   // Otherwise, the match failed, try to produce a decent error message.
3371 
3372   // If we had multiple suffix matches, then identify this as an ambiguous
3373   // match.
3374   if (NumSuccessfulMatches > 1) {
3375     char MatchChars[4];
3376     unsigned NumMatches = 0;
3377     for (unsigned I = 0, E = array_lengthof(Match); I != E; ++I)
3378       if (Match[I] == Match_Success)
3379         MatchChars[NumMatches++] = Suffixes[I];
3380 
3381     SmallString<126> Msg;
3382     raw_svector_ostream OS(Msg);
3383     OS << "ambiguous instructions require an explicit suffix (could be ";
3384     for (unsigned i = 0; i != NumMatches; ++i) {
3385       if (i != 0)
3386         OS << ", ";
3387       if (i + 1 == NumMatches)
3388         OS << "or ";
3389       OS << "'" << Base << MatchChars[i] << "'";
3390     }
3391     OS << ")";
3392     Error(IDLoc, OS.str(), EmptyRange, MatchingInlineAsm);
3393     return true;
3394   }
3395 
3396   // Okay, we know that none of the variants matched successfully.
3397 
3398   // If all of the instructions reported an invalid mnemonic, then the original
3399   // mnemonic was invalid.
3400   if (std::count(std::begin(Match), std::end(Match), Match_MnemonicFail) == 4) {
3401     if (OriginalError == Match_MnemonicFail)
3402       return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
3403                    Op.getLocRange(), MatchingInlineAsm);
3404 
3405     if (OriginalError == Match_Unsupported)
3406       return Error(IDLoc, "unsupported instruction", EmptyRange,
3407                    MatchingInlineAsm);
3408 
3409     assert(OriginalError == Match_InvalidOperand && "Unexpected error");
3410     // Recover location info for the operand if we know which was the problem.
3411     if (ErrorInfo != ~0ULL) {
3412       if (ErrorInfo >= Operands.size())
3413         return Error(IDLoc, "too few operands for instruction", EmptyRange,
3414                      MatchingInlineAsm);
3415 
3416       X86Operand &Operand = (X86Operand &)*Operands[ErrorInfo];
3417       if (Operand.getStartLoc().isValid()) {
3418         SMRange OperandRange = Operand.getLocRange();
3419         return Error(Operand.getStartLoc(), "invalid operand for instruction",
3420                      OperandRange, MatchingInlineAsm);
3421       }
3422     }
3423 
3424     return Error(IDLoc, "invalid operand for instruction", EmptyRange,
3425                  MatchingInlineAsm);
3426   }
3427 
3428   // If one instruction matched as unsupported, report this as unsupported.
3429   if (std::count(std::begin(Match), std::end(Match),
3430                  Match_Unsupported) == 1) {
3431     return Error(IDLoc, "unsupported instruction", EmptyRange,
3432                  MatchingInlineAsm);
3433   }
3434 
3435   // If one instruction matched with a missing feature, report this as a
3436   // missing feature.
3437   if (std::count(std::begin(Match), std::end(Match),
3438                  Match_MissingFeature) == 1) {
3439     ErrorInfo = Match_MissingFeature;
3440     return ErrorMissingFeature(IDLoc, ErrorInfoMissingFeatures,
3441                                MatchingInlineAsm);
3442   }
3443 
3444   // If one instruction matched with an invalid operand, report this as an
3445   // operand failure.
3446   if (std::count(std::begin(Match), std::end(Match),
3447                  Match_InvalidOperand) == 1) {
3448     return Error(IDLoc, "invalid operand for instruction", EmptyRange,
3449                  MatchingInlineAsm);
3450   }
3451 
3452   // If all of these were an outright failure, report it in a useless way.
3453   Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
3454         EmptyRange, MatchingInlineAsm);
3455   return true;
3456 }
3457 
3458 bool X86AsmParser::MatchAndEmitIntelInstruction(SMLoc IDLoc, unsigned &Opcode,
3459                                                 OperandVector &Operands,
3460                                                 MCStreamer &Out,
3461                                                 uint64_t &ErrorInfo,
3462                                                 bool MatchingInlineAsm) {
3463   assert(!Operands.empty() && "Unexpect empty operand list!");
3464   assert((*Operands[0]).isToken() && "Leading operand should always be a mnemonic!");
3465   StringRef Mnemonic = (static_cast<X86Operand &>(*Operands[0])).getToken();
3466   SMRange EmptyRange = None;
3467   StringRef Base = (static_cast<X86Operand &>(*Operands[0])).getToken();
3468   unsigned Prefixes = getPrefixes(Operands);
3469 
3470   // First, handle aliases that expand to multiple instructions.
3471   MatchFPUWaitAlias(IDLoc, static_cast<X86Operand &>(*Operands[0]), Operands, Out, MatchingInlineAsm);
3472   X86Operand &Op = static_cast<X86Operand &>(*Operands[0]);
3473 
3474   MCInst Inst;
3475 
3476   // If VEX3 encoding is forced, we need to pass the USE_VEX3 flag to the
3477   // encoder.
3478   if (ForcedVEXEncoding == VEXEncoding_VEX3)
3479     Prefixes |= X86::IP_USE_VEX3;
3480 
3481   if (Prefixes)
3482     Inst.setFlags(Prefixes);
3483 
3484   // Find one unsized memory operand, if present.
3485   X86Operand *UnsizedMemOp = nullptr;
3486   for (const auto &Op : Operands) {
3487     X86Operand *X86Op = static_cast<X86Operand *>(Op.get());
3488     if (X86Op->isMemUnsized()) {
3489       UnsizedMemOp = X86Op;
3490       // Have we found an unqualified memory operand,
3491       // break. IA allows only one memory operand.
3492       break;
3493     }
3494   }
3495 
3496   // Allow some instructions to have implicitly pointer-sized operands.  This is
3497   // compatible with gas.
3498   if (UnsizedMemOp) {
3499     static const char *const PtrSizedInstrs[] = {"call", "jmp", "push"};
3500     for (const char *Instr : PtrSizedInstrs) {
3501       if (Mnemonic == Instr) {
3502         UnsizedMemOp->Mem.Size = getPointerWidth();
3503         break;
3504       }
3505     }
3506   }
3507 
3508   SmallVector<unsigned, 8> Match;
3509   FeatureBitset ErrorInfoMissingFeatures;
3510   FeatureBitset MissingFeatures;
3511 
3512   // If unsized push has immediate operand we should default the default pointer
3513   // size for the size.
3514   if (Mnemonic == "push" && Operands.size() == 2) {
3515     auto *X86Op = static_cast<X86Operand *>(Operands[1].get());
3516     if (X86Op->isImm()) {
3517       // If it's not a constant fall through and let remainder take care of it.
3518       const auto *CE = dyn_cast<MCConstantExpr>(X86Op->getImm());
3519       unsigned Size = getPointerWidth();
3520       if (CE &&
3521           (isIntN(Size, CE->getValue()) || isUIntN(Size, CE->getValue()))) {
3522         SmallString<16> Tmp;
3523         Tmp += Base;
3524         Tmp += (is64BitMode())
3525                    ? "q"
3526                    : (is32BitMode()) ? "l" : (is16BitMode()) ? "w" : " ";
3527         Op.setTokenValue(Tmp);
3528         // Do match in ATT mode to allow explicit suffix usage.
3529         Match.push_back(MatchInstruction(Operands, Inst, ErrorInfo,
3530                                          MissingFeatures, MatchingInlineAsm,
3531                                          false /*isParsingIntelSyntax()*/));
3532         Op.setTokenValue(Base);
3533       }
3534     }
3535   }
3536 
3537   // If an unsized memory operand is present, try to match with each memory
3538   // operand size.  In Intel assembly, the size is not part of the instruction
3539   // mnemonic.
3540   if (UnsizedMemOp && UnsizedMemOp->isMemUnsized()) {
3541     static const unsigned MopSizes[] = {8, 16, 32, 64, 80, 128, 256, 512};
3542     for (unsigned Size : MopSizes) {
3543       UnsizedMemOp->Mem.Size = Size;
3544       uint64_t ErrorInfoIgnore;
3545       unsigned LastOpcode = Inst.getOpcode();
3546       unsigned M = MatchInstruction(Operands, Inst, ErrorInfoIgnore,
3547                                     MissingFeatures, MatchingInlineAsm,
3548                                     isParsingIntelSyntax());
3549       if (Match.empty() || LastOpcode != Inst.getOpcode())
3550         Match.push_back(M);
3551 
3552       // If this returned as a missing feature failure, remember that.
3553       if (Match.back() == Match_MissingFeature)
3554         ErrorInfoMissingFeatures = MissingFeatures;
3555     }
3556 
3557     // Restore the size of the unsized memory operand if we modified it.
3558     UnsizedMemOp->Mem.Size = 0;
3559   }
3560 
3561   // If we haven't matched anything yet, this is not a basic integer or FPU
3562   // operation.  There shouldn't be any ambiguity in our mnemonic table, so try
3563   // matching with the unsized operand.
3564   if (Match.empty()) {
3565     Match.push_back(MatchInstruction(
3566         Operands, Inst, ErrorInfo, MissingFeatures, MatchingInlineAsm,
3567         isParsingIntelSyntax()));
3568     // If this returned as a missing feature failure, remember that.
3569     if (Match.back() == Match_MissingFeature)
3570       ErrorInfoMissingFeatures = MissingFeatures;
3571   }
3572 
3573   // Restore the size of the unsized memory operand if we modified it.
3574   if (UnsizedMemOp)
3575     UnsizedMemOp->Mem.Size = 0;
3576 
3577   // If it's a bad mnemonic, all results will be the same.
3578   if (Match.back() == Match_MnemonicFail) {
3579     return Error(IDLoc, "invalid instruction mnemonic '" + Mnemonic + "'",
3580                  Op.getLocRange(), MatchingInlineAsm);
3581   }
3582 
3583   unsigned NumSuccessfulMatches =
3584       std::count(std::begin(Match), std::end(Match), Match_Success);
3585 
3586   // If matching was ambiguous and we had size information from the frontend,
3587   // try again with that. This handles cases like "movxz eax, m8/m16".
3588   if (UnsizedMemOp && NumSuccessfulMatches > 1 &&
3589       UnsizedMemOp->getMemFrontendSize()) {
3590     UnsizedMemOp->Mem.Size = UnsizedMemOp->getMemFrontendSize();
3591     unsigned M = MatchInstruction(
3592         Operands, Inst, ErrorInfo, MissingFeatures, MatchingInlineAsm,
3593         isParsingIntelSyntax());
3594     if (M == Match_Success)
3595       NumSuccessfulMatches = 1;
3596 
3597     // Add a rewrite that encodes the size information we used from the
3598     // frontend.
3599     InstInfo->AsmRewrites->emplace_back(
3600         AOK_SizeDirective, UnsizedMemOp->getStartLoc(),
3601         /*Len=*/0, UnsizedMemOp->getMemFrontendSize());
3602   }
3603 
3604   // If exactly one matched, then we treat that as a successful match (and the
3605   // instruction will already have been filled in correctly, since the failing
3606   // matches won't have modified it).
3607   if (NumSuccessfulMatches == 1) {
3608     if (!MatchingInlineAsm && validateInstruction(Inst, Operands))
3609       return true;
3610     // Some instructions need post-processing to, for example, tweak which
3611     // encoding is selected. Loop on it while changes happen so the individual
3612     // transformations can chain off each other.
3613     if (!MatchingInlineAsm)
3614       while (processInstruction(Inst, Operands))
3615         ;
3616     Inst.setLoc(IDLoc);
3617     if (!MatchingInlineAsm)
3618       emitInstruction(Inst, Operands, Out);
3619     Opcode = Inst.getOpcode();
3620     return false;
3621   } else if (NumSuccessfulMatches > 1) {
3622     assert(UnsizedMemOp &&
3623            "multiple matches only possible with unsized memory operands");
3624     return Error(UnsizedMemOp->getStartLoc(),
3625                  "ambiguous operand size for instruction '" + Mnemonic + "\'",
3626                  UnsizedMemOp->getLocRange());
3627   }
3628 
3629   // If one instruction matched as unsupported, report this as unsupported.
3630   if (std::count(std::begin(Match), std::end(Match),
3631                  Match_Unsupported) == 1) {
3632     return Error(IDLoc, "unsupported instruction", EmptyRange,
3633                  MatchingInlineAsm);
3634   }
3635 
3636   // If one instruction matched with a missing feature, report this as a
3637   // missing feature.
3638   if (std::count(std::begin(Match), std::end(Match),
3639                  Match_MissingFeature) == 1) {
3640     ErrorInfo = Match_MissingFeature;
3641     return ErrorMissingFeature(IDLoc, ErrorInfoMissingFeatures,
3642                                MatchingInlineAsm);
3643   }
3644 
3645   // If one instruction matched with an invalid operand, report this as an
3646   // operand failure.
3647   if (std::count(std::begin(Match), std::end(Match),
3648                  Match_InvalidOperand) == 1) {
3649     return Error(IDLoc, "invalid operand for instruction", EmptyRange,
3650                  MatchingInlineAsm);
3651   }
3652 
3653   if (std::count(std::begin(Match), std::end(Match),
3654                  Match_InvalidImmUnsignedi4) == 1) {
3655     SMLoc ErrorLoc = ((X86Operand &)*Operands[ErrorInfo]).getStartLoc();
3656     if (ErrorLoc == SMLoc())
3657       ErrorLoc = IDLoc;
3658     return Error(ErrorLoc, "immediate must be an integer in range [0, 15]",
3659                  EmptyRange, MatchingInlineAsm);
3660   }
3661 
3662   // If all of these were an outright failure, report it in a useless way.
3663   return Error(IDLoc, "unknown instruction mnemonic", EmptyRange,
3664                MatchingInlineAsm);
3665 }
3666 
3667 bool X86AsmParser::OmitRegisterFromClobberLists(unsigned RegNo) {
3668   return X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains(RegNo);
3669 }
3670 
3671 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
3672   MCAsmParser &Parser = getParser();
3673   StringRef IDVal = DirectiveID.getIdentifier();
3674   if (IDVal.startswith(".code"))
3675     return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
3676   else if (IDVal.startswith(".att_syntax")) {
3677     if (getLexer().isNot(AsmToken::EndOfStatement)) {
3678       if (Parser.getTok().getString() == "prefix")
3679         Parser.Lex();
3680       else if (Parser.getTok().getString() == "noprefix")
3681         return Error(DirectiveID.getLoc(), "'.att_syntax noprefix' is not "
3682                                            "supported: registers must have a "
3683                                            "'%' prefix in .att_syntax");
3684     }
3685     getParser().setAssemblerDialect(0);
3686     return false;
3687   } else if (IDVal.startswith(".intel_syntax")) {
3688     getParser().setAssemblerDialect(1);
3689     if (getLexer().isNot(AsmToken::EndOfStatement)) {
3690       if (Parser.getTok().getString() == "noprefix")
3691         Parser.Lex();
3692       else if (Parser.getTok().getString() == "prefix")
3693         return Error(DirectiveID.getLoc(), "'.intel_syntax prefix' is not "
3694                                            "supported: registers must not have "
3695                                            "a '%' prefix in .intel_syntax");
3696     }
3697     return false;
3698   } else if (IDVal == ".even")
3699     return parseDirectiveEven(DirectiveID.getLoc());
3700   else if (IDVal == ".cv_fpo_proc")
3701     return parseDirectiveFPOProc(DirectiveID.getLoc());
3702   else if (IDVal == ".cv_fpo_setframe")
3703     return parseDirectiveFPOSetFrame(DirectiveID.getLoc());
3704   else if (IDVal == ".cv_fpo_pushreg")
3705     return parseDirectiveFPOPushReg(DirectiveID.getLoc());
3706   else if (IDVal == ".cv_fpo_stackalloc")
3707     return parseDirectiveFPOStackAlloc(DirectiveID.getLoc());
3708   else if (IDVal == ".cv_fpo_stackalign")
3709     return parseDirectiveFPOStackAlign(DirectiveID.getLoc());
3710   else if (IDVal == ".cv_fpo_endprologue")
3711     return parseDirectiveFPOEndPrologue(DirectiveID.getLoc());
3712   else if (IDVal == ".cv_fpo_endproc")
3713     return parseDirectiveFPOEndProc(DirectiveID.getLoc());
3714   else if (IDVal == ".seh_pushreg")
3715     return parseDirectiveSEHPushReg(DirectiveID.getLoc());
3716   else if (IDVal == ".seh_setframe")
3717     return parseDirectiveSEHSetFrame(DirectiveID.getLoc());
3718   else if (IDVal == ".seh_savereg")
3719     return parseDirectiveSEHSaveReg(DirectiveID.getLoc());
3720   else if (IDVal == ".seh_savexmm")
3721     return parseDirectiveSEHSaveXMM(DirectiveID.getLoc());
3722   else if (IDVal == ".seh_pushframe")
3723     return parseDirectiveSEHPushFrame(DirectiveID.getLoc());
3724 
3725   return true;
3726 }
3727 
3728 /// parseDirectiveEven
3729 ///  ::= .even
3730 bool X86AsmParser::parseDirectiveEven(SMLoc L) {
3731   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
3732     return false;
3733 
3734   const MCSection *Section = getStreamer().getCurrentSectionOnly();
3735   if (!Section) {
3736     getStreamer().InitSections(false);
3737     Section = getStreamer().getCurrentSectionOnly();
3738   }
3739   if (Section->UseCodeAlign())
3740     getStreamer().emitCodeAlignment(2, 0);
3741   else
3742     getStreamer().emitValueToAlignment(2, 0, 1, 0);
3743   return false;
3744 }
3745 
3746 /// ParseDirectiveCode
3747 ///  ::= .code16 | .code32 | .code64
3748 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
3749   MCAsmParser &Parser = getParser();
3750   Code16GCC = false;
3751   if (IDVal == ".code16") {
3752     Parser.Lex();
3753     if (!is16BitMode()) {
3754       SwitchMode(X86::Mode16Bit);
3755       getParser().getStreamer().emitAssemblerFlag(MCAF_Code16);
3756     }
3757   } else if (IDVal == ".code16gcc") {
3758     // .code16gcc parses as if in 32-bit mode, but emits code in 16-bit mode.
3759     Parser.Lex();
3760     Code16GCC = true;
3761     if (!is16BitMode()) {
3762       SwitchMode(X86::Mode16Bit);
3763       getParser().getStreamer().emitAssemblerFlag(MCAF_Code16);
3764     }
3765   } else if (IDVal == ".code32") {
3766     Parser.Lex();
3767     if (!is32BitMode()) {
3768       SwitchMode(X86::Mode32Bit);
3769       getParser().getStreamer().emitAssemblerFlag(MCAF_Code32);
3770     }
3771   } else if (IDVal == ".code64") {
3772     Parser.Lex();
3773     if (!is64BitMode()) {
3774       SwitchMode(X86::Mode64Bit);
3775       getParser().getStreamer().emitAssemblerFlag(MCAF_Code64);
3776     }
3777   } else {
3778     Error(L, "unknown directive " + IDVal);
3779     return false;
3780   }
3781 
3782   return false;
3783 }
3784 
3785 // .cv_fpo_proc foo
3786 bool X86AsmParser::parseDirectiveFPOProc(SMLoc L) {
3787   MCAsmParser &Parser = getParser();
3788   StringRef ProcName;
3789   int64_t ParamsSize;
3790   if (Parser.parseIdentifier(ProcName))
3791     return Parser.TokError("expected symbol name");
3792   if (Parser.parseIntToken(ParamsSize, "expected parameter byte count"))
3793     return true;
3794   if (!isUIntN(32, ParamsSize))
3795     return Parser.TokError("parameters size out of range");
3796   if (Parser.parseEOL("unexpected tokens"))
3797     return addErrorSuffix(" in '.cv_fpo_proc' directive");
3798   MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
3799   return getTargetStreamer().emitFPOProc(ProcSym, ParamsSize, L);
3800 }
3801 
3802 // .cv_fpo_setframe ebp
3803 bool X86AsmParser::parseDirectiveFPOSetFrame(SMLoc L) {
3804   MCAsmParser &Parser = getParser();
3805   unsigned Reg;
3806   SMLoc DummyLoc;
3807   if (ParseRegister(Reg, DummyLoc, DummyLoc) ||
3808       Parser.parseEOL("unexpected tokens"))
3809     return addErrorSuffix(" in '.cv_fpo_setframe' directive");
3810   return getTargetStreamer().emitFPOSetFrame(Reg, L);
3811 }
3812 
3813 // .cv_fpo_pushreg ebx
3814 bool X86AsmParser::parseDirectiveFPOPushReg(SMLoc L) {
3815   MCAsmParser &Parser = getParser();
3816   unsigned Reg;
3817   SMLoc DummyLoc;
3818   if (ParseRegister(Reg, DummyLoc, DummyLoc) ||
3819       Parser.parseEOL("unexpected tokens"))
3820     return addErrorSuffix(" in '.cv_fpo_pushreg' directive");
3821   return getTargetStreamer().emitFPOPushReg(Reg, L);
3822 }
3823 
3824 // .cv_fpo_stackalloc 20
3825 bool X86AsmParser::parseDirectiveFPOStackAlloc(SMLoc L) {
3826   MCAsmParser &Parser = getParser();
3827   int64_t Offset;
3828   if (Parser.parseIntToken(Offset, "expected offset") ||
3829       Parser.parseEOL("unexpected tokens"))
3830     return addErrorSuffix(" in '.cv_fpo_stackalloc' directive");
3831   return getTargetStreamer().emitFPOStackAlloc(Offset, L);
3832 }
3833 
3834 // .cv_fpo_stackalign 8
3835 bool X86AsmParser::parseDirectiveFPOStackAlign(SMLoc L) {
3836   MCAsmParser &Parser = getParser();
3837   int64_t Offset;
3838   if (Parser.parseIntToken(Offset, "expected offset") ||
3839       Parser.parseEOL("unexpected tokens"))
3840     return addErrorSuffix(" in '.cv_fpo_stackalign' directive");
3841   return getTargetStreamer().emitFPOStackAlign(Offset, L);
3842 }
3843 
3844 // .cv_fpo_endprologue
3845 bool X86AsmParser::parseDirectiveFPOEndPrologue(SMLoc L) {
3846   MCAsmParser &Parser = getParser();
3847   if (Parser.parseEOL("unexpected tokens"))
3848     return addErrorSuffix(" in '.cv_fpo_endprologue' directive");
3849   return getTargetStreamer().emitFPOEndPrologue(L);
3850 }
3851 
3852 // .cv_fpo_endproc
3853 bool X86AsmParser::parseDirectiveFPOEndProc(SMLoc L) {
3854   MCAsmParser &Parser = getParser();
3855   if (Parser.parseEOL("unexpected tokens"))
3856     return addErrorSuffix(" in '.cv_fpo_endproc' directive");
3857   return getTargetStreamer().emitFPOEndProc(L);
3858 }
3859 
3860 bool X86AsmParser::parseSEHRegisterNumber(unsigned RegClassID,
3861                                           unsigned &RegNo) {
3862   SMLoc startLoc = getLexer().getLoc();
3863   const MCRegisterInfo *MRI = getContext().getRegisterInfo();
3864 
3865   // Try parsing the argument as a register first.
3866   if (getLexer().getTok().isNot(AsmToken::Integer)) {
3867     SMLoc endLoc;
3868     if (ParseRegister(RegNo, startLoc, endLoc))
3869       return true;
3870 
3871     if (!X86MCRegisterClasses[RegClassID].contains(RegNo)) {
3872       return Error(startLoc,
3873                    "register is not supported for use with this directive");
3874     }
3875   } else {
3876     // Otherwise, an integer number matching the encoding of the desired
3877     // register may appear.
3878     int64_t EncodedReg;
3879     if (getParser().parseAbsoluteExpression(EncodedReg))
3880       return true;
3881 
3882     // The SEH register number is the same as the encoding register number. Map
3883     // from the encoding back to the LLVM register number.
3884     RegNo = 0;
3885     for (MCPhysReg Reg : X86MCRegisterClasses[RegClassID]) {
3886       if (MRI->getEncodingValue(Reg) == EncodedReg) {
3887         RegNo = Reg;
3888         break;
3889       }
3890     }
3891     if (RegNo == 0) {
3892       return Error(startLoc,
3893                    "incorrect register number for use with this directive");
3894     }
3895   }
3896 
3897   return false;
3898 }
3899 
3900 bool X86AsmParser::parseDirectiveSEHPushReg(SMLoc Loc) {
3901   unsigned Reg = 0;
3902   if (parseSEHRegisterNumber(X86::GR64RegClassID, Reg))
3903     return true;
3904 
3905   if (getLexer().isNot(AsmToken::EndOfStatement))
3906     return TokError("unexpected token in directive");
3907 
3908   getParser().Lex();
3909   getStreamer().EmitWinCFIPushReg(Reg, Loc);
3910   return false;
3911 }
3912 
3913 bool X86AsmParser::parseDirectiveSEHSetFrame(SMLoc Loc) {
3914   unsigned Reg = 0;
3915   int64_t Off;
3916   if (parseSEHRegisterNumber(X86::GR64RegClassID, Reg))
3917     return true;
3918   if (getLexer().isNot(AsmToken::Comma))
3919     return TokError("you must specify a stack pointer offset");
3920 
3921   getParser().Lex();
3922   if (getParser().parseAbsoluteExpression(Off))
3923     return true;
3924 
3925   if (getLexer().isNot(AsmToken::EndOfStatement))
3926     return TokError("unexpected token in directive");
3927 
3928   getParser().Lex();
3929   getStreamer().EmitWinCFISetFrame(Reg, Off, Loc);
3930   return false;
3931 }
3932 
3933 bool X86AsmParser::parseDirectiveSEHSaveReg(SMLoc Loc) {
3934   unsigned Reg = 0;
3935   int64_t Off;
3936   if (parseSEHRegisterNumber(X86::GR64RegClassID, Reg))
3937     return true;
3938   if (getLexer().isNot(AsmToken::Comma))
3939     return TokError("you must specify an offset on the stack");
3940 
3941   getParser().Lex();
3942   if (getParser().parseAbsoluteExpression(Off))
3943     return true;
3944 
3945   if (getLexer().isNot(AsmToken::EndOfStatement))
3946     return TokError("unexpected token in directive");
3947 
3948   getParser().Lex();
3949   getStreamer().EmitWinCFISaveReg(Reg, Off, Loc);
3950   return false;
3951 }
3952 
3953 bool X86AsmParser::parseDirectiveSEHSaveXMM(SMLoc Loc) {
3954   unsigned Reg = 0;
3955   int64_t Off;
3956   if (parseSEHRegisterNumber(X86::VR128XRegClassID, Reg))
3957     return true;
3958   if (getLexer().isNot(AsmToken::Comma))
3959     return TokError("you must specify an offset on the stack");
3960 
3961   getParser().Lex();
3962   if (getParser().parseAbsoluteExpression(Off))
3963     return true;
3964 
3965   if (getLexer().isNot(AsmToken::EndOfStatement))
3966     return TokError("unexpected token in directive");
3967 
3968   getParser().Lex();
3969   getStreamer().EmitWinCFISaveXMM(Reg, Off, Loc);
3970   return false;
3971 }
3972 
3973 bool X86AsmParser::parseDirectiveSEHPushFrame(SMLoc Loc) {
3974   bool Code = false;
3975   StringRef CodeID;
3976   if (getLexer().is(AsmToken::At)) {
3977     SMLoc startLoc = getLexer().getLoc();
3978     getParser().Lex();
3979     if (!getParser().parseIdentifier(CodeID)) {
3980       if (CodeID != "code")
3981         return Error(startLoc, "expected @code");
3982       Code = true;
3983     }
3984   }
3985 
3986   if (getLexer().isNot(AsmToken::EndOfStatement))
3987     return TokError("unexpected token in directive");
3988 
3989   getParser().Lex();
3990   getStreamer().EmitWinCFIPushFrame(Code, Loc);
3991   return false;
3992 }
3993 
3994 // Force static initialization.
3995 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeX86AsmParser() {
3996   RegisterMCAsmParser<X86AsmParser> X(getTheX86_32Target());
3997   RegisterMCAsmParser<X86AsmParser> Y(getTheX86_64Target());
3998 }
3999 
4000 #define GET_REGISTER_MATCHER
4001 #define GET_MATCHER_IMPLEMENTATION
4002 #define GET_SUBTARGET_FEATURE_NAME
4003 #include "X86GenAsmMatcher.inc"
4004