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