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