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