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