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