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