1 //===-- AMDGPUAsmParser.cpp - Parse SI asm to MCInst instructions ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "AMDKernelCodeT.h"
11 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
12 #include "MCTargetDesc/AMDGPUTargetStreamer.h"
13 #include "SIDefines.h"
14 #include "Utils/AMDGPUAsmUtils.h"
15 #include "Utils/AMDGPUBaseInfo.h"
16 #include "Utils/AMDKernelCodeTUtils.h"
17 #include "llvm/ADT/APFloat.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/BinaryFormat/ELF.h"
27 #include "llvm/CodeGen/MachineValueType.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCInstrDesc.h"
33 #include "llvm/MC/MCInstrInfo.h"
34 #include "llvm/MC/MCParser/MCAsmLexer.h"
35 #include "llvm/MC/MCParser/MCAsmParser.h"
36 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
37 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
38 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
39 #include "llvm/MC/MCRegisterInfo.h"
40 #include "llvm/MC/MCStreamer.h"
41 #include "llvm/MC/MCSubtargetInfo.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/SMLoc.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/raw_ostream.h"
59 using namespace llvm::AMDGPU;
63 class AMDGPUAsmParser;
65 enum RegisterKind { IS_UNKNOWN, IS_VGPR, IS_SGPR, IS_TTMP, IS_SPECIAL };
67 //===----------------------------------------------------------------------===//
69 //===----------------------------------------------------------------------===//
71 class AMDGPUOperand : public MCParsedAsmOperand {
79 SMLoc StartLoc, EndLoc;
80 const AMDGPUAsmParser *AsmParser;
83 AMDGPUOperand(KindTy Kind_, const AMDGPUAsmParser *AsmParser_)
84 : MCParsedAsmOperand(), Kind(Kind_), AsmParser(AsmParser_) {}
86 typedef std::unique_ptr<AMDGPUOperand> Ptr;
93 bool hasFPModifiers() const { return Abs || Neg; }
94 bool hasIntModifiers() const { return Sext; }
95 bool hasModifiers() const { return hasFPModifiers() || hasIntModifiers(); }
97 int64_t getFPModifiersOperand() const {
99 Operand |= Abs ? SISrcMods::ABS : 0;
100 Operand |= Neg ? SISrcMods::NEG : 0;
104 int64_t getIntModifiersOperand() const {
106 Operand |= Sext ? SISrcMods::SEXT : 0;
110 int64_t getModifiersOperand() const {
111 assert(!(hasFPModifiers() && hasIntModifiers())
112 && "fp and int modifiers should not be used simultaneously");
113 if (hasFPModifiers()) {
114 return getFPModifiersOperand();
115 } else if (hasIntModifiers()) {
116 return getIntModifiersOperand();
122 friend raw_ostream &operator <<(raw_ostream &OS, AMDGPUOperand::Modifiers Mods);
195 bool isToken() const override {
199 if (Kind != Expression || !Expr)
202 // When parsing operands, we can't always tell if something was meant to be
203 // a token, like 'gds', or an expression that references a global variable.
204 // In this case, we assume the string is an expression, and if we need to
205 // interpret is a token, then we treat the symbol name as the token.
206 return isa<MCSymbolRefExpr>(Expr);
209 bool isImm() const override {
210 return Kind == Immediate;
213 bool isInlinableImm(MVT type) const;
214 bool isLiteralImm(MVT type) const;
216 bool isRegKind() const {
217 return Kind == Register;
220 bool isReg() const override {
221 return isRegKind() && !hasModifiers();
224 bool isRegOrImmWithInputMods(MVT type) const {
225 return isRegKind() || isInlinableImm(type);
228 bool isRegOrImmWithInt16InputMods() const {
229 return isRegOrImmWithInputMods(MVT::i16);
232 bool isRegOrImmWithInt32InputMods() const {
233 return isRegOrImmWithInputMods(MVT::i32);
236 bool isRegOrImmWithInt64InputMods() const {
237 return isRegOrImmWithInputMods(MVT::i64);
240 bool isRegOrImmWithFP16InputMods() const {
241 return isRegOrImmWithInputMods(MVT::f16);
244 bool isRegOrImmWithFP32InputMods() const {
245 return isRegOrImmWithInputMods(MVT::f32);
248 bool isRegOrImmWithFP64InputMods() const {
249 return isRegOrImmWithInputMods(MVT::f64);
252 bool isVReg() const {
253 return isRegClass(AMDGPU::VGPR_32RegClassID) ||
254 isRegClass(AMDGPU::VReg_64RegClassID) ||
255 isRegClass(AMDGPU::VReg_96RegClassID) ||
256 isRegClass(AMDGPU::VReg_128RegClassID) ||
257 isRegClass(AMDGPU::VReg_256RegClassID) ||
258 isRegClass(AMDGPU::VReg_512RegClassID);
261 bool isVReg32OrOff() const {
262 return isOff() || isRegClass(AMDGPU::VGPR_32RegClassID);
265 bool isSDWARegKind() const;
267 bool isImmTy(ImmTy ImmT) const {
268 return isImm() && Imm.Type == ImmT;
271 bool isImmModifier() const {
272 return isImm() && Imm.Type != ImmTyNone;
275 bool isClampSI() const { return isImmTy(ImmTyClampSI); }
276 bool isOModSI() const { return isImmTy(ImmTyOModSI); }
277 bool isDMask() const { return isImmTy(ImmTyDMask); }
278 bool isUNorm() const { return isImmTy(ImmTyUNorm); }
279 bool isDA() const { return isImmTy(ImmTyDA); }
280 bool isR128() const { return isImmTy(ImmTyUNorm); }
281 bool isLWE() const { return isImmTy(ImmTyLWE); }
282 bool isOff() const { return isImmTy(ImmTyOff); }
283 bool isExpTgt() const { return isImmTy(ImmTyExpTgt); }
284 bool isExpVM() const { return isImmTy(ImmTyExpVM); }
285 bool isExpCompr() const { return isImmTy(ImmTyExpCompr); }
286 bool isOffen() const { return isImmTy(ImmTyOffen); }
287 bool isIdxen() const { return isImmTy(ImmTyIdxen); }
288 bool isAddr64() const { return isImmTy(ImmTyAddr64); }
289 bool isOffset() const { return isImmTy(ImmTyOffset) && isUInt<16>(getImm()); }
290 bool isOffset0() const { return isImmTy(ImmTyOffset0) && isUInt<16>(getImm()); }
291 bool isOffset1() const { return isImmTy(ImmTyOffset1) && isUInt<8>(getImm()); }
293 bool isOffsetU12() const { return isImmTy(ImmTyOffset) && isUInt<12>(getImm()); }
294 bool isOffsetS13() const { return isImmTy(ImmTyOffset) && isInt<13>(getImm()); }
295 bool isGDS() const { return isImmTy(ImmTyGDS); }
296 bool isGLC() const { return isImmTy(ImmTyGLC); }
297 bool isSLC() const { return isImmTy(ImmTySLC); }
298 bool isTFE() const { return isImmTy(ImmTyTFE); }
299 bool isDFMT() const { return isImmTy(ImmTyDFMT) && isUInt<8>(getImm()); }
300 bool isNFMT() const { return isImmTy(ImmTyNFMT) && isUInt<8>(getImm()); }
301 bool isBankMask() const { return isImmTy(ImmTyDppBankMask); }
302 bool isRowMask() const { return isImmTy(ImmTyDppRowMask); }
303 bool isBoundCtrl() const { return isImmTy(ImmTyDppBoundCtrl); }
304 bool isSDWADstSel() const { return isImmTy(ImmTySdwaDstSel); }
305 bool isSDWASrc0Sel() const { return isImmTy(ImmTySdwaSrc0Sel); }
306 bool isSDWASrc1Sel() const { return isImmTy(ImmTySdwaSrc1Sel); }
307 bool isSDWADstUnused() const { return isImmTy(ImmTySdwaDstUnused); }
308 bool isInterpSlot() const { return isImmTy(ImmTyInterpSlot); }
309 bool isInterpAttr() const { return isImmTy(ImmTyInterpAttr); }
310 bool isAttrChan() const { return isImmTy(ImmTyAttrChan); }
311 bool isOpSel() const { return isImmTy(ImmTyOpSel); }
312 bool isOpSelHi() const { return isImmTy(ImmTyOpSelHi); }
313 bool isNegLo() const { return isImmTy(ImmTyNegLo); }
314 bool isNegHi() const { return isImmTy(ImmTyNegHi); }
317 return isClampSI() || isOModSI();
320 bool isRegOrImm() const {
321 return isReg() || isImm();
324 bool isRegClass(unsigned RCID) const;
326 bool isRegOrInlineNoMods(unsigned RCID, MVT type) const {
327 return (isRegClass(RCID) || isInlinableImm(type)) && !hasModifiers();
330 bool isSCSrcB16() const {
331 return isRegOrInlineNoMods(AMDGPU::SReg_32RegClassID, MVT::i16);
334 bool isSCSrcV2B16() const {
338 bool isSCSrcB32() const {
339 return isRegOrInlineNoMods(AMDGPU::SReg_32RegClassID, MVT::i32);
342 bool isSCSrcB64() const {
343 return isRegOrInlineNoMods(AMDGPU::SReg_64RegClassID, MVT::i64);
346 bool isSCSrcF16() const {
347 return isRegOrInlineNoMods(AMDGPU::SReg_32RegClassID, MVT::f16);
350 bool isSCSrcV2F16() const {
354 bool isSCSrcF32() const {
355 return isRegOrInlineNoMods(AMDGPU::SReg_32RegClassID, MVT::f32);
358 bool isSCSrcF64() const {
359 return isRegOrInlineNoMods(AMDGPU::SReg_64RegClassID, MVT::f64);
362 bool isSSrcB32() const {
363 return isSCSrcB32() || isLiteralImm(MVT::i32) || isExpr();
366 bool isSSrcB16() const {
367 return isSCSrcB16() || isLiteralImm(MVT::i16);
370 bool isSSrcV2B16() const {
371 llvm_unreachable("cannot happen");
375 bool isSSrcB64() const {
376 // TODO: Find out how SALU supports extension of 32-bit literals to 64 bits.
378 return isSCSrcB64() || isLiteralImm(MVT::i64);
381 bool isSSrcF32() const {
382 return isSCSrcB32() || isLiteralImm(MVT::f32) || isExpr();
385 bool isSSrcF64() const {
386 return isSCSrcB64() || isLiteralImm(MVT::f64);
389 bool isSSrcF16() const {
390 return isSCSrcB16() || isLiteralImm(MVT::f16);
393 bool isSSrcV2F16() const {
394 llvm_unreachable("cannot happen");
398 bool isVCSrcB32() const {
399 return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::i32);
402 bool isVCSrcB64() const {
403 return isRegOrInlineNoMods(AMDGPU::VS_64RegClassID, MVT::i64);
406 bool isVCSrcB16() const {
407 return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::i16);
410 bool isVCSrcV2B16() const {
414 bool isVCSrcF32() const {
415 return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::f32);
418 bool isVCSrcF64() const {
419 return isRegOrInlineNoMods(AMDGPU::VS_64RegClassID, MVT::f64);
422 bool isVCSrcF16() const {
423 return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::f16);
426 bool isVCSrcV2F16() const {
430 bool isVSrcB32() const {
431 return isVCSrcF32() || isLiteralImm(MVT::i32);
434 bool isVSrcB64() const {
435 return isVCSrcF64() || isLiteralImm(MVT::i64);
438 bool isVSrcB16() const {
439 return isVCSrcF16() || isLiteralImm(MVT::i16);
442 bool isVSrcV2B16() const {
443 llvm_unreachable("cannot happen");
447 bool isVSrcF32() const {
448 return isVCSrcF32() || isLiteralImm(MVT::f32);
451 bool isVSrcF64() const {
452 return isVCSrcF64() || isLiteralImm(MVT::f64);
455 bool isVSrcF16() const {
456 return isVCSrcF16() || isLiteralImm(MVT::f16);
459 bool isVSrcV2F16() const {
460 llvm_unreachable("cannot happen");
464 bool isKImmFP32() const {
465 return isLiteralImm(MVT::f32);
468 bool isKImmFP16() const {
469 return isLiteralImm(MVT::f16);
472 bool isMem() const override {
476 bool isExpr() const {
477 return Kind == Expression;
480 bool isSoppBrTarget() const {
481 return isExpr() || isImm();
484 bool isSWaitCnt() const;
485 bool isHwreg() const;
486 bool isSendMsg() const;
487 bool isSwizzle() const;
488 bool isSMRDOffset8() const;
489 bool isSMRDOffset20() const;
490 bool isSMRDLiteralOffset() const;
491 bool isDPPCtrl() const;
492 bool isGPRIdxMode() const;
493 bool isS16Imm() const;
494 bool isU16Imm() const;
496 StringRef getExpressionAsToken() const {
498 const MCSymbolRefExpr *S = cast<MCSymbolRefExpr>(Expr);
499 return S->getSymbol().getName();
502 StringRef getToken() const {
505 if (Kind == Expression)
506 return getExpressionAsToken();
508 return StringRef(Tok.Data, Tok.Length);
511 int64_t getImm() const {
516 ImmTy getImmTy() const {
521 unsigned getReg() const override {
525 SMLoc getStartLoc() const override {
529 SMLoc getEndLoc() const override {
533 Modifiers getModifiers() const {
534 assert(isRegKind() || isImmTy(ImmTyNone));
535 return isRegKind() ? Reg.Mods : Imm.Mods;
538 void setModifiers(Modifiers Mods) {
539 assert(isRegKind() || isImmTy(ImmTyNone));
546 bool hasModifiers() const {
547 return getModifiers().hasModifiers();
550 bool hasFPModifiers() const {
551 return getModifiers().hasFPModifiers();
554 bool hasIntModifiers() const {
555 return getModifiers().hasIntModifiers();
558 uint64_t applyInputFPModifiers(uint64_t Val, unsigned Size) const;
560 void addImmOperands(MCInst &Inst, unsigned N, bool ApplyModifiers = true) const;
562 void addLiteralImmOperand(MCInst &Inst, int64_t Val, bool ApplyModifiers) const;
564 template <unsigned Bitwidth>
565 void addKImmFPOperands(MCInst &Inst, unsigned N) const;
567 void addKImmFP16Operands(MCInst &Inst, unsigned N) const {
568 addKImmFPOperands<16>(Inst, N);
571 void addKImmFP32Operands(MCInst &Inst, unsigned N) const {
572 addKImmFPOperands<32>(Inst, N);
575 void addRegOperands(MCInst &Inst, unsigned N) const;
577 void addRegOrImmOperands(MCInst &Inst, unsigned N) const {
579 addRegOperands(Inst, N);
581 Inst.addOperand(MCOperand::createExpr(Expr));
583 addImmOperands(Inst, N);
586 void addRegOrImmWithInputModsOperands(MCInst &Inst, unsigned N) const {
587 Modifiers Mods = getModifiers();
588 Inst.addOperand(MCOperand::createImm(Mods.getModifiersOperand()));
590 addRegOperands(Inst, N);
592 addImmOperands(Inst, N, false);
596 void addRegOrImmWithFPInputModsOperands(MCInst &Inst, unsigned N) const {
597 assert(!hasIntModifiers());
598 addRegOrImmWithInputModsOperands(Inst, N);
601 void addRegOrImmWithIntInputModsOperands(MCInst &Inst, unsigned N) const {
602 assert(!hasFPModifiers());
603 addRegOrImmWithInputModsOperands(Inst, N);
606 void addRegWithInputModsOperands(MCInst &Inst, unsigned N) const {
607 Modifiers Mods = getModifiers();
608 Inst.addOperand(MCOperand::createImm(Mods.getModifiersOperand()));
610 addRegOperands(Inst, N);
613 void addRegWithFPInputModsOperands(MCInst &Inst, unsigned N) const {
614 assert(!hasIntModifiers());
615 addRegWithInputModsOperands(Inst, N);
618 void addRegWithIntInputModsOperands(MCInst &Inst, unsigned N) const {
619 assert(!hasFPModifiers());
620 addRegWithInputModsOperands(Inst, N);
623 void addSoppBrTargetOperands(MCInst &Inst, unsigned N) const {
625 addImmOperands(Inst, N);
628 Inst.addOperand(MCOperand::createExpr(Expr));
632 static void printImmTy(raw_ostream& OS, ImmTy Type) {
634 case ImmTyNone: OS << "None"; break;
635 case ImmTyGDS: OS << "GDS"; break;
636 case ImmTyOffen: OS << "Offen"; break;
637 case ImmTyIdxen: OS << "Idxen"; break;
638 case ImmTyAddr64: OS << "Addr64"; break;
639 case ImmTyOffset: OS << "Offset"; break;
640 case ImmTyOffset0: OS << "Offset0"; break;
641 case ImmTyOffset1: OS << "Offset1"; break;
642 case ImmTyGLC: OS << "GLC"; break;
643 case ImmTySLC: OS << "SLC"; break;
644 case ImmTyTFE: OS << "TFE"; break;
645 case ImmTyDFMT: OS << "DFMT"; break;
646 case ImmTyNFMT: OS << "NFMT"; break;
647 case ImmTyClampSI: OS << "ClampSI"; break;
648 case ImmTyOModSI: OS << "OModSI"; break;
649 case ImmTyDppCtrl: OS << "DppCtrl"; break;
650 case ImmTyDppRowMask: OS << "DppRowMask"; break;
651 case ImmTyDppBankMask: OS << "DppBankMask"; break;
652 case ImmTyDppBoundCtrl: OS << "DppBoundCtrl"; break;
653 case ImmTySdwaDstSel: OS << "SdwaDstSel"; break;
654 case ImmTySdwaSrc0Sel: OS << "SdwaSrc0Sel"; break;
655 case ImmTySdwaSrc1Sel: OS << "SdwaSrc1Sel"; break;
656 case ImmTySdwaDstUnused: OS << "SdwaDstUnused"; break;
657 case ImmTyDMask: OS << "DMask"; break;
658 case ImmTyUNorm: OS << "UNorm"; break;
659 case ImmTyDA: OS << "DA"; break;
660 case ImmTyR128: OS << "R128"; break;
661 case ImmTyLWE: OS << "LWE"; break;
662 case ImmTyOff: OS << "Off"; break;
663 case ImmTyExpTgt: OS << "ExpTgt"; break;
664 case ImmTyExpCompr: OS << "ExpCompr"; break;
665 case ImmTyExpVM: OS << "ExpVM"; break;
666 case ImmTyHwreg: OS << "Hwreg"; break;
667 case ImmTySendMsg: OS << "SendMsg"; break;
668 case ImmTyInterpSlot: OS << "InterpSlot"; break;
669 case ImmTyInterpAttr: OS << "InterpAttr"; break;
670 case ImmTyAttrChan: OS << "AttrChan"; break;
671 case ImmTyOpSel: OS << "OpSel"; break;
672 case ImmTyOpSelHi: OS << "OpSelHi"; break;
673 case ImmTyNegLo: OS << "NegLo"; break;
674 case ImmTyNegHi: OS << "NegHi"; break;
675 case ImmTySwizzle: OS << "Swizzle"; break;
679 void print(raw_ostream &OS) const override {
682 OS << "<register " << getReg() << " mods: " << Reg.Mods << '>';
685 OS << '<' << getImm();
686 if (getImmTy() != ImmTyNone) {
687 OS << " type: "; printImmTy(OS, getImmTy());
689 OS << " mods: " << Imm.Mods << '>';
692 OS << '\'' << getToken() << '\'';
695 OS << "<expr " << *Expr << '>';
700 static AMDGPUOperand::Ptr CreateImm(const AMDGPUAsmParser *AsmParser,
701 int64_t Val, SMLoc Loc,
702 ImmTy Type = ImmTyNone,
703 bool IsFPImm = false) {
704 auto Op = llvm::make_unique<AMDGPUOperand>(Immediate, AsmParser);
706 Op->Imm.IsFPImm = IsFPImm;
708 Op->Imm.Mods = Modifiers();
714 static AMDGPUOperand::Ptr CreateToken(const AMDGPUAsmParser *AsmParser,
715 StringRef Str, SMLoc Loc,
716 bool HasExplicitEncodingSize = true) {
717 auto Res = llvm::make_unique<AMDGPUOperand>(Token, AsmParser);
718 Res->Tok.Data = Str.data();
719 Res->Tok.Length = Str.size();
725 static AMDGPUOperand::Ptr CreateReg(const AMDGPUAsmParser *AsmParser,
726 unsigned RegNo, SMLoc S,
729 auto Op = llvm::make_unique<AMDGPUOperand>(Register, AsmParser);
730 Op->Reg.RegNo = RegNo;
731 Op->Reg.Mods = Modifiers();
732 Op->Reg.IsForcedVOP3 = ForceVOP3;
738 static AMDGPUOperand::Ptr CreateExpr(const AMDGPUAsmParser *AsmParser,
739 const class MCExpr *Expr, SMLoc S) {
740 auto Op = llvm::make_unique<AMDGPUOperand>(Expression, AsmParser);
748 raw_ostream &operator <<(raw_ostream &OS, AMDGPUOperand::Modifiers Mods) {
749 OS << "abs:" << Mods.Abs << " neg: " << Mods.Neg << " sext:" << Mods.Sext;
753 //===----------------------------------------------------------------------===//
755 //===----------------------------------------------------------------------===//
757 // Holds info related to the current kernel, e.g. count of SGPRs used.
758 // Kernel scope begins at .amdgpu_hsa_kernel directive, ends at next
759 // .amdgpu_hsa_kernel or at EOF.
760 class KernelScopeInfo {
761 int SgprIndexUnusedMin = -1;
762 int VgprIndexUnusedMin = -1;
763 MCContext *Ctx = nullptr;
765 void usesSgprAt(int i) {
766 if (i >= SgprIndexUnusedMin) {
767 SgprIndexUnusedMin = ++i;
769 MCSymbol * const Sym = Ctx->getOrCreateSymbol(Twine(".kernel.sgpr_count"));
770 Sym->setVariableValue(MCConstantExpr::create(SgprIndexUnusedMin, *Ctx));
775 void usesVgprAt(int i) {
776 if (i >= VgprIndexUnusedMin) {
777 VgprIndexUnusedMin = ++i;
779 MCSymbol * const Sym = Ctx->getOrCreateSymbol(Twine(".kernel.vgpr_count"));
780 Sym->setVariableValue(MCConstantExpr::create(VgprIndexUnusedMin, *Ctx));
786 KernelScopeInfo() = default;
788 void initialize(MCContext &Context) {
790 usesSgprAt(SgprIndexUnusedMin = -1);
791 usesVgprAt(VgprIndexUnusedMin = -1);
794 void usesRegister(RegisterKind RegKind, unsigned DwordRegIndex, unsigned RegWidth) {
796 case IS_SGPR: usesSgprAt(DwordRegIndex + RegWidth - 1); break;
797 case IS_VGPR: usesVgprAt(DwordRegIndex + RegWidth - 1); break;
803 class AMDGPUAsmParser : public MCTargetAsmParser {
804 const MCInstrInfo &MII;
807 unsigned ForcedEncodingSize = 0;
808 bool ForcedDPP = false;
809 bool ForcedSDWA = false;
810 KernelScopeInfo KernelScope;
812 /// @name Auto-generated Match Functions
815 #define GET_ASSEMBLER_HEADER
816 #include "AMDGPUGenAsmMatcher.inc"
821 bool ParseAsAbsoluteExpression(uint32_t &Ret);
822 bool ParseDirectiveMajorMinor(uint32_t &Major, uint32_t &Minor);
823 bool ParseDirectiveHSACodeObjectVersion();
824 bool ParseDirectiveHSACodeObjectISA();
825 bool ParseDirectiveCodeObjectMetadata();
826 bool ParseAMDKernelCodeTValue(StringRef ID, amd_kernel_code_t &Header);
827 bool ParseDirectiveAMDKernelCodeT();
828 bool subtargetHasRegister(const MCRegisterInfo &MRI, unsigned RegNo) const;
829 bool ParseDirectiveAMDGPUHsaKernel();
830 bool AddNextRegisterToList(unsigned& Reg, unsigned& RegWidth,
831 RegisterKind RegKind, unsigned Reg1,
833 bool ParseAMDGPURegister(RegisterKind& RegKind, unsigned& Reg,
834 unsigned& RegNum, unsigned& RegWidth,
835 unsigned *DwordRegIndex);
836 void cvtMubufImpl(MCInst &Inst, const OperandVector &Operands,
837 bool IsAtomic, bool IsAtomicReturn);
838 void cvtDSImpl(MCInst &Inst, const OperandVector &Operands,
839 bool IsGdsHardcoded);
842 enum AMDGPUMatchResultTy {
843 Match_PreferE32 = FIRST_TARGET_MATCH_RESULT_TY
846 typedef std::map<AMDGPUOperand::ImmTy, unsigned> OptionalImmIndexMap;
848 AMDGPUAsmParser(const MCSubtargetInfo &STI, MCAsmParser &_Parser,
849 const MCInstrInfo &MII,
850 const MCTargetOptions &Options)
851 : MCTargetAsmParser(Options, STI), MII(MII), Parser(_Parser) {
852 MCAsmParserExtension::Initialize(Parser);
854 if (getFeatureBits().none()) {
855 // Set default features.
856 copySTI().ToggleFeature("SOUTHERN_ISLANDS");
859 setAvailableFeatures(ComputeAvailableFeatures(getFeatureBits()));
862 // TODO: make those pre-defined variables read-only.
863 // Currently there is none suitable machinery in the core llvm-mc for this.
864 // MCSymbol::isRedefinable is intended for another purpose, and
865 // AsmParser::parseDirectiveSet() cannot be specialized for specific target.
866 AMDGPU::IsaInfo::IsaVersion ISA =
867 AMDGPU::IsaInfo::getIsaVersion(getFeatureBits());
868 MCContext &Ctx = getContext();
870 Ctx.getOrCreateSymbol(Twine(".option.machine_version_major"));
871 Sym->setVariableValue(MCConstantExpr::create(ISA.Major, Ctx));
872 Sym = Ctx.getOrCreateSymbol(Twine(".option.machine_version_minor"));
873 Sym->setVariableValue(MCConstantExpr::create(ISA.Minor, Ctx));
874 Sym = Ctx.getOrCreateSymbol(Twine(".option.machine_version_stepping"));
875 Sym->setVariableValue(MCConstantExpr::create(ISA.Stepping, Ctx));
877 KernelScope.initialize(getContext());
881 return AMDGPU::isSI(getSTI());
885 return AMDGPU::isCI(getSTI());
889 return AMDGPU::isVI(getSTI());
892 bool isGFX9() const {
893 return AMDGPU::isGFX9(getSTI());
896 bool hasInv2PiInlineImm() const {
897 return getFeatureBits()[AMDGPU::FeatureInv2PiInlineImm];
900 bool hasFlatOffsets() const {
901 return getFeatureBits()[AMDGPU::FeatureFlatInstOffsets];
904 bool hasSGPR102_SGPR103() const {
908 AMDGPUTargetStreamer &getTargetStreamer() {
909 MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
910 return static_cast<AMDGPUTargetStreamer &>(TS);
913 const MCRegisterInfo *getMRI() const {
914 // We need this const_cast because for some reason getContext() is not const
916 return const_cast<AMDGPUAsmParser*>(this)->getContext().getRegisterInfo();
919 const MCInstrInfo *getMII() const {
923 const FeatureBitset &getFeatureBits() const {
924 return getSTI().getFeatureBits();
927 void setForcedEncodingSize(unsigned Size) { ForcedEncodingSize = Size; }
928 void setForcedDPP(bool ForceDPP_) { ForcedDPP = ForceDPP_; }
929 void setForcedSDWA(bool ForceSDWA_) { ForcedSDWA = ForceSDWA_; }
931 unsigned getForcedEncodingSize() const { return ForcedEncodingSize; }
932 bool isForcedVOP3() const { return ForcedEncodingSize == 64; }
933 bool isForcedDPP() const { return ForcedDPP; }
934 bool isForcedSDWA() const { return ForcedSDWA; }
935 ArrayRef<unsigned> getMatchedVariants() const;
937 std::unique_ptr<AMDGPUOperand> parseRegister();
938 bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
939 unsigned checkTargetMatchPredicate(MCInst &Inst) override;
940 unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
941 unsigned Kind) override;
942 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
943 OperandVector &Operands, MCStreamer &Out,
945 bool MatchingInlineAsm) override;
946 bool ParseDirective(AsmToken DirectiveID) override;
947 OperandMatchResultTy parseOperand(OperandVector &Operands, StringRef Mnemonic);
948 StringRef parseMnemonicSuffix(StringRef Name);
949 bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
950 SMLoc NameLoc, OperandVector &Operands) override;
951 //bool ProcessInstruction(MCInst &Inst);
953 OperandMatchResultTy parseIntWithPrefix(const char *Prefix, int64_t &Int);
956 parseIntWithPrefix(const char *Prefix, OperandVector &Operands,
957 AMDGPUOperand::ImmTy ImmTy = AMDGPUOperand::ImmTyNone,
958 bool (*ConvertResult)(int64_t &) = nullptr);
960 OperandMatchResultTy parseOperandArrayWithPrefix(
962 OperandVector &Operands,
963 AMDGPUOperand::ImmTy ImmTy = AMDGPUOperand::ImmTyNone,
964 bool (*ConvertResult)(int64_t&) = nullptr);
967 parseNamedBit(const char *Name, OperandVector &Operands,
968 AMDGPUOperand::ImmTy ImmTy = AMDGPUOperand::ImmTyNone);
969 OperandMatchResultTy parseStringWithPrefix(StringRef Prefix,
972 bool parseAbsoluteExpr(int64_t &Val, bool AbsMod = false);
973 OperandMatchResultTy parseImm(OperandVector &Operands, bool AbsMod = false);
974 OperandMatchResultTy parseReg(OperandVector &Operands);
975 OperandMatchResultTy parseRegOrImm(OperandVector &Operands, bool AbsMod = false);
976 OperandMatchResultTy parseRegOrImmWithFPInputMods(OperandVector &Operands, bool AllowImm = true);
977 OperandMatchResultTy parseRegOrImmWithIntInputMods(OperandVector &Operands, bool AllowImm = true);
978 OperandMatchResultTy parseRegWithFPInputMods(OperandVector &Operands);
979 OperandMatchResultTy parseRegWithIntInputMods(OperandVector &Operands);
980 OperandMatchResultTy parseVReg32OrOff(OperandVector &Operands);
982 void cvtDSOffset01(MCInst &Inst, const OperandVector &Operands);
983 void cvtDS(MCInst &Inst, const OperandVector &Operands) { cvtDSImpl(Inst, Operands, false); }
984 void cvtDSGds(MCInst &Inst, const OperandVector &Operands) { cvtDSImpl(Inst, Operands, true); }
985 void cvtExp(MCInst &Inst, const OperandVector &Operands);
987 bool parseCnt(int64_t &IntVal);
988 OperandMatchResultTy parseSWaitCntOps(OperandVector &Operands);
989 OperandMatchResultTy parseHwreg(OperandVector &Operands);
992 struct OperandInfoTy {
995 OperandInfoTy(int64_t Id_) : Id(Id_), IsSymbolic(false) { }
998 bool parseSendMsgConstruct(OperandInfoTy &Msg, OperandInfoTy &Operation, int64_t &StreamId);
999 bool parseHwregConstruct(OperandInfoTy &HwReg, int64_t &Offset, int64_t &Width);
1002 OperandMatchResultTy parseExpTgtImpl(StringRef Str, uint8_t &Val);
1004 bool validateInstruction(const MCInst &Inst, const SMLoc &IDLoc);
1005 bool validateConstantBusLimitations(const MCInst &Inst);
1006 bool validateEarlyClobberLimitations(const MCInst &Inst);
1007 bool usesConstantBus(const MCInst &Inst, unsigned OpIdx);
1008 bool isInlineConstant(const MCInst &Inst, unsigned OpIdx) const;
1009 unsigned findImplicitSGPRReadInVOP(const MCInst &Inst) const;
1011 bool trySkipId(const StringRef Id);
1012 bool trySkipToken(const AsmToken::TokenKind Kind);
1013 bool skipToken(const AsmToken::TokenKind Kind, const StringRef ErrMsg);
1014 bool parseString(StringRef &Val, const StringRef ErrMsg = "expected a string");
1015 bool parseExpr(int64_t &Imm);
1018 OperandMatchResultTy parseOptionalOperand(OperandVector &Operands);
1020 OperandMatchResultTy parseExpTgt(OperandVector &Operands);
1021 OperandMatchResultTy parseSendMsgOp(OperandVector &Operands);
1022 OperandMatchResultTy parseInterpSlot(OperandVector &Operands);
1023 OperandMatchResultTy parseInterpAttr(OperandVector &Operands);
1024 OperandMatchResultTy parseSOppBrTarget(OperandVector &Operands);
1026 bool parseSwizzleOperands(const unsigned OpNum, int64_t* Op,
1027 const unsigned MinVal,
1028 const unsigned MaxVal,
1029 const StringRef ErrMsg);
1030 OperandMatchResultTy parseSwizzleOp(OperandVector &Operands);
1031 bool parseSwizzleOffset(int64_t &Imm);
1032 bool parseSwizzleMacro(int64_t &Imm);
1033 bool parseSwizzleQuadPerm(int64_t &Imm);
1034 bool parseSwizzleBitmaskPerm(int64_t &Imm);
1035 bool parseSwizzleBroadcast(int64_t &Imm);
1036 bool parseSwizzleSwap(int64_t &Imm);
1037 bool parseSwizzleReverse(int64_t &Imm);
1039 void cvtMubuf(MCInst &Inst, const OperandVector &Operands) { cvtMubufImpl(Inst, Operands, false, false); }
1040 void cvtMubufAtomic(MCInst &Inst, const OperandVector &Operands) { cvtMubufImpl(Inst, Operands, true, false); }
1041 void cvtMubufAtomicReturn(MCInst &Inst, const OperandVector &Operands) { cvtMubufImpl(Inst, Operands, true, true); }
1042 void cvtMtbuf(MCInst &Inst, const OperandVector &Operands);
1044 AMDGPUOperand::Ptr defaultGLC() const;
1045 AMDGPUOperand::Ptr defaultSLC() const;
1046 AMDGPUOperand::Ptr defaultTFE() const;
1048 AMDGPUOperand::Ptr defaultDMask() const;
1049 AMDGPUOperand::Ptr defaultUNorm() const;
1050 AMDGPUOperand::Ptr defaultDA() const;
1051 AMDGPUOperand::Ptr defaultR128() const;
1052 AMDGPUOperand::Ptr defaultLWE() const;
1053 AMDGPUOperand::Ptr defaultSMRDOffset8() const;
1054 AMDGPUOperand::Ptr defaultSMRDOffset20() const;
1055 AMDGPUOperand::Ptr defaultSMRDLiteralOffset() const;
1056 AMDGPUOperand::Ptr defaultOffsetU12() const;
1057 AMDGPUOperand::Ptr defaultOffsetS13() const;
1059 OperandMatchResultTy parseOModOperand(OperandVector &Operands);
1061 void cvtVOP3(MCInst &Inst, const OperandVector &Operands,
1062 OptionalImmIndexMap &OptionalIdx);
1063 void cvtVOP3(MCInst &Inst, const OperandVector &Operands);
1064 void cvtVOP3P(MCInst &Inst, const OperandVector &Operands);
1066 void cvtMIMG(MCInst &Inst, const OperandVector &Operands,
1067 bool IsAtomic = false);
1068 void cvtMIMGAtomic(MCInst &Inst, const OperandVector &Operands);
1070 OperandMatchResultTy parseDPPCtrl(OperandVector &Operands);
1071 AMDGPUOperand::Ptr defaultRowMask() const;
1072 AMDGPUOperand::Ptr defaultBankMask() const;
1073 AMDGPUOperand::Ptr defaultBoundCtrl() const;
1074 void cvtDPP(MCInst &Inst, const OperandVector &Operands);
1076 OperandMatchResultTy parseSDWASel(OperandVector &Operands, StringRef Prefix,
1077 AMDGPUOperand::ImmTy Type);
1078 OperandMatchResultTy parseSDWADstUnused(OperandVector &Operands);
1079 void cvtSdwaVOP1(MCInst &Inst, const OperandVector &Operands);
1080 void cvtSdwaVOP2(MCInst &Inst, const OperandVector &Operands);
1081 void cvtSdwaVOP2b(MCInst &Inst, const OperandVector &Operands);
1082 void cvtSdwaVOPC(MCInst &Inst, const OperandVector &Operands);
1083 void cvtSDWA(MCInst &Inst, const OperandVector &Operands,
1084 uint64_t BasicInstType, bool skipVcc = false);
1087 struct OptionalOperand {
1089 AMDGPUOperand::ImmTy Type;
1091 bool (*ConvertResult)(int64_t&);
1094 } // end anonymous namespace
1096 // May be called with integer type with equivalent bitwidth.
1097 static const fltSemantics *getFltSemantics(unsigned Size) {
1100 return &APFloat::IEEEsingle();
1102 return &APFloat::IEEEdouble();
1104 return &APFloat::IEEEhalf();
1106 llvm_unreachable("unsupported fp type");
1110 static const fltSemantics *getFltSemantics(MVT VT) {
1111 return getFltSemantics(VT.getSizeInBits() / 8);
1114 static const fltSemantics *getOpFltSemantics(uint8_t OperandType) {
1115 switch (OperandType) {
1116 case AMDGPU::OPERAND_REG_IMM_INT32:
1117 case AMDGPU::OPERAND_REG_IMM_FP32:
1118 case AMDGPU::OPERAND_REG_INLINE_C_INT32:
1119 case AMDGPU::OPERAND_REG_INLINE_C_FP32:
1120 return &APFloat::IEEEsingle();
1121 case AMDGPU::OPERAND_REG_IMM_INT64:
1122 case AMDGPU::OPERAND_REG_IMM_FP64:
1123 case AMDGPU::OPERAND_REG_INLINE_C_INT64:
1124 case AMDGPU::OPERAND_REG_INLINE_C_FP64:
1125 return &APFloat::IEEEdouble();
1126 case AMDGPU::OPERAND_REG_IMM_INT16:
1127 case AMDGPU::OPERAND_REG_IMM_FP16:
1128 case AMDGPU::OPERAND_REG_INLINE_C_INT16:
1129 case AMDGPU::OPERAND_REG_INLINE_C_FP16:
1130 case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
1131 case AMDGPU::OPERAND_REG_INLINE_C_V2FP16:
1132 return &APFloat::IEEEhalf();
1134 llvm_unreachable("unsupported fp type");
1138 //===----------------------------------------------------------------------===//
1140 //===----------------------------------------------------------------------===//
1142 static bool canLosslesslyConvertToFPType(APFloat &FPLiteral, MVT VT) {
1145 // Convert literal to single precision
1146 APFloat::opStatus Status = FPLiteral.convert(*getFltSemantics(VT),
1147 APFloat::rmNearestTiesToEven,
1149 // We allow precision lost but not overflow or underflow
1150 if (Status != APFloat::opOK &&
1152 ((Status & APFloat::opOverflow) != 0 ||
1153 (Status & APFloat::opUnderflow) != 0)) {
1160 bool AMDGPUOperand::isInlinableImm(MVT type) const {
1161 if (!isImmTy(ImmTyNone)) {
1162 // Only plain immediates are inlinable (e.g. "clamp" attribute is not)
1165 // TODO: We should avoid using host float here. It would be better to
1166 // check the float bit values which is what a few other places do.
1167 // We've had bot failures before due to weird NaN support on mips hosts.
1169 APInt Literal(64, Imm.Val);
1171 if (Imm.IsFPImm) { // We got fp literal token
1172 if (type == MVT::f64 || type == MVT::i64) { // Expected 64-bit operand
1173 return AMDGPU::isInlinableLiteral64(Imm.Val,
1174 AsmParser->hasInv2PiInlineImm());
1177 APFloat FPLiteral(APFloat::IEEEdouble(), APInt(64, Imm.Val));
1178 if (!canLosslesslyConvertToFPType(FPLiteral, type))
1181 if (type.getScalarSizeInBits() == 16) {
1182 return AMDGPU::isInlinableLiteral16(
1183 static_cast<int16_t>(FPLiteral.bitcastToAPInt().getZExtValue()),
1184 AsmParser->hasInv2PiInlineImm());
1187 // Check if single precision literal is inlinable
1188 return AMDGPU::isInlinableLiteral32(
1189 static_cast<int32_t>(FPLiteral.bitcastToAPInt().getZExtValue()),
1190 AsmParser->hasInv2PiInlineImm());
1193 // We got int literal token.
1194 if (type == MVT::f64 || type == MVT::i64) { // Expected 64-bit operand
1195 return AMDGPU::isInlinableLiteral64(Imm.Val,
1196 AsmParser->hasInv2PiInlineImm());
1199 if (type.getScalarSizeInBits() == 16) {
1200 return AMDGPU::isInlinableLiteral16(
1201 static_cast<int16_t>(Literal.getLoBits(16).getSExtValue()),
1202 AsmParser->hasInv2PiInlineImm());
1205 return AMDGPU::isInlinableLiteral32(
1206 static_cast<int32_t>(Literal.getLoBits(32).getZExtValue()),
1207 AsmParser->hasInv2PiInlineImm());
1210 bool AMDGPUOperand::isLiteralImm(MVT type) const {
1211 // Check that this immediate can be added as literal
1212 if (!isImmTy(ImmTyNone)) {
1217 // We got int literal token.
1219 if (type == MVT::f64 && hasFPModifiers()) {
1220 // Cannot apply fp modifiers to int literals preserving the same semantics
1221 // for VOP1/2/C and VOP3 because of integer truncation. To avoid ambiguity,
1222 // disable these cases.
1226 unsigned Size = type.getSizeInBits();
1230 // FIXME: 64-bit operands can zero extend, sign extend, or pad zeroes for FP
1232 return isUIntN(Size, Imm.Val) || isIntN(Size, Imm.Val);
1235 // We got fp literal token
1236 if (type == MVT::f64) { // Expected 64-bit fp operand
1237 // We would set low 64-bits of literal to zeroes but we accept this literals
1241 if (type == MVT::i64) { // Expected 64-bit int operand
1242 // We don't allow fp literals in 64-bit integer instructions. It is
1243 // unclear how we should encode them.
1247 APFloat FPLiteral(APFloat::IEEEdouble(), APInt(64, Imm.Val));
1248 return canLosslesslyConvertToFPType(FPLiteral, type);
1251 bool AMDGPUOperand::isRegClass(unsigned RCID) const {
1252 return isRegKind() && AsmParser->getMRI()->getRegClass(RCID).contains(getReg());
1255 bool AMDGPUOperand::isSDWARegKind() const {
1256 if (AsmParser->isVI())
1258 else if (AsmParser->isGFX9())
1264 uint64_t AMDGPUOperand::applyInputFPModifiers(uint64_t Val, unsigned Size) const
1266 assert(isImmTy(ImmTyNone) && Imm.Mods.hasFPModifiers());
1267 assert(Size == 2 || Size == 4 || Size == 8);
1269 const uint64_t FpSignMask = (1ULL << (Size * 8 - 1));
1281 void AMDGPUOperand::addImmOperands(MCInst &Inst, unsigned N, bool ApplyModifiers) const {
1283 if (AMDGPU::isSISrcOperand(AsmParser->getMII()->get(Inst.getOpcode()),
1284 Inst.getNumOperands())) {
1285 addLiteralImmOperand(Inst, Imm.Val,
1287 isImmTy(ImmTyNone) && Imm.Mods.hasFPModifiers());
1289 assert(!isImmTy(ImmTyNone) || !hasModifiers());
1290 Inst.addOperand(MCOperand::createImm(Imm.Val));
1294 void AMDGPUOperand::addLiteralImmOperand(MCInst &Inst, int64_t Val, bool ApplyModifiers) const {
1295 const auto& InstDesc = AsmParser->getMII()->get(Inst.getOpcode());
1296 auto OpNum = Inst.getNumOperands();
1297 // Check that this operand accepts literals
1298 assert(AMDGPU::isSISrcOperand(InstDesc, OpNum));
1300 if (ApplyModifiers) {
1301 assert(AMDGPU::isSISrcFPOperand(InstDesc, OpNum));
1302 const unsigned Size = Imm.IsFPImm ? sizeof(double) : getOperandSize(InstDesc, OpNum);
1303 Val = applyInputFPModifiers(Val, Size);
1306 APInt Literal(64, Val);
1307 uint8_t OpTy = InstDesc.OpInfo[OpNum].OperandType;
1309 if (Imm.IsFPImm) { // We got fp literal token
1311 case AMDGPU::OPERAND_REG_IMM_INT64:
1312 case AMDGPU::OPERAND_REG_IMM_FP64:
1313 case AMDGPU::OPERAND_REG_INLINE_C_INT64:
1314 case AMDGPU::OPERAND_REG_INLINE_C_FP64: {
1315 if (AMDGPU::isInlinableLiteral64(Literal.getZExtValue(),
1316 AsmParser->hasInv2PiInlineImm())) {
1317 Inst.addOperand(MCOperand::createImm(Literal.getZExtValue()));
1322 if (AMDGPU::isSISrcFPOperand(InstDesc, OpNum)) { // Expected 64-bit fp operand
1323 // For fp operands we check if low 32 bits are zeros
1324 if (Literal.getLoBits(32) != 0) {
1325 const_cast<AMDGPUAsmParser *>(AsmParser)->Warning(Inst.getLoc(),
1326 "Can't encode literal as exact 64-bit floating-point operand. "
1327 "Low 32-bits will be set to zero");
1330 Inst.addOperand(MCOperand::createImm(Literal.lshr(32).getZExtValue()));
1334 // We don't allow fp literals in 64-bit integer instructions. It is
1335 // unclear how we should encode them. This case should be checked earlier
1336 // in predicate methods (isLiteralImm())
1337 llvm_unreachable("fp literal in 64-bit integer instruction.");
1339 case AMDGPU::OPERAND_REG_IMM_INT32:
1340 case AMDGPU::OPERAND_REG_IMM_FP32:
1341 case AMDGPU::OPERAND_REG_INLINE_C_INT32:
1342 case AMDGPU::OPERAND_REG_INLINE_C_FP32:
1343 case AMDGPU::OPERAND_REG_IMM_INT16:
1344 case AMDGPU::OPERAND_REG_IMM_FP16:
1345 case AMDGPU::OPERAND_REG_INLINE_C_INT16:
1346 case AMDGPU::OPERAND_REG_INLINE_C_FP16:
1347 case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
1348 case AMDGPU::OPERAND_REG_INLINE_C_V2FP16: {
1350 APFloat FPLiteral(APFloat::IEEEdouble(), Literal);
1351 // Convert literal to single precision
1352 FPLiteral.convert(*getOpFltSemantics(OpTy),
1353 APFloat::rmNearestTiesToEven, &lost);
1354 // We allow precision lost but not overflow or underflow. This should be
1355 // checked earlier in isLiteralImm()
1357 uint64_t ImmVal = FPLiteral.bitcastToAPInt().getZExtValue();
1358 if (OpTy == AMDGPU::OPERAND_REG_INLINE_C_V2INT16 ||
1359 OpTy == AMDGPU::OPERAND_REG_INLINE_C_V2FP16) {
1360 ImmVal |= (ImmVal << 16);
1363 Inst.addOperand(MCOperand::createImm(ImmVal));
1367 llvm_unreachable("invalid operand size");
1373 // We got int literal token.
1374 // Only sign extend inline immediates.
1375 // FIXME: No errors on truncation
1377 case AMDGPU::OPERAND_REG_IMM_INT32:
1378 case AMDGPU::OPERAND_REG_IMM_FP32:
1379 case AMDGPU::OPERAND_REG_INLINE_C_INT32:
1380 case AMDGPU::OPERAND_REG_INLINE_C_FP32: {
1381 if (isInt<32>(Val) &&
1382 AMDGPU::isInlinableLiteral32(static_cast<int32_t>(Val),
1383 AsmParser->hasInv2PiInlineImm())) {
1384 Inst.addOperand(MCOperand::createImm(Val));
1388 Inst.addOperand(MCOperand::createImm(Val & 0xffffffff));
1391 case AMDGPU::OPERAND_REG_IMM_INT64:
1392 case AMDGPU::OPERAND_REG_IMM_FP64:
1393 case AMDGPU::OPERAND_REG_INLINE_C_INT64:
1394 case AMDGPU::OPERAND_REG_INLINE_C_FP64: {
1395 if (AMDGPU::isInlinableLiteral64(Val, AsmParser->hasInv2PiInlineImm())) {
1396 Inst.addOperand(MCOperand::createImm(Val));
1400 Inst.addOperand(MCOperand::createImm(Lo_32(Val)));
1403 case AMDGPU::OPERAND_REG_IMM_INT16:
1404 case AMDGPU::OPERAND_REG_IMM_FP16:
1405 case AMDGPU::OPERAND_REG_INLINE_C_INT16:
1406 case AMDGPU::OPERAND_REG_INLINE_C_FP16: {
1407 if (isInt<16>(Val) &&
1408 AMDGPU::isInlinableLiteral16(static_cast<int16_t>(Val),
1409 AsmParser->hasInv2PiInlineImm())) {
1410 Inst.addOperand(MCOperand::createImm(Val));
1414 Inst.addOperand(MCOperand::createImm(Val & 0xffff));
1417 case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
1418 case AMDGPU::OPERAND_REG_INLINE_C_V2FP16: {
1419 auto LiteralVal = static_cast<uint16_t>(Literal.getLoBits(16).getZExtValue());
1420 assert(AMDGPU::isInlinableLiteral16(LiteralVal,
1421 AsmParser->hasInv2PiInlineImm()));
1423 uint32_t ImmVal = static_cast<uint32_t>(LiteralVal) << 16 |
1424 static_cast<uint32_t>(LiteralVal);
1425 Inst.addOperand(MCOperand::createImm(ImmVal));
1429 llvm_unreachable("invalid operand size");
1433 template <unsigned Bitwidth>
1434 void AMDGPUOperand::addKImmFPOperands(MCInst &Inst, unsigned N) const {
1435 APInt Literal(64, Imm.Val);
1438 // We got int literal token.
1439 Inst.addOperand(MCOperand::createImm(Literal.getLoBits(Bitwidth).getZExtValue()));
1444 APFloat FPLiteral(APFloat::IEEEdouble(), Literal);
1445 FPLiteral.convert(*getFltSemantics(Bitwidth / 8),
1446 APFloat::rmNearestTiesToEven, &Lost);
1447 Inst.addOperand(MCOperand::createImm(FPLiteral.bitcastToAPInt().getZExtValue()));
1450 void AMDGPUOperand::addRegOperands(MCInst &Inst, unsigned N) const {
1451 Inst.addOperand(MCOperand::createReg(AMDGPU::getMCReg(getReg(), AsmParser->getSTI())));
1454 //===----------------------------------------------------------------------===//
1456 //===----------------------------------------------------------------------===//
1458 static int getRegClass(RegisterKind Is, unsigned RegWidth) {
1459 if (Is == IS_VGPR) {
1462 case 1: return AMDGPU::VGPR_32RegClassID;
1463 case 2: return AMDGPU::VReg_64RegClassID;
1464 case 3: return AMDGPU::VReg_96RegClassID;
1465 case 4: return AMDGPU::VReg_128RegClassID;
1466 case 8: return AMDGPU::VReg_256RegClassID;
1467 case 16: return AMDGPU::VReg_512RegClassID;
1469 } else if (Is == IS_TTMP) {
1472 case 1: return AMDGPU::TTMP_32RegClassID;
1473 case 2: return AMDGPU::TTMP_64RegClassID;
1474 case 4: return AMDGPU::TTMP_128RegClassID;
1476 } else if (Is == IS_SGPR) {
1479 case 1: return AMDGPU::SGPR_32RegClassID;
1480 case 2: return AMDGPU::SGPR_64RegClassID;
1481 case 4: return AMDGPU::SGPR_128RegClassID;
1482 case 8: return AMDGPU::SReg_256RegClassID;
1483 case 16: return AMDGPU::SReg_512RegClassID;
1489 static unsigned getSpecialRegForName(StringRef RegName) {
1490 return StringSwitch<unsigned>(RegName)
1491 .Case("exec", AMDGPU::EXEC)
1492 .Case("vcc", AMDGPU::VCC)
1493 .Case("flat_scratch", AMDGPU::FLAT_SCR)
1494 .Case("m0", AMDGPU::M0)
1495 .Case("scc", AMDGPU::SCC)
1496 .Case("tba", AMDGPU::TBA)
1497 .Case("tma", AMDGPU::TMA)
1498 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
1499 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
1500 .Case("vcc_lo", AMDGPU::VCC_LO)
1501 .Case("vcc_hi", AMDGPU::VCC_HI)
1502 .Case("exec_lo", AMDGPU::EXEC_LO)
1503 .Case("exec_hi", AMDGPU::EXEC_HI)
1504 .Case("tma_lo", AMDGPU::TMA_LO)
1505 .Case("tma_hi", AMDGPU::TMA_HI)
1506 .Case("tba_lo", AMDGPU::TBA_LO)
1507 .Case("tba_hi", AMDGPU::TBA_HI)
1511 bool AMDGPUAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1513 auto R = parseRegister();
1514 if (!R) return true;
1516 RegNo = R->getReg();
1517 StartLoc = R->getStartLoc();
1518 EndLoc = R->getEndLoc();
1522 bool AMDGPUAsmParser::AddNextRegisterToList(unsigned &Reg, unsigned &RegWidth,
1523 RegisterKind RegKind, unsigned Reg1,
1527 if (Reg == AMDGPU::EXEC_LO && Reg1 == AMDGPU::EXEC_HI) {
1532 if (Reg == AMDGPU::FLAT_SCR_LO && Reg1 == AMDGPU::FLAT_SCR_HI) {
1533 Reg = AMDGPU::FLAT_SCR;
1537 if (Reg == AMDGPU::VCC_LO && Reg1 == AMDGPU::VCC_HI) {
1542 if (Reg == AMDGPU::TBA_LO && Reg1 == AMDGPU::TBA_HI) {
1547 if (Reg == AMDGPU::TMA_LO && Reg1 == AMDGPU::TMA_HI) {
1556 if (Reg1 != Reg + RegWidth) {
1562 llvm_unreachable("unexpected register kind");
1566 bool AMDGPUAsmParser::ParseAMDGPURegister(RegisterKind &RegKind, unsigned &Reg,
1567 unsigned &RegNum, unsigned &RegWidth,
1568 unsigned *DwordRegIndex) {
1569 if (DwordRegIndex) { *DwordRegIndex = 0; }
1570 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
1571 if (getLexer().is(AsmToken::Identifier)) {
1572 StringRef RegName = Parser.getTok().getString();
1573 if ((Reg = getSpecialRegForName(RegName))) {
1575 RegKind = IS_SPECIAL;
1577 unsigned RegNumIndex = 0;
1578 if (RegName[0] == 'v') {
1581 } else if (RegName[0] == 's') {
1584 } else if (RegName.startswith("ttmp")) {
1585 RegNumIndex = strlen("ttmp");
1590 if (RegName.size() > RegNumIndex) {
1591 // Single 32-bit register: vXX.
1592 if (RegName.substr(RegNumIndex).getAsInteger(10, RegNum))
1597 // Range of registers: v[XX:YY]. ":YY" is optional.
1599 int64_t RegLo, RegHi;
1600 if (getLexer().isNot(AsmToken::LBrac))
1604 if (getParser().parseAbsoluteExpression(RegLo))
1607 const bool isRBrace = getLexer().is(AsmToken::RBrac);
1608 if (!isRBrace && getLexer().isNot(AsmToken::Colon))
1615 if (getParser().parseAbsoluteExpression(RegHi))
1618 if (getLexer().isNot(AsmToken::RBrac))
1622 RegNum = (unsigned) RegLo;
1623 RegWidth = (RegHi - RegLo) + 1;
1626 } else if (getLexer().is(AsmToken::LBrac)) {
1627 // List of consecutive registers: [s0,s1,s2,s3]
1629 if (!ParseAMDGPURegister(RegKind, Reg, RegNum, RegWidth, nullptr))
1633 RegisterKind RegKind1;
1634 unsigned Reg1, RegNum1, RegWidth1;
1636 if (getLexer().is(AsmToken::Comma)) {
1638 } else if (getLexer().is(AsmToken::RBrac)) {
1641 } else if (ParseAMDGPURegister(RegKind1, Reg1, RegNum1, RegWidth1, nullptr)) {
1642 if (RegWidth1 != 1) {
1645 if (RegKind1 != RegKind) {
1648 if (!AddNextRegisterToList(Reg, RegWidth, RegKind1, Reg1, RegNum1)) {
1668 if (RegKind == IS_SGPR || RegKind == IS_TTMP) {
1669 // SGPR and TTMP registers must be aligned. Max required alignment is 4 dwords.
1670 Size = std::min(RegWidth, 4u);
1672 if (RegNum % Size != 0)
1674 if (DwordRegIndex) { *DwordRegIndex = RegNum; }
1675 RegNum = RegNum / Size;
1676 int RCID = getRegClass(RegKind, RegWidth);
1679 const MCRegisterClass RC = TRI->getRegClass(RCID);
1680 if (RegNum >= RC.getNumRegs())
1682 Reg = RC.getRegister(RegNum);
1687 llvm_unreachable("unexpected register kind");
1690 if (!subtargetHasRegister(*TRI, Reg))
1695 std::unique_ptr<AMDGPUOperand> AMDGPUAsmParser::parseRegister() {
1696 const auto &Tok = Parser.getTok();
1697 SMLoc StartLoc = Tok.getLoc();
1698 SMLoc EndLoc = Tok.getEndLoc();
1699 RegisterKind RegKind;
1700 unsigned Reg, RegNum, RegWidth, DwordRegIndex;
1702 if (!ParseAMDGPURegister(RegKind, Reg, RegNum, RegWidth, &DwordRegIndex)) {
1705 KernelScope.usesRegister(RegKind, DwordRegIndex, RegWidth);
1706 return AMDGPUOperand::CreateReg(this, Reg, StartLoc, EndLoc, false);
1710 AMDGPUAsmParser::parseAbsoluteExpr(int64_t &Val, bool AbsMod) {
1711 if (AbsMod && getLexer().peekTok().is(AsmToken::Pipe) &&
1712 (getLexer().getKind() == AsmToken::Integer ||
1713 getLexer().getKind() == AsmToken::Real)) {
1715 // This is a workaround for handling operands like these:
1718 // This syntax is not compatible with syntax of standard
1719 // MC expressions (due to the trailing '|').
1724 if (getParser().parsePrimaryExpr(Expr, EndLoc)) {
1728 return !Expr->evaluateAsAbsolute(Val);
1731 return getParser().parseAbsoluteExpression(Val);
1734 OperandMatchResultTy
1735 AMDGPUAsmParser::parseImm(OperandVector &Operands, bool AbsMod) {
1736 // TODO: add syntactic sugar for 1/(2*PI)
1738 if (getLexer().getKind() == AsmToken::Minus) {
1743 SMLoc S = Parser.getTok().getLoc();
1744 switch(getLexer().getKind()) {
1745 case AsmToken::Integer: {
1747 if (parseAbsoluteExpr(IntVal, AbsMod))
1748 return MatchOperand_ParseFail;
1751 Operands.push_back(AMDGPUOperand::CreateImm(this, IntVal, S));
1752 return MatchOperand_Success;
1754 case AsmToken::Real: {
1756 if (parseAbsoluteExpr(IntVal, AbsMod))
1757 return MatchOperand_ParseFail;
1759 APFloat F(BitsToDouble(IntVal));
1763 AMDGPUOperand::CreateImm(this, F.bitcastToAPInt().getZExtValue(), S,
1764 AMDGPUOperand::ImmTyNone, true));
1765 return MatchOperand_Success;
1768 return Minus ? MatchOperand_ParseFail : MatchOperand_NoMatch;
1772 OperandMatchResultTy
1773 AMDGPUAsmParser::parseReg(OperandVector &Operands) {
1774 if (auto R = parseRegister()) {
1776 R->Reg.IsForcedVOP3 = isForcedVOP3();
1777 Operands.push_back(std::move(R));
1778 return MatchOperand_Success;
1780 return MatchOperand_NoMatch;
1783 OperandMatchResultTy
1784 AMDGPUAsmParser::parseRegOrImm(OperandVector &Operands, bool AbsMod) {
1785 auto res = parseImm(Operands, AbsMod);
1786 if (res != MatchOperand_NoMatch) {
1790 return parseReg(Operands);
1793 OperandMatchResultTy
1794 AMDGPUAsmParser::parseRegOrImmWithFPInputMods(OperandVector &Operands,
1796 bool Negate = false, Negate2 = false, Abs = false, Abs2 = false;
1798 if (getLexer().getKind()== AsmToken::Minus) {
1799 const AsmToken NextToken = getLexer().peekTok();
1801 // Disable ambiguous constructs like '--1' etc. Should use neg(-1) instead.
1802 if (NextToken.is(AsmToken::Minus)) {
1803 Error(Parser.getTok().getLoc(), "invalid syntax, expected 'neg' modifier");
1804 return MatchOperand_ParseFail;
1807 // '-' followed by an integer literal N should be interpreted as integer
1808 // negation rather than a floating-point NEG modifier applied to N.
1809 // Beside being contr-intuitive, such use of floating-point NEG modifier
1810 // results in different meaning of integer literals used with VOP1/2/C
1811 // and VOP3, for example:
1812 // v_exp_f32_e32 v5, -1 // VOP1: src0 = 0xFFFFFFFF
1813 // v_exp_f32_e64 v5, -1 // VOP3: src0 = 0x80000001
1814 // Negative fp literals should be handled likewise for unifomtity
1815 if (!NextToken.is(AsmToken::Integer) && !NextToken.is(AsmToken::Real)) {
1821 if (getLexer().getKind() == AsmToken::Identifier &&
1822 Parser.getTok().getString() == "neg") {
1824 Error(Parser.getTok().getLoc(), "expected register or immediate");
1825 return MatchOperand_ParseFail;
1829 if (getLexer().isNot(AsmToken::LParen)) {
1830 Error(Parser.getTok().getLoc(), "expected left paren after neg");
1831 return MatchOperand_ParseFail;
1836 if (getLexer().getKind() == AsmToken::Identifier &&
1837 Parser.getTok().getString() == "abs") {
1840 if (getLexer().isNot(AsmToken::LParen)) {
1841 Error(Parser.getTok().getLoc(), "expected left paren after abs");
1842 return MatchOperand_ParseFail;
1847 if (getLexer().getKind() == AsmToken::Pipe) {
1849 Error(Parser.getTok().getLoc(), "expected register or immediate");
1850 return MatchOperand_ParseFail;
1856 OperandMatchResultTy Res;
1858 Res = parseRegOrImm(Operands, Abs);
1860 Res = parseReg(Operands);
1862 if (Res != MatchOperand_Success) {
1866 AMDGPUOperand::Modifiers Mods;
1868 if (getLexer().getKind() != AsmToken::Pipe) {
1869 Error(Parser.getTok().getLoc(), "expected vertical bar");
1870 return MatchOperand_ParseFail;
1876 if (getLexer().isNot(AsmToken::RParen)) {
1877 Error(Parser.getTok().getLoc(), "expected closing parentheses");
1878 return MatchOperand_ParseFail;
1886 } else if (Negate2) {
1887 if (getLexer().isNot(AsmToken::RParen)) {
1888 Error(Parser.getTok().getLoc(), "expected closing parentheses");
1889 return MatchOperand_ParseFail;
1895 if (Mods.hasFPModifiers()) {
1896 AMDGPUOperand &Op = static_cast<AMDGPUOperand &>(*Operands.back());
1897 Op.setModifiers(Mods);
1899 return MatchOperand_Success;
1902 OperandMatchResultTy
1903 AMDGPUAsmParser::parseRegOrImmWithIntInputMods(OperandVector &Operands,
1907 if (getLexer().getKind() == AsmToken::Identifier &&
1908 Parser.getTok().getString() == "sext") {
1911 if (getLexer().isNot(AsmToken::LParen)) {
1912 Error(Parser.getTok().getLoc(), "expected left paren after sext");
1913 return MatchOperand_ParseFail;
1918 OperandMatchResultTy Res;
1920 Res = parseRegOrImm(Operands);
1922 Res = parseReg(Operands);
1924 if (Res != MatchOperand_Success) {
1928 AMDGPUOperand::Modifiers Mods;
1930 if (getLexer().isNot(AsmToken::RParen)) {
1931 Error(Parser.getTok().getLoc(), "expected closing parentheses");
1932 return MatchOperand_ParseFail;
1938 if (Mods.hasIntModifiers()) {
1939 AMDGPUOperand &Op = static_cast<AMDGPUOperand &>(*Operands.back());
1940 Op.setModifiers(Mods);
1943 return MatchOperand_Success;
1946 OperandMatchResultTy
1947 AMDGPUAsmParser::parseRegWithFPInputMods(OperandVector &Operands) {
1948 return parseRegOrImmWithFPInputMods(Operands, false);
1951 OperandMatchResultTy
1952 AMDGPUAsmParser::parseRegWithIntInputMods(OperandVector &Operands) {
1953 return parseRegOrImmWithIntInputMods(Operands, false);
1956 OperandMatchResultTy AMDGPUAsmParser::parseVReg32OrOff(OperandVector &Operands) {
1957 std::unique_ptr<AMDGPUOperand> Reg = parseRegister();
1959 Operands.push_back(std::move(Reg));
1960 return MatchOperand_Success;
1963 const AsmToken &Tok = Parser.getTok();
1964 if (Tok.getString() == "off") {
1965 Operands.push_back(AMDGPUOperand::CreateImm(this, 0, Tok.getLoc(),
1966 AMDGPUOperand::ImmTyOff, false));
1968 return MatchOperand_Success;
1971 return MatchOperand_NoMatch;
1974 unsigned AMDGPUAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
1975 uint64_t TSFlags = MII.get(Inst.getOpcode()).TSFlags;
1977 if ((getForcedEncodingSize() == 32 && (TSFlags & SIInstrFlags::VOP3)) ||
1978 (getForcedEncodingSize() == 64 && !(TSFlags & SIInstrFlags::VOP3)) ||
1979 (isForcedDPP() && !(TSFlags & SIInstrFlags::DPP)) ||
1980 (isForcedSDWA() && !(TSFlags & SIInstrFlags::SDWA)) )
1981 return Match_InvalidOperand;
1983 if ((TSFlags & SIInstrFlags::VOP3) &&
1984 (TSFlags & SIInstrFlags::VOPAsmPrefer32Bit) &&
1985 getForcedEncodingSize() != 64)
1986 return Match_PreferE32;
1988 if (Inst.getOpcode() == AMDGPU::V_MAC_F32_sdwa_vi ||
1989 Inst.getOpcode() == AMDGPU::V_MAC_F16_sdwa_vi) {
1990 // v_mac_f32/16 allow only dst_sel == DWORD;
1992 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::dst_sel);
1993 const auto &Op = Inst.getOperand(OpNum);
1994 if (!Op.isImm() || Op.getImm() != AMDGPU::SDWA::SdwaSel::DWORD) {
1995 return Match_InvalidOperand;
1999 if ((TSFlags & SIInstrFlags::FLAT) && !hasFlatOffsets()) {
2000 // FIXME: Produces error without correct column reported.
2002 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::offset);
2003 const auto &Op = Inst.getOperand(OpNum);
2004 if (Op.getImm() != 0)
2005 return Match_InvalidOperand;
2008 return Match_Success;
2011 // What asm variants we should check
2012 ArrayRef<unsigned> AMDGPUAsmParser::getMatchedVariants() const {
2013 if (getForcedEncodingSize() == 32) {
2014 static const unsigned Variants[] = {AMDGPUAsmVariants::DEFAULT};
2015 return makeArrayRef(Variants);
2018 if (isForcedVOP3()) {
2019 static const unsigned Variants[] = {AMDGPUAsmVariants::VOP3};
2020 return makeArrayRef(Variants);
2023 if (isForcedSDWA()) {
2024 static const unsigned Variants[] = {AMDGPUAsmVariants::SDWA,
2025 AMDGPUAsmVariants::SDWA9};
2026 return makeArrayRef(Variants);
2029 if (isForcedDPP()) {
2030 static const unsigned Variants[] = {AMDGPUAsmVariants::DPP};
2031 return makeArrayRef(Variants);
2034 static const unsigned Variants[] = {
2035 AMDGPUAsmVariants::DEFAULT, AMDGPUAsmVariants::VOP3,
2036 AMDGPUAsmVariants::SDWA, AMDGPUAsmVariants::SDWA9, AMDGPUAsmVariants::DPP
2039 return makeArrayRef(Variants);
2042 unsigned AMDGPUAsmParser::findImplicitSGPRReadInVOP(const MCInst &Inst) const {
2043 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
2044 const unsigned Num = Desc.getNumImplicitUses();
2045 for (unsigned i = 0; i < Num; ++i) {
2046 unsigned Reg = Desc.ImplicitUses[i];
2048 case AMDGPU::FLAT_SCR:
2056 return AMDGPU::NoRegister;
2059 // NB: This code is correct only when used to check constant
2060 // bus limitations because GFX7 support no f16 inline constants.
2061 // Note that there are no cases when a GFX7 opcode violates
2062 // constant bus limitations due to the use of an f16 constant.
2063 bool AMDGPUAsmParser::isInlineConstant(const MCInst &Inst,
2064 unsigned OpIdx) const {
2065 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
2067 if (!AMDGPU::isSISrcOperand(Desc, OpIdx)) {
2071 const MCOperand &MO = Inst.getOperand(OpIdx);
2073 int64_t Val = MO.getImm();
2074 auto OpSize = AMDGPU::getOperandSize(Desc, OpIdx);
2076 switch (OpSize) { // expected operand size
2078 return AMDGPU::isInlinableLiteral64(Val, hasInv2PiInlineImm());
2080 return AMDGPU::isInlinableLiteral32(Val, hasInv2PiInlineImm());
2082 const unsigned OperandType = Desc.OpInfo[OpIdx].OperandType;
2083 if (OperandType == AMDGPU::OPERAND_REG_INLINE_C_V2INT16 ||
2084 OperandType == AMDGPU::OPERAND_REG_INLINE_C_V2FP16) {
2085 return AMDGPU::isInlinableLiteralV216(Val, hasInv2PiInlineImm());
2087 return AMDGPU::isInlinableLiteral16(Val, hasInv2PiInlineImm());
2091 llvm_unreachable("invalid operand size");
2095 bool AMDGPUAsmParser::usesConstantBus(const MCInst &Inst, unsigned OpIdx) {
2096 const MCOperand &MO = Inst.getOperand(OpIdx);
2098 return !isInlineConstant(Inst, OpIdx);
2100 return !MO.isReg() ||
2101 isSGPR(mc2PseudoReg(MO.getReg()), getContext().getRegisterInfo());
2104 bool AMDGPUAsmParser::validateConstantBusLimitations(const MCInst &Inst) {
2105 const unsigned Opcode = Inst.getOpcode();
2106 const MCInstrDesc &Desc = MII.get(Opcode);
2107 unsigned ConstantBusUseCount = 0;
2110 (SIInstrFlags::VOPC |
2111 SIInstrFlags::VOP1 | SIInstrFlags::VOP2 |
2112 SIInstrFlags::VOP3 | SIInstrFlags::VOP3P |
2113 SIInstrFlags::SDWA)) {
2115 // Check special imm operands (used by madmk, etc)
2116 if (AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::imm) != -1) {
2117 ++ConstantBusUseCount;
2120 unsigned SGPRUsed = findImplicitSGPRReadInVOP(Inst);
2121 if (SGPRUsed != AMDGPU::NoRegister) {
2122 ++ConstantBusUseCount;
2125 const int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
2126 const int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
2127 const int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
2129 const int OpIndices[] = { Src0Idx, Src1Idx, Src2Idx };
2131 for (int OpIdx : OpIndices) {
2132 if (OpIdx == -1) break;
2134 const MCOperand &MO = Inst.getOperand(OpIdx);
2135 if (usesConstantBus(Inst, OpIdx)) {
2137 const unsigned Reg = mc2PseudoReg(MO.getReg());
2138 // Pairs of registers with a partial intersections like these
2140 // flat_scratch_lo, flat_scratch
2141 // flat_scratch_lo, flat_scratch_hi
2142 // are theoretically valid but they are disabled anyway.
2143 // Note that this code mimics SIInstrInfo::verifyInstruction
2144 if (Reg != SGPRUsed) {
2145 ++ConstantBusUseCount;
2148 } else { // Expression or a literal
2149 ++ConstantBusUseCount;
2155 return ConstantBusUseCount <= 1;
2158 bool AMDGPUAsmParser::validateEarlyClobberLimitations(const MCInst &Inst) {
2160 const unsigned Opcode = Inst.getOpcode();
2161 const MCInstrDesc &Desc = MII.get(Opcode);
2163 const int DstIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdst);
2165 Desc.getOperandConstraint(DstIdx, MCOI::EARLY_CLOBBER) == -1) {
2169 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
2171 const int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
2172 const int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
2173 const int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
2175 assert(DstIdx != -1);
2176 const MCOperand &Dst = Inst.getOperand(DstIdx);
2177 assert(Dst.isReg());
2178 const unsigned DstReg = mc2PseudoReg(Dst.getReg());
2180 const int SrcIndices[] = { Src0Idx, Src1Idx, Src2Idx };
2182 for (int SrcIdx : SrcIndices) {
2183 if (SrcIdx == -1) break;
2184 const MCOperand &Src = Inst.getOperand(SrcIdx);
2186 const unsigned SrcReg = mc2PseudoReg(Src.getReg());
2187 if (isRegIntersect(DstReg, SrcReg, TRI)) {
2196 bool AMDGPUAsmParser::validateInstruction(const MCInst &Inst,
2197 const SMLoc &IDLoc) {
2198 if (!validateConstantBusLimitations(Inst)) {
2200 "invalid operand (violates constant bus restrictions)");
2203 if (!validateEarlyClobberLimitations(Inst)) {
2205 "destination must be different than all sources");
2212 bool AMDGPUAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2213 OperandVector &Operands,
2215 uint64_t &ErrorInfo,
2216 bool MatchingInlineAsm) {
2218 unsigned Result = Match_Success;
2219 for (auto Variant : getMatchedVariants()) {
2221 auto R = MatchInstructionImpl(Operands, Inst, EI, MatchingInlineAsm,
2223 // We order match statuses from least to most specific. We use most specific
2224 // status as resulting
2225 // Match_MnemonicFail < Match_InvalidOperand < Match_MissingFeature < Match_PreferE32
2226 if ((R == Match_Success) ||
2227 (R == Match_PreferE32) ||
2228 (R == Match_MissingFeature && Result != Match_PreferE32) ||
2229 (R == Match_InvalidOperand && Result != Match_MissingFeature
2230 && Result != Match_PreferE32) ||
2231 (R == Match_MnemonicFail && Result != Match_InvalidOperand
2232 && Result != Match_MissingFeature
2233 && Result != Match_PreferE32)) {
2237 if (R == Match_Success)
2244 if (!validateInstruction(Inst, IDLoc)) {
2248 Out.EmitInstruction(Inst, getSTI());
2251 case Match_MissingFeature:
2252 return Error(IDLoc, "instruction not supported on this GPU");
2254 case Match_MnemonicFail:
2255 return Error(IDLoc, "unrecognized instruction mnemonic");
2257 case Match_InvalidOperand: {
2258 SMLoc ErrorLoc = IDLoc;
2259 if (ErrorInfo != ~0ULL) {
2260 if (ErrorInfo >= Operands.size()) {
2261 return Error(IDLoc, "too few operands for instruction");
2263 ErrorLoc = ((AMDGPUOperand &)*Operands[ErrorInfo]).getStartLoc();
2264 if (ErrorLoc == SMLoc())
2267 return Error(ErrorLoc, "invalid operand for instruction");
2270 case Match_PreferE32:
2271 return Error(IDLoc, "internal error: instruction without _e64 suffix "
2272 "should be encoded as e32");
2274 llvm_unreachable("Implement any new match types added!");
2277 bool AMDGPUAsmParser::ParseAsAbsoluteExpression(uint32_t &Ret) {
2279 if (getLexer().isNot(AsmToken::Integer) && getLexer().isNot(AsmToken::Identifier)) {
2282 if (getParser().parseAbsoluteExpression(Tmp)) {
2285 Ret = static_cast<uint32_t>(Tmp);
2289 bool AMDGPUAsmParser::ParseDirectiveMajorMinor(uint32_t &Major,
2291 if (ParseAsAbsoluteExpression(Major))
2292 return TokError("invalid major version");
2294 if (getLexer().isNot(AsmToken::Comma))
2295 return TokError("minor version number required, comma expected");
2298 if (ParseAsAbsoluteExpression(Minor))
2299 return TokError("invalid minor version");
2304 bool AMDGPUAsmParser::ParseDirectiveHSACodeObjectVersion() {
2308 if (ParseDirectiveMajorMinor(Major, Minor))
2311 getTargetStreamer().EmitDirectiveHSACodeObjectVersion(Major, Minor);
2315 bool AMDGPUAsmParser::ParseDirectiveHSACodeObjectISA() {
2319 StringRef VendorName;
2322 // If this directive has no arguments, then use the ISA version for the
2324 if (getLexer().is(AsmToken::EndOfStatement)) {
2325 AMDGPU::IsaInfo::IsaVersion ISA =
2326 AMDGPU::IsaInfo::getIsaVersion(getFeatureBits());
2327 getTargetStreamer().EmitDirectiveHSACodeObjectISA(ISA.Major, ISA.Minor,
2333 if (ParseDirectiveMajorMinor(Major, Minor))
2336 if (getLexer().isNot(AsmToken::Comma))
2337 return TokError("stepping version number required, comma expected");
2340 if (ParseAsAbsoluteExpression(Stepping))
2341 return TokError("invalid stepping version");
2343 if (getLexer().isNot(AsmToken::Comma))
2344 return TokError("vendor name required, comma expected");
2347 if (getLexer().isNot(AsmToken::String))
2348 return TokError("invalid vendor name");
2350 VendorName = getLexer().getTok().getStringContents();
2353 if (getLexer().isNot(AsmToken::Comma))
2354 return TokError("arch name required, comma expected");
2357 if (getLexer().isNot(AsmToken::String))
2358 return TokError("invalid arch name");
2360 ArchName = getLexer().getTok().getStringContents();
2363 getTargetStreamer().EmitDirectiveHSACodeObjectISA(Major, Minor, Stepping,
2364 VendorName, ArchName);
2368 bool AMDGPUAsmParser::ParseDirectiveCodeObjectMetadata() {
2369 std::string YamlString;
2370 raw_string_ostream YamlStream(YamlString);
2372 getLexer().setSkipSpace(false);
2374 bool FoundEnd = false;
2375 while (!getLexer().is(AsmToken::Eof)) {
2376 while (getLexer().is(AsmToken::Space)) {
2377 YamlStream << getLexer().getTok().getString();
2381 if (getLexer().is(AsmToken::Identifier)) {
2382 StringRef ID = getLexer().getTok().getIdentifier();
2383 if (ID == AMDGPU::CodeObject::MetadataAssemblerDirectiveEnd) {
2390 YamlStream << Parser.parseStringToEndOfStatement()
2391 << getContext().getAsmInfo()->getSeparatorString();
2393 Parser.eatToEndOfStatement();
2396 getLexer().setSkipSpace(true);
2398 if (getLexer().is(AsmToken::Eof) && !FoundEnd) {
2400 "expected directive .end_amdgpu_code_object_metadata not found");
2405 if (!getTargetStreamer().EmitCodeObjectMetadata(YamlString))
2406 return Error(getParser().getTok().getLoc(), "invalid code object metadata");
2411 bool AMDGPUAsmParser::ParseAMDKernelCodeTValue(StringRef ID,
2412 amd_kernel_code_t &Header) {
2413 SmallString<40> ErrStr;
2414 raw_svector_ostream Err(ErrStr);
2415 if (!parseAmdKernelCodeField(ID, getParser(), Header, Err)) {
2416 return TokError(Err.str());
2422 bool AMDGPUAsmParser::ParseDirectiveAMDKernelCodeT() {
2423 amd_kernel_code_t Header;
2424 AMDGPU::initDefaultAMDKernelCodeT(Header, getFeatureBits());
2427 // Lex EndOfStatement. This is in a while loop, because lexing a comment
2428 // will set the current token to EndOfStatement.
2429 while(getLexer().is(AsmToken::EndOfStatement))
2432 if (getLexer().isNot(AsmToken::Identifier))
2433 return TokError("expected value identifier or .end_amd_kernel_code_t");
2435 StringRef ID = getLexer().getTok().getIdentifier();
2438 if (ID == ".end_amd_kernel_code_t")
2441 if (ParseAMDKernelCodeTValue(ID, Header))
2445 getTargetStreamer().EmitAMDKernelCodeT(Header);
2450 bool AMDGPUAsmParser::ParseDirectiveAMDGPUHsaKernel() {
2451 if (getLexer().isNot(AsmToken::Identifier))
2452 return TokError("expected symbol name");
2454 StringRef KernelName = Parser.getTok().getString();
2456 getTargetStreamer().EmitAMDGPUSymbolType(KernelName,
2457 ELF::STT_AMDGPU_HSA_KERNEL);
2459 KernelScope.initialize(getContext());
2463 bool AMDGPUAsmParser::ParseDirective(AsmToken DirectiveID) {
2464 StringRef IDVal = DirectiveID.getString();
2466 if (IDVal == ".hsa_code_object_version")
2467 return ParseDirectiveHSACodeObjectVersion();
2469 if (IDVal == ".hsa_code_object_isa")
2470 return ParseDirectiveHSACodeObjectISA();
2472 if (IDVal == AMDGPU::CodeObject::MetadataAssemblerDirectiveBegin)
2473 return ParseDirectiveCodeObjectMetadata();
2475 if (IDVal == ".amd_kernel_code_t")
2476 return ParseDirectiveAMDKernelCodeT();
2478 if (IDVal == ".amdgpu_hsa_kernel")
2479 return ParseDirectiveAMDGPUHsaKernel();
2484 bool AMDGPUAsmParser::subtargetHasRegister(const MCRegisterInfo &MRI,
2485 unsigned RegNo) const {
2492 case AMDGPU::FLAT_SCR:
2493 case AMDGPU::FLAT_SCR_LO:
2494 case AMDGPU::FLAT_SCR_HI:
2501 // VI only has 102 SGPRs, so make sure we aren't trying to use the 2 more that
2503 for (MCRegAliasIterator R(AMDGPU::SGPR102_SGPR103, &MRI, true);
2512 OperandMatchResultTy
2513 AMDGPUAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
2514 // Try to parse with a custom parser
2515 OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
2517 // If we successfully parsed the operand or if there as an error parsing,
2520 // If we are parsing after we reach EndOfStatement then this means we
2521 // are appending default values to the Operands list. This is only done
2522 // by custom parser, so we shouldn't continue on to the generic parsing.
2523 if (ResTy == MatchOperand_Success || ResTy == MatchOperand_ParseFail ||
2524 getLexer().is(AsmToken::EndOfStatement))
2527 ResTy = parseRegOrImm(Operands);
2529 if (ResTy == MatchOperand_Success)
2532 if (getLexer().getKind() == AsmToken::Identifier) {
2533 // If this identifier is a symbol, we want to create an expression for it.
2534 // It is a little difficult to distinguish between a symbol name, and
2535 // an instruction flag like 'gds'. In order to do this, we parse
2536 // all tokens as expressions and then treate the symbol name as the token
2537 // string when we want to interpret the operand as a token.
2538 const auto &Tok = Parser.getTok();
2539 SMLoc S = Tok.getLoc();
2540 const MCExpr *Expr = nullptr;
2541 if (!Parser.parseExpression(Expr)) {
2542 Operands.push_back(AMDGPUOperand::CreateExpr(this, Expr, S));
2543 return MatchOperand_Success;
2546 Operands.push_back(AMDGPUOperand::CreateToken(this, Tok.getString(), Tok.getLoc()));
2548 return MatchOperand_Success;
2550 return MatchOperand_NoMatch;
2553 StringRef AMDGPUAsmParser::parseMnemonicSuffix(StringRef Name) {
2554 // Clear any forced encodings from the previous instruction.
2555 setForcedEncodingSize(0);
2556 setForcedDPP(false);
2557 setForcedSDWA(false);
2559 if (Name.endswith("_e64")) {
2560 setForcedEncodingSize(64);
2561 return Name.substr(0, Name.size() - 4);
2562 } else if (Name.endswith("_e32")) {
2563 setForcedEncodingSize(32);
2564 return Name.substr(0, Name.size() - 4);
2565 } else if (Name.endswith("_dpp")) {
2567 return Name.substr(0, Name.size() - 4);
2568 } else if (Name.endswith("_sdwa")) {
2569 setForcedSDWA(true);
2570 return Name.substr(0, Name.size() - 5);
2575 bool AMDGPUAsmParser::ParseInstruction(ParseInstructionInfo &Info,
2577 SMLoc NameLoc, OperandVector &Operands) {
2578 // Add the instruction mnemonic
2579 Name = parseMnemonicSuffix(Name);
2580 Operands.push_back(AMDGPUOperand::CreateToken(this, Name, NameLoc));
2582 while (!getLexer().is(AsmToken::EndOfStatement)) {
2583 OperandMatchResultTy Res = parseOperand(Operands, Name);
2585 // Eat the comma or space if there is one.
2586 if (getLexer().is(AsmToken::Comma))
2590 case MatchOperand_Success: break;
2591 case MatchOperand_ParseFail:
2592 Error(getLexer().getLoc(), "failed parsing operand.");
2593 while (!getLexer().is(AsmToken::EndOfStatement)) {
2597 case MatchOperand_NoMatch:
2598 Error(getLexer().getLoc(), "not a valid operand.");
2599 while (!getLexer().is(AsmToken::EndOfStatement)) {
2609 //===----------------------------------------------------------------------===//
2610 // Utility functions
2611 //===----------------------------------------------------------------------===//
2613 OperandMatchResultTy
2614 AMDGPUAsmParser::parseIntWithPrefix(const char *Prefix, int64_t &Int) {
2615 switch(getLexer().getKind()) {
2616 default: return MatchOperand_NoMatch;
2617 case AsmToken::Identifier: {
2618 StringRef Name = Parser.getTok().getString();
2619 if (!Name.equals(Prefix)) {
2620 return MatchOperand_NoMatch;
2624 if (getLexer().isNot(AsmToken::Colon))
2625 return MatchOperand_ParseFail;
2629 bool IsMinus = false;
2630 if (getLexer().getKind() == AsmToken::Minus) {
2635 if (getLexer().isNot(AsmToken::Integer))
2636 return MatchOperand_ParseFail;
2638 if (getParser().parseAbsoluteExpression(Int))
2639 return MatchOperand_ParseFail;
2646 return MatchOperand_Success;
2649 OperandMatchResultTy
2650 AMDGPUAsmParser::parseIntWithPrefix(const char *Prefix, OperandVector &Operands,
2651 AMDGPUOperand::ImmTy ImmTy,
2652 bool (*ConvertResult)(int64_t&)) {
2653 SMLoc S = Parser.getTok().getLoc();
2656 OperandMatchResultTy Res = parseIntWithPrefix(Prefix, Value);
2657 if (Res != MatchOperand_Success)
2660 if (ConvertResult && !ConvertResult(Value)) {
2661 return MatchOperand_ParseFail;
2664 Operands.push_back(AMDGPUOperand::CreateImm(this, Value, S, ImmTy));
2665 return MatchOperand_Success;
2668 OperandMatchResultTy AMDGPUAsmParser::parseOperandArrayWithPrefix(
2670 OperandVector &Operands,
2671 AMDGPUOperand::ImmTy ImmTy,
2672 bool (*ConvertResult)(int64_t&)) {
2673 StringRef Name = Parser.getTok().getString();
2674 if (!Name.equals(Prefix))
2675 return MatchOperand_NoMatch;
2678 if (getLexer().isNot(AsmToken::Colon))
2679 return MatchOperand_ParseFail;
2682 if (getLexer().isNot(AsmToken::LBrac))
2683 return MatchOperand_ParseFail;
2687 SMLoc S = Parser.getTok().getLoc();
2689 // FIXME: How to verify the number of elements matches the number of src
2691 for (int I = 0; I < 3; ++I) {
2693 if (getLexer().is(AsmToken::RBrac))
2696 if (getLexer().isNot(AsmToken::Comma))
2697 return MatchOperand_ParseFail;
2701 if (getLexer().isNot(AsmToken::Integer))
2702 return MatchOperand_ParseFail;
2705 if (getParser().parseAbsoluteExpression(Op))
2706 return MatchOperand_ParseFail;
2708 if (Op != 0 && Op != 1)
2709 return MatchOperand_ParseFail;
2714 Operands.push_back(AMDGPUOperand::CreateImm(this, Val, S, ImmTy));
2715 return MatchOperand_Success;
2718 OperandMatchResultTy
2719 AMDGPUAsmParser::parseNamedBit(const char *Name, OperandVector &Operands,
2720 AMDGPUOperand::ImmTy ImmTy) {
2722 SMLoc S = Parser.getTok().getLoc();
2724 // We are at the end of the statement, and this is a default argument, so
2725 // use a default value.
2726 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2727 switch(getLexer().getKind()) {
2728 case AsmToken::Identifier: {
2729 StringRef Tok = Parser.getTok().getString();
2733 } else if (Tok.startswith("no") && Tok.endswith(Name)) {
2737 return MatchOperand_NoMatch;
2742 return MatchOperand_NoMatch;
2746 Operands.push_back(AMDGPUOperand::CreateImm(this, Bit, S, ImmTy));
2747 return MatchOperand_Success;
2750 static void addOptionalImmOperand(
2751 MCInst& Inst, const OperandVector& Operands,
2752 AMDGPUAsmParser::OptionalImmIndexMap& OptionalIdx,
2753 AMDGPUOperand::ImmTy ImmT,
2754 int64_t Default = 0) {
2755 auto i = OptionalIdx.find(ImmT);
2756 if (i != OptionalIdx.end()) {
2757 unsigned Idx = i->second;
2758 ((AMDGPUOperand &)*Operands[Idx]).addImmOperands(Inst, 1);
2760 Inst.addOperand(MCOperand::createImm(Default));
2764 OperandMatchResultTy
2765 AMDGPUAsmParser::parseStringWithPrefix(StringRef Prefix, StringRef &Value) {
2766 if (getLexer().isNot(AsmToken::Identifier)) {
2767 return MatchOperand_NoMatch;
2769 StringRef Tok = Parser.getTok().getString();
2770 if (Tok != Prefix) {
2771 return MatchOperand_NoMatch;
2775 if (getLexer().isNot(AsmToken::Colon)) {
2776 return MatchOperand_ParseFail;
2780 if (getLexer().isNot(AsmToken::Identifier)) {
2781 return MatchOperand_ParseFail;
2784 Value = Parser.getTok().getString();
2785 return MatchOperand_Success;
2788 //===----------------------------------------------------------------------===//
2790 //===----------------------------------------------------------------------===//
2792 void AMDGPUAsmParser::cvtDSOffset01(MCInst &Inst,
2793 const OperandVector &Operands) {
2794 OptionalImmIndexMap OptionalIdx;
2796 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
2797 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
2799 // Add the register arguments
2801 Op.addRegOperands(Inst, 1);
2805 // Handle optional arguments
2806 OptionalIdx[Op.getImmTy()] = i;
2809 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyOffset0);
2810 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyOffset1);
2811 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyGDS);
2813 Inst.addOperand(MCOperand::createReg(AMDGPU::M0)); // m0
2816 void AMDGPUAsmParser::cvtDSImpl(MCInst &Inst, const OperandVector &Operands,
2817 bool IsGdsHardcoded) {
2818 OptionalImmIndexMap OptionalIdx;
2820 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
2821 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
2823 // Add the register arguments
2825 Op.addRegOperands(Inst, 1);
2829 if (Op.isToken() && Op.getToken() == "gds") {
2830 IsGdsHardcoded = true;
2834 // Handle optional arguments
2835 OptionalIdx[Op.getImmTy()] = i;
2838 AMDGPUOperand::ImmTy OffsetType =
2839 (Inst.getOpcode() == AMDGPU::DS_SWIZZLE_B32_si ||
2840 Inst.getOpcode() == AMDGPU::DS_SWIZZLE_B32_vi) ? AMDGPUOperand::ImmTySwizzle :
2841 AMDGPUOperand::ImmTyOffset;
2843 addOptionalImmOperand(Inst, Operands, OptionalIdx, OffsetType);
2845 if (!IsGdsHardcoded) {
2846 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyGDS);
2848 Inst.addOperand(MCOperand::createReg(AMDGPU::M0)); // m0
2851 void AMDGPUAsmParser::cvtExp(MCInst &Inst, const OperandVector &Operands) {
2852 OptionalImmIndexMap OptionalIdx;
2854 unsigned OperandIdx[4];
2855 unsigned EnMask = 0;
2858 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
2859 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
2861 // Add the register arguments
2864 OperandIdx[SrcIdx] = Inst.size();
2865 Op.addRegOperands(Inst, 1);
2872 OperandIdx[SrcIdx] = Inst.size();
2873 Inst.addOperand(MCOperand::createReg(AMDGPU::NoRegister));
2878 if (Op.isImm() && Op.getImmTy() == AMDGPUOperand::ImmTyExpTgt) {
2879 Op.addImmOperands(Inst, 1);
2883 if (Op.isToken() && Op.getToken() == "done")
2886 // Handle optional arguments
2887 OptionalIdx[Op.getImmTy()] = i;
2890 assert(SrcIdx == 4);
2893 if (OptionalIdx.find(AMDGPUOperand::ImmTyExpCompr) != OptionalIdx.end()) {
2895 Inst.getOperand(OperandIdx[1]) = Inst.getOperand(OperandIdx[2]);
2896 Inst.getOperand(OperandIdx[2]).setReg(AMDGPU::NoRegister);
2897 Inst.getOperand(OperandIdx[3]).setReg(AMDGPU::NoRegister);
2900 for (auto i = 0; i < SrcIdx; ++i) {
2901 if (Inst.getOperand(OperandIdx[i]).getReg() != AMDGPU::NoRegister) {
2902 EnMask |= Compr? (0x3 << i * 2) : (0x1 << i);
2906 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyExpVM);
2907 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyExpCompr);
2909 Inst.addOperand(MCOperand::createImm(EnMask));
2912 //===----------------------------------------------------------------------===//
2914 //===----------------------------------------------------------------------===//
2918 const AMDGPU::IsaInfo::IsaVersion ISA,
2922 unsigned (*encode)(const IsaInfo::IsaVersion &Version, unsigned, unsigned),
2923 unsigned (*decode)(const IsaInfo::IsaVersion &Version, unsigned))
2925 bool Failed = false;
2927 IntVal = encode(ISA, IntVal, CntVal);
2928 if (CntVal != decode(ISA, IntVal)) {
2930 IntVal = encode(ISA, IntVal, -1);
2938 bool AMDGPUAsmParser::parseCnt(int64_t &IntVal) {
2939 StringRef CntName = Parser.getTok().getString();
2943 if (getLexer().isNot(AsmToken::LParen))
2947 if (getLexer().isNot(AsmToken::Integer))
2950 SMLoc ValLoc = Parser.getTok().getLoc();
2951 if (getParser().parseAbsoluteExpression(CntVal))
2954 AMDGPU::IsaInfo::IsaVersion ISA =
2955 AMDGPU::IsaInfo::getIsaVersion(getFeatureBits());
2958 bool Sat = CntName.endswith("_sat");
2960 if (CntName == "vmcnt" || CntName == "vmcnt_sat") {
2961 Failed = encodeCnt(ISA, IntVal, CntVal, Sat, encodeVmcnt, decodeVmcnt);
2962 } else if (CntName == "expcnt" || CntName == "expcnt_sat") {
2963 Failed = encodeCnt(ISA, IntVal, CntVal, Sat, encodeExpcnt, decodeExpcnt);
2964 } else if (CntName == "lgkmcnt" || CntName == "lgkmcnt_sat") {
2965 Failed = encodeCnt(ISA, IntVal, CntVal, Sat, encodeLgkmcnt, decodeLgkmcnt);
2969 Error(ValLoc, "too large value for " + CntName);
2973 if (getLexer().isNot(AsmToken::RParen)) {
2978 if (getLexer().is(AsmToken::Amp) || getLexer().is(AsmToken::Comma)) {
2979 const AsmToken NextToken = getLexer().peekTok();
2980 if (NextToken.is(AsmToken::Identifier)) {
2988 OperandMatchResultTy
2989 AMDGPUAsmParser::parseSWaitCntOps(OperandVector &Operands) {
2990 AMDGPU::IsaInfo::IsaVersion ISA =
2991 AMDGPU::IsaInfo::getIsaVersion(getFeatureBits());
2992 int64_t Waitcnt = getWaitcntBitMask(ISA);
2993 SMLoc S = Parser.getTok().getLoc();
2995 switch(getLexer().getKind()) {
2996 default: return MatchOperand_ParseFail;
2997 case AsmToken::Integer:
2998 // The operand can be an integer value.
2999 if (getParser().parseAbsoluteExpression(Waitcnt))
3000 return MatchOperand_ParseFail;
3003 case AsmToken::Identifier:
3005 if (parseCnt(Waitcnt))
3006 return MatchOperand_ParseFail;
3007 } while(getLexer().isNot(AsmToken::EndOfStatement));
3010 Operands.push_back(AMDGPUOperand::CreateImm(this, Waitcnt, S));
3011 return MatchOperand_Success;
3014 bool AMDGPUAsmParser::parseHwregConstruct(OperandInfoTy &HwReg, int64_t &Offset,
3016 using namespace llvm::AMDGPU::Hwreg;
3018 if (Parser.getTok().getString() != "hwreg")
3022 if (getLexer().isNot(AsmToken::LParen))
3026 if (getLexer().is(AsmToken::Identifier)) {
3027 HwReg.IsSymbolic = true;
3028 HwReg.Id = ID_UNKNOWN_;
3029 const StringRef tok = Parser.getTok().getString();
3030 for (int i = ID_SYMBOLIC_FIRST_; i < ID_SYMBOLIC_LAST_; ++i) {
3031 if (tok == IdSymbolic[i]) {
3038 HwReg.IsSymbolic = false;
3039 if (getLexer().isNot(AsmToken::Integer))
3041 if (getParser().parseAbsoluteExpression(HwReg.Id))
3045 if (getLexer().is(AsmToken::RParen)) {
3051 if (getLexer().isNot(AsmToken::Comma))
3055 if (getLexer().isNot(AsmToken::Integer))
3057 if (getParser().parseAbsoluteExpression(Offset))
3060 if (getLexer().isNot(AsmToken::Comma))
3064 if (getLexer().isNot(AsmToken::Integer))
3066 if (getParser().parseAbsoluteExpression(Width))
3069 if (getLexer().isNot(AsmToken::RParen))
3076 OperandMatchResultTy AMDGPUAsmParser::parseHwreg(OperandVector &Operands) {
3077 using namespace llvm::AMDGPU::Hwreg;
3079 int64_t Imm16Val = 0;
3080 SMLoc S = Parser.getTok().getLoc();
3082 switch(getLexer().getKind()) {
3083 default: return MatchOperand_NoMatch;
3084 case AsmToken::Integer:
3085 // The operand can be an integer value.
3086 if (getParser().parseAbsoluteExpression(Imm16Val))
3087 return MatchOperand_NoMatch;
3088 if (Imm16Val < 0 || !isUInt<16>(Imm16Val)) {
3089 Error(S, "invalid immediate: only 16-bit values are legal");
3090 // Do not return error code, but create an imm operand anyway and proceed
3091 // to the next operand, if any. That avoids unneccessary error messages.
3095 case AsmToken::Identifier: {
3096 OperandInfoTy HwReg(ID_UNKNOWN_);
3097 int64_t Offset = OFFSET_DEFAULT_;
3098 int64_t Width = WIDTH_M1_DEFAULT_ + 1;
3099 if (parseHwregConstruct(HwReg, Offset, Width))
3100 return MatchOperand_ParseFail;
3101 if (HwReg.Id < 0 || !isUInt<ID_WIDTH_>(HwReg.Id)) {
3102 if (HwReg.IsSymbolic)
3103 Error(S, "invalid symbolic name of hardware register");
3105 Error(S, "invalid code of hardware register: only 6-bit values are legal");
3107 if (Offset < 0 || !isUInt<OFFSET_WIDTH_>(Offset))
3108 Error(S, "invalid bit offset: only 5-bit values are legal");
3109 if ((Width-1) < 0 || !isUInt<WIDTH_M1_WIDTH_>(Width-1))
3110 Error(S, "invalid bitfield width: only values from 1 to 32 are legal");
3111 Imm16Val = (HwReg.Id << ID_SHIFT_) | (Offset << OFFSET_SHIFT_) | ((Width-1) << WIDTH_M1_SHIFT_);
3115 Operands.push_back(AMDGPUOperand::CreateImm(this, Imm16Val, S, AMDGPUOperand::ImmTyHwreg));
3116 return MatchOperand_Success;
3119 bool AMDGPUOperand::isSWaitCnt() const {
3123 bool AMDGPUOperand::isHwreg() const {
3124 return isImmTy(ImmTyHwreg);
3127 bool AMDGPUAsmParser::parseSendMsgConstruct(OperandInfoTy &Msg, OperandInfoTy &Operation, int64_t &StreamId) {
3128 using namespace llvm::AMDGPU::SendMsg;
3130 if (Parser.getTok().getString() != "sendmsg")
3134 if (getLexer().isNot(AsmToken::LParen))
3138 if (getLexer().is(AsmToken::Identifier)) {
3139 Msg.IsSymbolic = true;
3140 Msg.Id = ID_UNKNOWN_;
3141 const std::string tok = Parser.getTok().getString();
3142 for (int i = ID_GAPS_FIRST_; i < ID_GAPS_LAST_; ++i) {
3144 default: continue; // Omit gaps.
3145 case ID_INTERRUPT: case ID_GS: case ID_GS_DONE: case ID_SYSMSG: break;
3147 if (tok == IdSymbolic[i]) {
3154 Msg.IsSymbolic = false;
3155 if (getLexer().isNot(AsmToken::Integer))
3157 if (getParser().parseAbsoluteExpression(Msg.Id))
3159 if (getLexer().is(AsmToken::Integer))
3160 if (getParser().parseAbsoluteExpression(Msg.Id))
3161 Msg.Id = ID_UNKNOWN_;
3163 if (Msg.Id == ID_UNKNOWN_) // Don't know how to parse the rest.
3166 if (!(Msg.Id == ID_GS || Msg.Id == ID_GS_DONE || Msg.Id == ID_SYSMSG)) {
3167 if (getLexer().isNot(AsmToken::RParen))
3173 if (getLexer().isNot(AsmToken::Comma))
3177 assert(Msg.Id == ID_GS || Msg.Id == ID_GS_DONE || Msg.Id == ID_SYSMSG);
3178 Operation.Id = ID_UNKNOWN_;
3179 if (getLexer().is(AsmToken::Identifier)) {
3180 Operation.IsSymbolic = true;
3181 const char* const *S = (Msg.Id == ID_SYSMSG) ? OpSysSymbolic : OpGsSymbolic;
3182 const int F = (Msg.Id == ID_SYSMSG) ? OP_SYS_FIRST_ : OP_GS_FIRST_;
3183 const int L = (Msg.Id == ID_SYSMSG) ? OP_SYS_LAST_ : OP_GS_LAST_;
3184 const StringRef Tok = Parser.getTok().getString();
3185 for (int i = F; i < L; ++i) {
3193 Operation.IsSymbolic = false;
3194 if (getLexer().isNot(AsmToken::Integer))
3196 if (getParser().parseAbsoluteExpression(Operation.Id))
3200 if ((Msg.Id == ID_GS || Msg.Id == ID_GS_DONE) && Operation.Id != OP_GS_NOP) {
3201 // Stream id is optional.
3202 if (getLexer().is(AsmToken::RParen)) {
3207 if (getLexer().isNot(AsmToken::Comma))
3211 if (getLexer().isNot(AsmToken::Integer))
3213 if (getParser().parseAbsoluteExpression(StreamId))
3217 if (getLexer().isNot(AsmToken::RParen))
3223 OperandMatchResultTy AMDGPUAsmParser::parseInterpSlot(OperandVector &Operands) {
3224 if (getLexer().getKind() != AsmToken::Identifier)
3225 return MatchOperand_NoMatch;
3227 StringRef Str = Parser.getTok().getString();
3228 int Slot = StringSwitch<int>(Str)
3234 SMLoc S = Parser.getTok().getLoc();
3236 return MatchOperand_ParseFail;
3239 Operands.push_back(AMDGPUOperand::CreateImm(this, Slot, S,
3240 AMDGPUOperand::ImmTyInterpSlot));
3241 return MatchOperand_Success;
3244 OperandMatchResultTy AMDGPUAsmParser::parseInterpAttr(OperandVector &Operands) {
3245 if (getLexer().getKind() != AsmToken::Identifier)
3246 return MatchOperand_NoMatch;
3248 StringRef Str = Parser.getTok().getString();
3249 if (!Str.startswith("attr"))
3250 return MatchOperand_NoMatch;
3252 StringRef Chan = Str.take_back(2);
3253 int AttrChan = StringSwitch<int>(Chan)
3260 return MatchOperand_ParseFail;
3262 Str = Str.drop_back(2).drop_front(4);
3265 if (Str.getAsInteger(10, Attr))
3266 return MatchOperand_ParseFail;
3268 SMLoc S = Parser.getTok().getLoc();
3271 Error(S, "out of bounds attr");
3272 return MatchOperand_Success;
3275 SMLoc SChan = SMLoc::getFromPointer(Chan.data());
3277 Operands.push_back(AMDGPUOperand::CreateImm(this, Attr, S,
3278 AMDGPUOperand::ImmTyInterpAttr));
3279 Operands.push_back(AMDGPUOperand::CreateImm(this, AttrChan, SChan,
3280 AMDGPUOperand::ImmTyAttrChan));
3281 return MatchOperand_Success;
3284 void AMDGPUAsmParser::errorExpTgt() {
3285 Error(Parser.getTok().getLoc(), "invalid exp target");
3288 OperandMatchResultTy AMDGPUAsmParser::parseExpTgtImpl(StringRef Str,
3290 if (Str == "null") {
3292 return MatchOperand_Success;
3295 if (Str.startswith("mrt")) {
3296 Str = Str.drop_front(3);
3297 if (Str == "z") { // == mrtz
3299 return MatchOperand_Success;
3302 if (Str.getAsInteger(10, Val))
3303 return MatchOperand_ParseFail;
3308 return MatchOperand_Success;
3311 if (Str.startswith("pos")) {
3312 Str = Str.drop_front(3);
3313 if (Str.getAsInteger(10, Val))
3314 return MatchOperand_ParseFail;
3320 return MatchOperand_Success;
3323 if (Str.startswith("param")) {
3324 Str = Str.drop_front(5);
3325 if (Str.getAsInteger(10, Val))
3326 return MatchOperand_ParseFail;
3332 return MatchOperand_Success;
3335 if (Str.startswith("invalid_target_")) {
3336 Str = Str.drop_front(15);
3337 if (Str.getAsInteger(10, Val))
3338 return MatchOperand_ParseFail;
3341 return MatchOperand_Success;
3344 return MatchOperand_NoMatch;
3347 OperandMatchResultTy AMDGPUAsmParser::parseExpTgt(OperandVector &Operands) {
3349 StringRef Str = Parser.getTok().getString();
3351 auto Res = parseExpTgtImpl(Str, Val);
3352 if (Res != MatchOperand_Success)
3355 SMLoc S = Parser.getTok().getLoc();
3358 Operands.push_back(AMDGPUOperand::CreateImm(this, Val, S,
3359 AMDGPUOperand::ImmTyExpTgt));
3360 return MatchOperand_Success;
3363 OperandMatchResultTy
3364 AMDGPUAsmParser::parseSendMsgOp(OperandVector &Operands) {
3365 using namespace llvm::AMDGPU::SendMsg;
3367 int64_t Imm16Val = 0;
3368 SMLoc S = Parser.getTok().getLoc();
3370 switch(getLexer().getKind()) {
3372 return MatchOperand_NoMatch;
3373 case AsmToken::Integer:
3374 // The operand can be an integer value.
3375 if (getParser().parseAbsoluteExpression(Imm16Val))
3376 return MatchOperand_NoMatch;
3377 if (Imm16Val < 0 || !isUInt<16>(Imm16Val)) {
3378 Error(S, "invalid immediate: only 16-bit values are legal");
3379 // Do not return error code, but create an imm operand anyway and proceed
3380 // to the next operand, if any. That avoids unneccessary error messages.
3383 case AsmToken::Identifier: {
3384 OperandInfoTy Msg(ID_UNKNOWN_);
3385 OperandInfoTy Operation(OP_UNKNOWN_);
3386 int64_t StreamId = STREAM_ID_DEFAULT_;
3387 if (parseSendMsgConstruct(Msg, Operation, StreamId))
3388 return MatchOperand_ParseFail;
3390 // Validate and encode message ID.
3391 if (! ((ID_INTERRUPT <= Msg.Id && Msg.Id <= ID_GS_DONE)
3392 || Msg.Id == ID_SYSMSG)) {
3394 Error(S, "invalid/unsupported symbolic name of message");
3396 Error(S, "invalid/unsupported code of message");
3399 Imm16Val = (Msg.Id << ID_SHIFT_);
3400 // Validate and encode operation ID.
3401 if (Msg.Id == ID_GS || Msg.Id == ID_GS_DONE) {
3402 if (! (OP_GS_FIRST_ <= Operation.Id && Operation.Id < OP_GS_LAST_)) {
3403 if (Operation.IsSymbolic)
3404 Error(S, "invalid symbolic name of GS_OP");
3406 Error(S, "invalid code of GS_OP: only 2-bit values are legal");
3409 if (Operation.Id == OP_GS_NOP
3410 && Msg.Id != ID_GS_DONE) {
3411 Error(S, "invalid GS_OP: NOP is for GS_DONE only");
3414 Imm16Val |= (Operation.Id << OP_SHIFT_);
3416 if (Msg.Id == ID_SYSMSG) {
3417 if (! (OP_SYS_FIRST_ <= Operation.Id && Operation.Id < OP_SYS_LAST_)) {
3418 if (Operation.IsSymbolic)
3419 Error(S, "invalid/unsupported symbolic name of SYSMSG_OP");
3421 Error(S, "invalid/unsupported code of SYSMSG_OP");
3424 Imm16Val |= (Operation.Id << OP_SHIFT_);
3426 // Validate and encode stream ID.
3427 if ((Msg.Id == ID_GS || Msg.Id == ID_GS_DONE) && Operation.Id != OP_GS_NOP) {
3428 if (! (STREAM_ID_FIRST_ <= StreamId && StreamId < STREAM_ID_LAST_)) {
3429 Error(S, "invalid stream id: only 2-bit values are legal");
3432 Imm16Val |= (StreamId << STREAM_ID_SHIFT_);
3438 Operands.push_back(AMDGPUOperand::CreateImm(this, Imm16Val, S, AMDGPUOperand::ImmTySendMsg));
3439 return MatchOperand_Success;
3442 bool AMDGPUOperand::isSendMsg() const {
3443 return isImmTy(ImmTySendMsg);
3446 //===----------------------------------------------------------------------===//
3448 //===----------------------------------------------------------------------===//
3451 AMDGPUAsmParser::trySkipId(const StringRef Id) {
3452 if (getLexer().getKind() == AsmToken::Identifier &&
3453 Parser.getTok().getString() == Id) {
3461 AMDGPUAsmParser::trySkipToken(const AsmToken::TokenKind Kind) {
3462 if (getLexer().getKind() == Kind) {
3470 AMDGPUAsmParser::skipToken(const AsmToken::TokenKind Kind,
3471 const StringRef ErrMsg) {
3472 if (!trySkipToken(Kind)) {
3473 Error(Parser.getTok().getLoc(), ErrMsg);
3480 AMDGPUAsmParser::parseExpr(int64_t &Imm) {
3481 return !getParser().parseAbsoluteExpression(Imm);
3485 AMDGPUAsmParser::parseString(StringRef &Val, const StringRef ErrMsg) {
3486 SMLoc S = Parser.getTok().getLoc();
3487 if (getLexer().getKind() == AsmToken::String) {
3488 Val = Parser.getTok().getStringContents();
3497 //===----------------------------------------------------------------------===//
3499 //===----------------------------------------------------------------------===//
3503 encodeBitmaskPerm(const unsigned AndMask,
3504 const unsigned OrMask,
3505 const unsigned XorMask) {
3506 using namespace llvm::AMDGPU::Swizzle;
3508 return BITMASK_PERM_ENC |
3509 (AndMask << BITMASK_AND_SHIFT) |
3510 (OrMask << BITMASK_OR_SHIFT) |
3511 (XorMask << BITMASK_XOR_SHIFT);
3515 AMDGPUAsmParser::parseSwizzleOperands(const unsigned OpNum, int64_t* Op,
3516 const unsigned MinVal,
3517 const unsigned MaxVal,
3518 const StringRef ErrMsg) {
3519 for (unsigned i = 0; i < OpNum; ++i) {
3520 if (!skipToken(AsmToken::Comma, "expected a comma")){
3523 SMLoc ExprLoc = Parser.getTok().getLoc();
3524 if (!parseExpr(Op[i])) {
3527 if (Op[i] < MinVal || Op[i] > MaxVal) {
3528 Error(ExprLoc, ErrMsg);
3537 AMDGPUAsmParser::parseSwizzleQuadPerm(int64_t &Imm) {
3538 using namespace llvm::AMDGPU::Swizzle;
3540 int64_t Lane[LANE_NUM];
3541 if (parseSwizzleOperands(LANE_NUM, Lane, 0, LANE_MAX,
3542 "expected a 2-bit lane id")) {
3543 Imm = QUAD_PERM_ENC;
3544 for (auto i = 0; i < LANE_NUM; ++i) {
3545 Imm |= Lane[i] << (LANE_SHIFT * i);
3553 AMDGPUAsmParser::parseSwizzleBroadcast(int64_t &Imm) {
3554 using namespace llvm::AMDGPU::Swizzle;
3556 SMLoc S = Parser.getTok().getLoc();
3560 if (!parseSwizzleOperands(1, &GroupSize,
3562 "group size must be in the interval [2,32]")) {
3565 if (!isPowerOf2_64(GroupSize)) {
3566 Error(S, "group size must be a power of two");
3569 if (parseSwizzleOperands(1, &LaneIdx,
3571 "lane id must be in the interval [0,group size - 1]")) {
3572 Imm = encodeBitmaskPerm(BITMASK_MAX - GroupSize + 1, LaneIdx, 0);
3579 AMDGPUAsmParser::parseSwizzleReverse(int64_t &Imm) {
3580 using namespace llvm::AMDGPU::Swizzle;
3582 SMLoc S = Parser.getTok().getLoc();
3585 if (!parseSwizzleOperands(1, &GroupSize,
3586 2, 32, "group size must be in the interval [2,32]")) {
3589 if (!isPowerOf2_64(GroupSize)) {
3590 Error(S, "group size must be a power of two");
3594 Imm = encodeBitmaskPerm(BITMASK_MAX, 0, GroupSize - 1);
3599 AMDGPUAsmParser::parseSwizzleSwap(int64_t &Imm) {
3600 using namespace llvm::AMDGPU::Swizzle;
3602 SMLoc S = Parser.getTok().getLoc();
3605 if (!parseSwizzleOperands(1, &GroupSize,
3606 1, 16, "group size must be in the interval [1,16]")) {
3609 if (!isPowerOf2_64(GroupSize)) {
3610 Error(S, "group size must be a power of two");
3614 Imm = encodeBitmaskPerm(BITMASK_MAX, 0, GroupSize);
3619 AMDGPUAsmParser::parseSwizzleBitmaskPerm(int64_t &Imm) {
3620 using namespace llvm::AMDGPU::Swizzle;
3622 if (!skipToken(AsmToken::Comma, "expected a comma")) {
3627 SMLoc StrLoc = Parser.getTok().getLoc();
3628 if (!parseString(Ctl)) {
3631 if (Ctl.size() != BITMASK_WIDTH) {
3632 Error(StrLoc, "expected a 5-character mask");
3636 unsigned AndMask = 0;
3637 unsigned OrMask = 0;
3638 unsigned XorMask = 0;
3640 for (size_t i = 0; i < Ctl.size(); ++i) {
3641 unsigned Mask = 1 << (BITMASK_WIDTH - 1 - i);
3644 Error(StrLoc, "invalid mask");
3661 Imm = encodeBitmaskPerm(AndMask, OrMask, XorMask);
3666 AMDGPUAsmParser::parseSwizzleOffset(int64_t &Imm) {
3668 SMLoc OffsetLoc = Parser.getTok().getLoc();
3670 if (!parseExpr(Imm)) {
3673 if (!isUInt<16>(Imm)) {
3674 Error(OffsetLoc, "expected a 16-bit offset");
3681 AMDGPUAsmParser::parseSwizzleMacro(int64_t &Imm) {
3682 using namespace llvm::AMDGPU::Swizzle;
3684 if (skipToken(AsmToken::LParen, "expected a left parentheses")) {
3686 SMLoc ModeLoc = Parser.getTok().getLoc();
3689 if (trySkipId(IdSymbolic[ID_QUAD_PERM])) {
3690 Ok = parseSwizzleQuadPerm(Imm);
3691 } else if (trySkipId(IdSymbolic[ID_BITMASK_PERM])) {
3692 Ok = parseSwizzleBitmaskPerm(Imm);
3693 } else if (trySkipId(IdSymbolic[ID_BROADCAST])) {
3694 Ok = parseSwizzleBroadcast(Imm);
3695 } else if (trySkipId(IdSymbolic[ID_SWAP])) {
3696 Ok = parseSwizzleSwap(Imm);
3697 } else if (trySkipId(IdSymbolic[ID_REVERSE])) {
3698 Ok = parseSwizzleReverse(Imm);
3700 Error(ModeLoc, "expected a swizzle mode");
3703 return Ok && skipToken(AsmToken::RParen, "expected a closing parentheses");
3709 OperandMatchResultTy
3710 AMDGPUAsmParser::parseSwizzleOp(OperandVector &Operands) {
3711 SMLoc S = Parser.getTok().getLoc();
3714 if (trySkipId("offset")) {
3717 if (skipToken(AsmToken::Colon, "expected a colon")) {
3718 if (trySkipId("swizzle")) {
3719 Ok = parseSwizzleMacro(Imm);
3721 Ok = parseSwizzleOffset(Imm);
3725 Operands.push_back(AMDGPUOperand::CreateImm(this, Imm, S, AMDGPUOperand::ImmTySwizzle));
3727 return Ok? MatchOperand_Success : MatchOperand_ParseFail;
3729 return MatchOperand_NoMatch;
3734 AMDGPUOperand::isSwizzle() const {
3735 return isImmTy(ImmTySwizzle);
3738 //===----------------------------------------------------------------------===//
3739 // sopp branch targets
3740 //===----------------------------------------------------------------------===//
3742 OperandMatchResultTy
3743 AMDGPUAsmParser::parseSOppBrTarget(OperandVector &Operands) {
3744 SMLoc S = Parser.getTok().getLoc();
3746 switch (getLexer().getKind()) {
3747 default: return MatchOperand_ParseFail;
3748 case AsmToken::Integer: {
3750 if (getParser().parseAbsoluteExpression(Imm))
3751 return MatchOperand_ParseFail;
3752 Operands.push_back(AMDGPUOperand::CreateImm(this, Imm, S));
3753 return MatchOperand_Success;
3756 case AsmToken::Identifier:
3757 Operands.push_back(AMDGPUOperand::CreateExpr(this,
3758 MCSymbolRefExpr::create(getContext().getOrCreateSymbol(
3759 Parser.getTok().getString()), getContext()), S));
3761 return MatchOperand_Success;
3765 //===----------------------------------------------------------------------===//
3767 //===----------------------------------------------------------------------===//
3769 AMDGPUOperand::Ptr AMDGPUAsmParser::defaultGLC() const {
3770 return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyGLC);
3773 AMDGPUOperand::Ptr AMDGPUAsmParser::defaultSLC() const {
3774 return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTySLC);
3777 AMDGPUOperand::Ptr AMDGPUAsmParser::defaultTFE() const {
3778 return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyTFE);
3781 void AMDGPUAsmParser::cvtMubufImpl(MCInst &Inst,
3782 const OperandVector &Operands,
3783 bool IsAtomic, bool IsAtomicReturn) {
3784 OptionalImmIndexMap OptionalIdx;
3785 assert(IsAtomicReturn ? IsAtomic : true);
3787 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
3788 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
3790 // Add the register arguments
3792 Op.addRegOperands(Inst, 1);
3796 // Handle the case where soffset is an immediate
3797 if (Op.isImm() && Op.getImmTy() == AMDGPUOperand::ImmTyNone) {
3798 Op.addImmOperands(Inst, 1);
3802 // Handle tokens like 'offen' which are sometimes hard-coded into the
3803 // asm string. There are no MCInst operands for these.
3809 // Handle optional arguments
3810 OptionalIdx[Op.getImmTy()] = i;
3813 // Copy $vdata_in operand and insert as $vdata for MUBUF_Atomic RTN insns.
3814 if (IsAtomicReturn) {
3815 MCInst::iterator I = Inst.begin(); // $vdata_in is always at the beginning.
3819 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyOffset);
3820 if (!IsAtomic) { // glc is hard-coded.
3821 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyGLC);
3823 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySLC);
3824 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyTFE);
3827 void AMDGPUAsmParser::cvtMtbuf(MCInst &Inst, const OperandVector &Operands) {
3828 OptionalImmIndexMap OptionalIdx;
3830 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
3831 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
3833 // Add the register arguments
3835 Op.addRegOperands(Inst, 1);
3839 // Handle the case where soffset is an immediate
3840 if (Op.isImm() && Op.getImmTy() == AMDGPUOperand::ImmTyNone) {
3841 Op.addImmOperands(Inst, 1);
3845 // Handle tokens like 'offen' which are sometimes hard-coded into the
3846 // asm string. There are no MCInst operands for these.
3852 // Handle optional arguments
3853 OptionalIdx[Op.getImmTy()] = i;
3856 addOptionalImmOperand(Inst, Operands, OptionalIdx,
3857 AMDGPUOperand::ImmTyOffset);
3858 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyDFMT);
3859 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyNFMT);
3860 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyGLC);
3861 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySLC);
3862 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyTFE);
3865 //===----------------------------------------------------------------------===//
3867 //===----------------------------------------------------------------------===//
3869 void AMDGPUAsmParser::cvtMIMG(MCInst &Inst, const OperandVector &Operands,
3872 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
3873 for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
3874 ((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
3878 // Add src, same as dst
3879 ((AMDGPUOperand &)*Operands[I]).addRegOperands(Inst, 1);
3882 OptionalImmIndexMap OptionalIdx;
3884 for (unsigned E = Operands.size(); I != E; ++I) {
3885 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
3887 // Add the register arguments
3888 if (Op.isRegOrImm()) {
3889 Op.addRegOrImmOperands(Inst, 1);
3891 } else if (Op.isImmModifier()) {
3892 OptionalIdx[Op.getImmTy()] = I;
3894 llvm_unreachable("unexpected operand type");
3898 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyDMask);
3899 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyUNorm);
3900 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyGLC);
3901 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyDA);
3902 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyR128);
3903 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyTFE);
3904 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyLWE);
3905 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySLC);
3908 void AMDGPUAsmParser::cvtMIMGAtomic(MCInst &Inst, const OperandVector &Operands) {
3909 cvtMIMG(Inst, Operands, true);
3912 AMDGPUOperand::Ptr AMDGPUAsmParser::defaultDMask() const {
3913 return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyDMask);
3916 AMDGPUOperand::Ptr AMDGPUAsmParser::defaultUNorm() const {
3917 return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyUNorm);
3920 AMDGPUOperand::Ptr AMDGPUAsmParser::defaultDA() const {
3921 return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyDA);
3924 AMDGPUOperand::Ptr AMDGPUAsmParser::defaultR128() const {
3925 return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyR128);
3928 AMDGPUOperand::Ptr AMDGPUAsmParser::defaultLWE() const {
3929 return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyLWE);
3932 //===----------------------------------------------------------------------===//
3934 //===----------------------------------------------------------------------===//
3936 bool AMDGPUOperand::isSMRDOffset8() const {
3937 return isImm() && isUInt<8>(getImm());
3940 bool AMDGPUOperand::isSMRDOffset20() const {
3941 return isImm() && isUInt<20>(getImm());
3944 bool AMDGPUOperand::isSMRDLiteralOffset() const {
3945 // 32-bit literals are only supported on CI and we only want to use them
3946 // when the offset is > 8-bits.
3947 return isImm() && !isUInt<8>(getImm()) && isUInt<32>(getImm());
3950 AMDGPUOperand::Ptr AMDGPUAsmParser::defaultSMRDOffset8() const {
3951 return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyOffset);
3954 AMDGPUOperand::Ptr AMDGPUAsmParser::defaultSMRDOffset20() const {
3955 return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyOffset);
3958 AMDGPUOperand::Ptr AMDGPUAsmParser::defaultSMRDLiteralOffset() const {
3959 return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyOffset);
3962 AMDGPUOperand::Ptr AMDGPUAsmParser::defaultOffsetU12() const {
3963 return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyOffset);
3966 AMDGPUOperand::Ptr AMDGPUAsmParser::defaultOffsetS13() const {
3967 return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyOffset);
3970 //===----------------------------------------------------------------------===//
3972 //===----------------------------------------------------------------------===//
3974 static bool ConvertOmodMul(int64_t &Mul) {
3975 if (Mul != 1 && Mul != 2 && Mul != 4)
3982 static bool ConvertOmodDiv(int64_t &Div) {
3996 static bool ConvertBoundCtrl(int64_t &BoundCtrl) {
3997 if (BoundCtrl == 0) {
4002 if (BoundCtrl == -1) {
4010 // Note: the order in this table matches the order of operands in AsmString.
4011 static const OptionalOperand AMDGPUOptionalOperandTable[] = {
4012 {"offen", AMDGPUOperand::ImmTyOffen, true, nullptr},
4013 {"idxen", AMDGPUOperand::ImmTyIdxen, true, nullptr},
4014 {"addr64", AMDGPUOperand::ImmTyAddr64, true, nullptr},
4015 {"offset0", AMDGPUOperand::ImmTyOffset0, false, nullptr},
4016 {"offset1", AMDGPUOperand::ImmTyOffset1, false, nullptr},
4017 {"gds", AMDGPUOperand::ImmTyGDS, true, nullptr},
4018 {"offset", AMDGPUOperand::ImmTyOffset, false, nullptr},
4019 {"dfmt", AMDGPUOperand::ImmTyDFMT, false, nullptr},
4020 {"nfmt", AMDGPUOperand::ImmTyNFMT, false, nullptr},
4021 {"glc", AMDGPUOperand::ImmTyGLC, true, nullptr},
4022 {"slc", AMDGPUOperand::ImmTySLC, true, nullptr},
4023 {"tfe", AMDGPUOperand::ImmTyTFE, true, nullptr},
4024 {"clamp", AMDGPUOperand::ImmTyClampSI, true, nullptr},
4025 {"omod", AMDGPUOperand::ImmTyOModSI, false, ConvertOmodMul},
4026 {"unorm", AMDGPUOperand::ImmTyUNorm, true, nullptr},
4027 {"da", AMDGPUOperand::ImmTyDA, true, nullptr},
4028 {"r128", AMDGPUOperand::ImmTyR128, true, nullptr},
4029 {"lwe", AMDGPUOperand::ImmTyLWE, true, nullptr},
4030 {"dmask", AMDGPUOperand::ImmTyDMask, false, nullptr},
4031 {"row_mask", AMDGPUOperand::ImmTyDppRowMask, false, nullptr},
4032 {"bank_mask", AMDGPUOperand::ImmTyDppBankMask, false, nullptr},
4033 {"bound_ctrl", AMDGPUOperand::ImmTyDppBoundCtrl, false, ConvertBoundCtrl},
4034 {"dst_sel", AMDGPUOperand::ImmTySdwaDstSel, false, nullptr},
4035 {"src0_sel", AMDGPUOperand::ImmTySdwaSrc0Sel, false, nullptr},
4036 {"src1_sel", AMDGPUOperand::ImmTySdwaSrc1Sel, false, nullptr},
4037 {"dst_unused", AMDGPUOperand::ImmTySdwaDstUnused, false, nullptr},
4038 {"compr", AMDGPUOperand::ImmTyExpCompr, true, nullptr },
4039 {"vm", AMDGPUOperand::ImmTyExpVM, true, nullptr},
4040 {"op_sel", AMDGPUOperand::ImmTyOpSel, false, nullptr},
4041 {"op_sel_hi", AMDGPUOperand::ImmTyOpSelHi, false, nullptr},
4042 {"neg_lo", AMDGPUOperand::ImmTyNegLo, false, nullptr},
4043 {"neg_hi", AMDGPUOperand::ImmTyNegHi, false, nullptr}
4046 OperandMatchResultTy AMDGPUAsmParser::parseOptionalOperand(OperandVector &Operands) {
4047 OperandMatchResultTy res;
4048 for (const OptionalOperand &Op : AMDGPUOptionalOperandTable) {
4049 // try to parse any optional operand here
4051 res = parseNamedBit(Op.Name, Operands, Op.Type);
4052 } else if (Op.Type == AMDGPUOperand::ImmTyOModSI) {
4053 res = parseOModOperand(Operands);
4054 } else if (Op.Type == AMDGPUOperand::ImmTySdwaDstSel ||
4055 Op.Type == AMDGPUOperand::ImmTySdwaSrc0Sel ||
4056 Op.Type == AMDGPUOperand::ImmTySdwaSrc1Sel) {
4057 res = parseSDWASel(Operands, Op.Name, Op.Type);
4058 } else if (Op.Type == AMDGPUOperand::ImmTySdwaDstUnused) {
4059 res = parseSDWADstUnused(Operands);
4060 } else if (Op.Type == AMDGPUOperand::ImmTyOpSel ||
4061 Op.Type == AMDGPUOperand::ImmTyOpSelHi ||
4062 Op.Type == AMDGPUOperand::ImmTyNegLo ||
4063 Op.Type == AMDGPUOperand::ImmTyNegHi) {
4064 res = parseOperandArrayWithPrefix(Op.Name, Operands, Op.Type,
4067 res = parseIntWithPrefix(Op.Name, Operands, Op.Type, Op.ConvertResult);
4069 if (res != MatchOperand_NoMatch) {
4073 return MatchOperand_NoMatch;
4076 OperandMatchResultTy AMDGPUAsmParser::parseOModOperand(OperandVector &Operands) {
4077 StringRef Name = Parser.getTok().getString();
4078 if (Name == "mul") {
4079 return parseIntWithPrefix("mul", Operands,
4080 AMDGPUOperand::ImmTyOModSI, ConvertOmodMul);
4083 if (Name == "div") {
4084 return parseIntWithPrefix("div", Operands,
4085 AMDGPUOperand::ImmTyOModSI, ConvertOmodDiv);
4088 return MatchOperand_NoMatch;
4091 static bool isRegOrImmWithInputMods(const MCInstrDesc &Desc, unsigned OpNum) {
4092 // 1. This operand is input modifiers
4093 return Desc.OpInfo[OpNum].OperandType == AMDGPU::OPERAND_INPUT_MODS
4094 // 2. This is not last operand
4095 && Desc.NumOperands > (OpNum + 1)
4096 // 3. Next operand is register class
4097 && Desc.OpInfo[OpNum + 1].RegClass != -1
4098 // 4. Next register is not tied to any other operand
4099 && Desc.getOperandConstraint(OpNum + 1, MCOI::OperandConstraint::TIED_TO) == -1;
4102 void AMDGPUAsmParser::cvtVOP3(MCInst &Inst, const OperandVector &Operands,
4103 OptionalImmIndexMap &OptionalIdx) {
4104 unsigned Opc = Inst.getOpcode();
4107 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
4108 for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
4109 ((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
4112 if (AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers) != -1) {
4113 // This instruction has src modifiers
4114 for (unsigned E = Operands.size(); I != E; ++I) {
4115 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
4116 if (isRegOrImmWithInputMods(Desc, Inst.getNumOperands())) {
4117 Op.addRegOrImmWithFPInputModsOperands(Inst, 2);
4118 } else if (Op.isImmModifier()) {
4119 OptionalIdx[Op.getImmTy()] = I;
4120 } else if (Op.isRegOrImm()) {
4121 Op.addRegOrImmOperands(Inst, 1);
4123 llvm_unreachable("unhandled operand type");
4128 for (unsigned E = Operands.size(); I != E; ++I) {
4129 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
4131 OptionalIdx[Op.getImmTy()] = I;
4133 Op.addRegOrImmOperands(Inst, 1);
4138 if (AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp) != -1) {
4139 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyClampSI);
4142 if (AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod) != -1) {
4143 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyOModSI);
4146 // special case v_mac_{f16, f32}:
4147 // it has src2 register operand that is tied to dst operand
4148 // we don't allow modifiers for this operand in assembler so src2_modifiers
4150 if (Opc == AMDGPU::V_MAC_F32_e64_si || Opc == AMDGPU::V_MAC_F32_e64_vi ||
4151 Opc == AMDGPU::V_MAC_F16_e64_vi) {
4152 auto it = Inst.begin();
4153 std::advance(it, AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2_modifiers));
4154 it = Inst.insert(it, MCOperand::createImm(0)); // no modifiers for src2
4156 Inst.insert(it, Inst.getOperand(0)); // src2 = dst
4160 void AMDGPUAsmParser::cvtVOP3(MCInst &Inst, const OperandVector &Operands) {
4161 OptionalImmIndexMap OptionalIdx;
4162 cvtVOP3(Inst, Operands, OptionalIdx);
4165 void AMDGPUAsmParser::cvtVOP3P(MCInst &Inst, const OperandVector &Operands) {
4166 OptionalImmIndexMap OptIdx;
4168 cvtVOP3(Inst, Operands, OptIdx);
4170 // FIXME: This is messy. Parse the modifiers as if it was a normal VOP3
4171 // instruction, and then figure out where to actually put the modifiers
4172 int Opc = Inst.getOpcode();
4174 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyOpSel);
4175 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyOpSelHi, -1);
4177 int NegLoIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::neg_lo);
4178 if (NegLoIdx != -1) {
4179 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyNegLo);
4180 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyNegHi);
4183 const int Ops[] = { AMDGPU::OpName::src0,
4184 AMDGPU::OpName::src1,
4185 AMDGPU::OpName::src2 };
4186 const int ModOps[] = { AMDGPU::OpName::src0_modifiers,
4187 AMDGPU::OpName::src1_modifiers,
4188 AMDGPU::OpName::src2_modifiers };
4190 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
4191 int OpSelHiIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel_hi);
4193 unsigned OpSel = Inst.getOperand(OpSelIdx).getImm();
4194 unsigned OpSelHi = Inst.getOperand(OpSelHiIdx).getImm();
4198 if (NegLoIdx != -1) {
4199 int NegHiIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::neg_hi);
4200 NegLo = Inst.getOperand(NegLoIdx).getImm();
4201 NegHi = Inst.getOperand(NegHiIdx).getImm();
4204 for (int J = 0; J < 3; ++J) {
4205 int OpIdx = AMDGPU::getNamedOperandIdx(Opc, Ops[J]);
4209 uint32_t ModVal = 0;
4211 if ((OpSel & (1 << J)) != 0)
4212 ModVal |= SISrcMods::OP_SEL_0;
4214 if ((OpSelHi & (1 << J)) != 0)
4215 ModVal |= SISrcMods::OP_SEL_1;
4217 if ((NegLo & (1 << J)) != 0)
4218 ModVal |= SISrcMods::NEG;
4220 if ((NegHi & (1 << J)) != 0)
4221 ModVal |= SISrcMods::NEG_HI;
4223 int ModIdx = AMDGPU::getNamedOperandIdx(Opc, ModOps[J]);
4225 Inst.getOperand(ModIdx).setImm(Inst.getOperand(ModIdx).getImm() | ModVal);
4229 //===----------------------------------------------------------------------===//
4231 //===----------------------------------------------------------------------===//
4233 bool AMDGPUOperand::isDPPCtrl() const {
4234 bool result = isImm() && getImmTy() == ImmTyDppCtrl && isUInt<9>(getImm());
4236 int64_t Imm = getImm();
4237 return ((Imm >= 0x000) && (Imm <= 0x0ff)) ||
4238 ((Imm >= 0x101) && (Imm <= 0x10f)) ||
4239 ((Imm >= 0x111) && (Imm <= 0x11f)) ||
4240 ((Imm >= 0x121) && (Imm <= 0x12f)) ||
4253 bool AMDGPUOperand::isGPRIdxMode() const {
4254 return isImm() && isUInt<4>(getImm());
4257 bool AMDGPUOperand::isS16Imm() const {
4258 return isImm() && (isInt<16>(getImm()) || isUInt<16>(getImm()));
4261 bool AMDGPUOperand::isU16Imm() const {
4262 return isImm() && isUInt<16>(getImm());
4265 OperandMatchResultTy
4266 AMDGPUAsmParser::parseDPPCtrl(OperandVector &Operands) {
4267 SMLoc S = Parser.getTok().getLoc();
4271 if (getLexer().getKind() == AsmToken::Identifier) {
4272 Prefix = Parser.getTok().getString();
4274 return MatchOperand_NoMatch;
4277 if (Prefix == "row_mirror") {
4280 } else if (Prefix == "row_half_mirror") {
4284 // Check to prevent parseDPPCtrlOps from eating invalid tokens
4285 if (Prefix != "quad_perm"
4286 && Prefix != "row_shl"
4287 && Prefix != "row_shr"
4288 && Prefix != "row_ror"
4289 && Prefix != "wave_shl"
4290 && Prefix != "wave_rol"
4291 && Prefix != "wave_shr"
4292 && Prefix != "wave_ror"
4293 && Prefix != "row_bcast") {
4294 return MatchOperand_NoMatch;
4298 if (getLexer().isNot(AsmToken::Colon))
4299 return MatchOperand_ParseFail;
4301 if (Prefix == "quad_perm") {
4302 // quad_perm:[%d,%d,%d,%d]
4304 if (getLexer().isNot(AsmToken::LBrac))
4305 return MatchOperand_ParseFail;
4308 if (getParser().parseAbsoluteExpression(Int) || !(0 <= Int && Int <=3))
4309 return MatchOperand_ParseFail;
4311 for (int i = 0; i < 3; ++i) {
4312 if (getLexer().isNot(AsmToken::Comma))
4313 return MatchOperand_ParseFail;
4317 if (getParser().parseAbsoluteExpression(Temp) || !(0 <= Temp && Temp <=3))
4318 return MatchOperand_ParseFail;
4319 const int shift = i*2 + 2;
4320 Int += (Temp << shift);
4323 if (getLexer().isNot(AsmToken::RBrac))
4324 return MatchOperand_ParseFail;
4330 if (getParser().parseAbsoluteExpression(Int))
4331 return MatchOperand_ParseFail;
4333 if (Prefix == "row_shl" && 1 <= Int && Int <= 15) {
4335 } else if (Prefix == "row_shr" && 1 <= Int && Int <= 15) {
4337 } else if (Prefix == "row_ror" && 1 <= Int && Int <= 15) {
4339 } else if (Prefix == "wave_shl" && 1 == Int) {
4341 } else if (Prefix == "wave_rol" && 1 == Int) {
4343 } else if (Prefix == "wave_shr" && 1 == Int) {
4345 } else if (Prefix == "wave_ror" && 1 == Int) {
4347 } else if (Prefix == "row_bcast") {
4350 } else if (Int == 31) {
4353 return MatchOperand_ParseFail;
4356 return MatchOperand_ParseFail;
4361 Operands.push_back(AMDGPUOperand::CreateImm(this, Int, S, AMDGPUOperand::ImmTyDppCtrl));
4362 return MatchOperand_Success;
4365 AMDGPUOperand::Ptr AMDGPUAsmParser::defaultRowMask() const {
4366 return AMDGPUOperand::CreateImm(this, 0xf, SMLoc(), AMDGPUOperand::ImmTyDppRowMask);
4369 AMDGPUOperand::Ptr AMDGPUAsmParser::defaultBankMask() const {
4370 return AMDGPUOperand::CreateImm(this, 0xf, SMLoc(), AMDGPUOperand::ImmTyDppBankMask);
4373 AMDGPUOperand::Ptr AMDGPUAsmParser::defaultBoundCtrl() const {
4374 return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyDppBoundCtrl);
4377 void AMDGPUAsmParser::cvtDPP(MCInst &Inst, const OperandVector &Operands) {
4378 OptionalImmIndexMap OptionalIdx;
4381 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
4382 for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
4383 ((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
4386 for (unsigned E = Operands.size(); I != E; ++I) {
4387 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
4388 // Add the register arguments
4389 if (Op.isReg() && Op.Reg.RegNo == AMDGPU::VCC) {
4390 // VOP2b (v_add_u32, v_sub_u32 ...) dpp use "vcc" token.
4393 } if (isRegOrImmWithInputMods(Desc, Inst.getNumOperands())) {
4394 Op.addRegWithFPInputModsOperands(Inst, 2);
4395 } else if (Op.isDPPCtrl()) {
4396 Op.addImmOperands(Inst, 1);
4397 } else if (Op.isImm()) {
4398 // Handle optional arguments
4399 OptionalIdx[Op.getImmTy()] = I;
4401 llvm_unreachable("Invalid operand type");
4405 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyDppRowMask, 0xf);
4406 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyDppBankMask, 0xf);
4407 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyDppBoundCtrl);
4409 // special case v_mac_{f16, f32}:
4410 // it has src2 register operand that is tied to dst operand
4411 if (Inst.getOpcode() == AMDGPU::V_MAC_F32_dpp ||
4412 Inst.getOpcode() == AMDGPU::V_MAC_F16_dpp) {
4413 auto it = Inst.begin();
4415 it, AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::src2));
4416 Inst.insert(it, Inst.getOperand(0)); // src2 = dst
4420 //===----------------------------------------------------------------------===//
4422 //===----------------------------------------------------------------------===//
4424 OperandMatchResultTy
4425 AMDGPUAsmParser::parseSDWASel(OperandVector &Operands, StringRef Prefix,
4426 AMDGPUOperand::ImmTy Type) {
4427 using namespace llvm::AMDGPU::SDWA;
4429 SMLoc S = Parser.getTok().getLoc();
4431 OperandMatchResultTy res;
4433 res = parseStringWithPrefix(Prefix, Value);
4434 if (res != MatchOperand_Success) {
4439 Int = StringSwitch<int64_t>(Value)
4440 .Case("BYTE_0", SdwaSel::BYTE_0)
4441 .Case("BYTE_1", SdwaSel::BYTE_1)
4442 .Case("BYTE_2", SdwaSel::BYTE_2)
4443 .Case("BYTE_3", SdwaSel::BYTE_3)
4444 .Case("WORD_0", SdwaSel::WORD_0)
4445 .Case("WORD_1", SdwaSel::WORD_1)
4446 .Case("DWORD", SdwaSel::DWORD)
4447 .Default(0xffffffff);
4448 Parser.Lex(); // eat last token
4450 if (Int == 0xffffffff) {
4451 return MatchOperand_ParseFail;
4454 Operands.push_back(AMDGPUOperand::CreateImm(this, Int, S, Type));
4455 return MatchOperand_Success;
4458 OperandMatchResultTy
4459 AMDGPUAsmParser::parseSDWADstUnused(OperandVector &Operands) {
4460 using namespace llvm::AMDGPU::SDWA;
4462 SMLoc S = Parser.getTok().getLoc();
4464 OperandMatchResultTy res;
4466 res = parseStringWithPrefix("dst_unused", Value);
4467 if (res != MatchOperand_Success) {
4472 Int = StringSwitch<int64_t>(Value)
4473 .Case("UNUSED_PAD", DstUnused::UNUSED_PAD)
4474 .Case("UNUSED_SEXT", DstUnused::UNUSED_SEXT)
4475 .Case("UNUSED_PRESERVE", DstUnused::UNUSED_PRESERVE)
4476 .Default(0xffffffff);
4477 Parser.Lex(); // eat last token
4479 if (Int == 0xffffffff) {
4480 return MatchOperand_ParseFail;
4483 Operands.push_back(AMDGPUOperand::CreateImm(this, Int, S, AMDGPUOperand::ImmTySdwaDstUnused));
4484 return MatchOperand_Success;
4487 void AMDGPUAsmParser::cvtSdwaVOP1(MCInst &Inst, const OperandVector &Operands) {
4488 cvtSDWA(Inst, Operands, SIInstrFlags::VOP1);
4491 void AMDGPUAsmParser::cvtSdwaVOP2(MCInst &Inst, const OperandVector &Operands) {
4492 cvtSDWA(Inst, Operands, SIInstrFlags::VOP2);
4495 void AMDGPUAsmParser::cvtSdwaVOP2b(MCInst &Inst, const OperandVector &Operands) {
4496 cvtSDWA(Inst, Operands, SIInstrFlags::VOP2, true);
4499 void AMDGPUAsmParser::cvtSdwaVOPC(MCInst &Inst, const OperandVector &Operands) {
4500 cvtSDWA(Inst, Operands, SIInstrFlags::VOPC, isVI());
4503 void AMDGPUAsmParser::cvtSDWA(MCInst &Inst, const OperandVector &Operands,
4504 uint64_t BasicInstType, bool skipVcc) {
4505 using namespace llvm::AMDGPU::SDWA;
4506 OptionalImmIndexMap OptionalIdx;
4507 bool skippedVcc = false;
4510 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
4511 for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
4512 ((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
4515 for (unsigned E = Operands.size(); I != E; ++I) {
4516 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
4517 if (skipVcc && !skippedVcc && Op.isReg() && Op.Reg.RegNo == AMDGPU::VCC) {
4518 // VOP2b (v_add_u32, v_sub_u32 ...) sdwa use "vcc" token as dst.
4519 // Skip it if it's 2nd (e.g. v_add_i32_sdwa v1, vcc, v2, v3)
4520 // or 4th (v_addc_u32_sdwa v1, vcc, v2, v3, vcc) operand.
4521 // Skip VCC only if we didn't skip it on previous iteration.
4522 if (BasicInstType == SIInstrFlags::VOP2 &&
4523 (Inst.getNumOperands() == 1 || Inst.getNumOperands() == 5)) {
4526 } else if (BasicInstType == SIInstrFlags::VOPC &&
4527 Inst.getNumOperands() == 0) {
4532 if (isRegOrImmWithInputMods(Desc, Inst.getNumOperands())) {
4533 Op.addRegWithInputModsOperands(Inst, 2);
4534 } else if (Op.isImm()) {
4535 // Handle optional arguments
4536 OptionalIdx[Op.getImmTy()] = I;
4538 llvm_unreachable("Invalid operand type");
4543 if (Inst.getOpcode() != AMDGPU::V_NOP_sdwa_gfx9 &&
4544 Inst.getOpcode() != AMDGPU::V_NOP_sdwa_vi) {
4545 // v_nop_sdwa_sdwa_vi/gfx9 has no optional sdwa arguments
4546 switch (BasicInstType) {
4547 case SIInstrFlags::VOP1:
4548 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyClampSI, 0);
4549 if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::omod) != -1) {
4550 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyOModSI, 0);
4552 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaDstSel, SdwaSel::DWORD);
4553 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaDstUnused, DstUnused::UNUSED_PRESERVE);
4554 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaSrc0Sel, SdwaSel::DWORD);
4557 case SIInstrFlags::VOP2:
4558 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyClampSI, 0);
4559 if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::omod) != -1) {
4560 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyOModSI, 0);
4562 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaDstSel, SdwaSel::DWORD);
4563 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaDstUnused, DstUnused::UNUSED_PRESERVE);
4564 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaSrc0Sel, SdwaSel::DWORD);
4565 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaSrc1Sel, SdwaSel::DWORD);
4568 case SIInstrFlags::VOPC:
4569 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyClampSI, 0);
4570 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaSrc0Sel, SdwaSel::DWORD);
4571 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaSrc1Sel, SdwaSel::DWORD);
4575 llvm_unreachable("Invalid instruction type. Only VOP1, VOP2 and VOPC allowed");
4579 // special case v_mac_{f16, f32}:
4580 // it has src2 register operand that is tied to dst operand
4581 if (Inst.getOpcode() == AMDGPU::V_MAC_F32_sdwa_vi ||
4582 Inst.getOpcode() == AMDGPU::V_MAC_F16_sdwa_vi) {
4583 auto it = Inst.begin();
4585 it, AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::src2));
4586 Inst.insert(it, Inst.getOperand(0)); // src2 = dst
4590 /// Force static initialization.
4591 extern "C" void LLVMInitializeAMDGPUAsmParser() {
4592 RegisterMCAsmParser<AMDGPUAsmParser> A(getTheAMDGPUTarget());
4593 RegisterMCAsmParser<AMDGPUAsmParser> B(getTheGCNTarget());
4596 #define GET_REGISTER_MATCHER
4597 #define GET_MATCHER_IMPLEMENTATION
4598 #include "AMDGPUGenAsmMatcher.inc"
4600 // This fuction should be defined after auto-generated include so that we have
4601 // MatchClassKind enum defined
4602 unsigned AMDGPUAsmParser::validateTargetOperandClass(MCParsedAsmOperand &Op,
4604 // Tokens like "glc" would be parsed as immediate operands in ParseOperand().
4605 // But MatchInstructionImpl() expects to meet token and fails to validate
4606 // operand. This method checks if we are given immediate operand but expect to
4607 // get corresponding token.
4608 AMDGPUOperand &Operand = (AMDGPUOperand&)Op;
4611 return Operand.isAddr64() ? Match_Success : Match_InvalidOperand;
4613 return Operand.isGDS() ? Match_Success : Match_InvalidOperand;
4615 return Operand.isGLC() ? Match_Success : Match_InvalidOperand;
4617 return Operand.isIdxen() ? Match_Success : Match_InvalidOperand;
4619 return Operand.isOffen() ? Match_Success : Match_InvalidOperand;
4621 // When operands have expression values, they will return true for isToken,
4622 // because it is not possible to distinguish between a token and an
4623 // expression at parse time. MatchInstructionImpl() will always try to
4624 // match an operand as a token, when isToken returns true, and when the
4625 // name of the expression is not a valid token, the match will fail,
4626 // so we need to handle it here.
4627 return Operand.isSSrcB32() ? Match_Success : Match_InvalidOperand;
4629 return Operand.isSSrcF32() ? Match_Success : Match_InvalidOperand;
4630 case MCK_SoppBrTarget:
4631 return Operand.isSoppBrTarget() ? Match_Success : Match_InvalidOperand;
4632 case MCK_VReg32OrOff:
4633 return Operand.isVReg32OrOff() ? Match_Success : Match_InvalidOperand;
4634 case MCK_InterpSlot:
4635 return Operand.isInterpSlot() ? Match_Success : Match_InvalidOperand;
4637 return Operand.isInterpAttr() ? Match_Success : Match_InvalidOperand;
4639 return Operand.isAttrChan() ? Match_Success : Match_InvalidOperand;
4641 return Match_InvalidOperand;