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