LLVM 24.0.0git
AMDGPUAsmParser.cpp
Go to the documentation of this file.
1//===- AMDGPUAsmParser.cpp - Parse SI asm to MCInst instructions ----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "AMDKernelCodeT.h"
16#include "SIDefines.h"
17#include "SIInstrInfo.h"
22#include "llvm/ADT/APFloat.h"
24#include "llvm/ADT/Twine.h"
27#include "llvm/MC/MCAsmInfo.h"
28#include "llvm/MC/MCContext.h"
29#include "llvm/MC/MCExpr.h"
30#include "llvm/MC/MCInst.h"
31#include "llvm/MC/MCInstrDesc.h"
37#include "llvm/MC/MCSymbol.h"
46#include <optional>
47
48using namespace llvm;
49using namespace llvm::AMDGPU;
50using namespace llvm::amdhsa;
51
52namespace {
53
54class AMDGPUAsmParser;
55
56enum RegisterKind {
57 IS_UNKNOWN,
58 IS_VGPR,
59 IS_SGPR,
60 IS_AGPR,
61 IS_TTMP,
62 IS_SPECIAL
63};
64
65//===----------------------------------------------------------------------===//
66// Operand
67//===----------------------------------------------------------------------===//
68
69class AMDGPUOperand : public MCParsedAsmOperand {
70 enum KindTy { Token, Immediate, Register, Expression } Kind;
71
72 SMLoc StartLoc, EndLoc;
73 const AMDGPUAsmParser *AsmParser;
74
75public:
76 AMDGPUOperand(KindTy Kind_, const AMDGPUAsmParser *AsmParser_)
77 : Kind(Kind_), AsmParser(AsmParser_) {}
78
79 using Ptr = std::unique_ptr<AMDGPUOperand>;
80
81 struct Modifiers {
82 bool Abs = false;
83 bool Neg = false;
84 bool Sext = false;
85 LitModifier Lit = LitModifier::None;
86
87 bool hasFPModifiers() const { return Abs || Neg; }
88 bool hasIntModifiers() const { return Sext; }
89 bool hasModifiers() const { return hasFPModifiers() || hasIntModifiers(); }
90 bool isForcedLit() const { return Lit == LitModifier::Lit; }
91 bool isForcedLit64() const { return Lit == LitModifier::Lit64; }
92
93 int64_t getFPModifiersOperand() const {
94 int64_t Operand = 0;
95 Operand |= Abs ? SISrcMods::ABS : 0u;
96 Operand |= Neg ? SISrcMods::NEG : 0u;
97 return Operand;
98 }
99
100 int64_t getIntModifiersOperand() const {
101 int64_t Operand = 0;
102 Operand |= Sext ? SISrcMods::SEXT : 0u;
103 return Operand;
104 }
105
106 int64_t getModifiersOperand() const {
107 assert(!(hasFPModifiers() && hasIntModifiers()) &&
108 "fp and int modifiers should not be used simultaneously");
109 if (hasFPModifiers())
110 return getFPModifiersOperand();
111 if (hasIntModifiers())
112 return getIntModifiersOperand();
113 return 0;
114 }
115
116 friend raw_ostream &operator<<(raw_ostream &OS,
117 AMDGPUOperand::Modifiers Mods);
118 };
119
120 enum ImmTy {
121 ImmTyNone,
122 ImmTyGDS,
123 ImmTyLDS,
124 ImmTyOffen,
125 ImmTyIdxen,
126 ImmTyAddr64,
127 ImmTyOffset,
128 ImmTyInstOffset,
129 ImmTyOffset0,
130 ImmTyOffset1,
131 ImmTySMEMOffsetMod,
132 ImmTyCPol,
133 ImmTyTFE,
134 ImmTyIsAsync,
135 ImmTyD16,
136 ImmTyClamp,
137 ImmTyOModSI,
138 ImmTySDWADstSel,
139 ImmTySDWASrc0Sel,
140 ImmTySDWASrc1Sel,
141 ImmTySDWADstUnused,
142 ImmTyDMask,
143 ImmTyDim,
144 ImmTyUNorm,
145 ImmTyDA,
146 ImmTyR128A16,
147 ImmTyA16,
148 ImmTyLWE,
149 ImmTyExpTgt,
150 ImmTyExpCompr,
151 ImmTyExpVM,
152 ImmTyDone,
153 ImmTyRowEn,
154 ImmTyFormat,
155 ImmTyFormatOp,
156 ImmTyHwreg,
157 ImmTyOff,
158 ImmTySendMsg,
159 ImmTyWaitEvent,
160 ImmTyInterpSlot,
161 ImmTyInterpAttr,
162 ImmTyInterpAttrChan,
163 ImmTyOpSel,
164 ImmTyOpSelHi,
165 ImmTyNegLo,
166 ImmTyNegHi,
167 ImmTyIndexKey8bit,
168 ImmTyIndexKey16bit,
169 ImmTyIndexKey32bit,
170 ImmTyDPP8,
171 ImmTyDppCtrl,
172 ImmTyDppRowMask,
173 ImmTyDppBankMask,
174 ImmTyDppBoundCtrl,
175 ImmTyDppFI,
176 ImmTySwizzle,
177 ImmTyGprIdxMode,
178 ImmTyHigh,
179 ImmTyBLGP,
180 ImmTyCBSZ,
181 ImmTyABID,
182 ImmTyEndpgm,
183 ImmTyWaitVDST,
184 ImmTyWaitEXP,
185 ImmTyWaitVAVDst,
186 ImmTyWaitVMVSrc,
187 ImmTyBitOp3,
188 ImmTyMatrixAFMT,
189 ImmTyMatrixBFMT,
190 ImmTyMatrixAScale,
191 ImmTyMatrixBScale,
192 ImmTyMatrixAScaleFmt,
193 ImmTyMatrixBScaleFmt,
194 ImmTyMatrixAReuse,
195 ImmTyMatrixBReuse,
196 ImmTyScaleSel,
197 ImmTyByteSel,
198 };
199
200private:
201 struct TokOp {
202 const char *Data;
203 unsigned Length;
204 };
205
206 struct ImmOp {
207 int64_t Val;
208 ImmTy Type;
209 bool IsFPImm;
210 Modifiers Mods;
211 };
212
213 struct RegOp {
214 MCRegister RegNo;
215 Modifiers Mods;
216 };
217
218 union {
219 TokOp Tok;
220 ImmOp Imm;
221 RegOp Reg;
222 const MCExpr *Expr;
223 };
224
225 // The index of the associated MCInst operand.
226 mutable int MCOpIdx = -1;
227
228public:
229 bool isToken() const override { return Kind == Token; }
230
231 bool isSymbolRefExpr() const {
232 return isExpr() && Expr && isa<MCSymbolRefExpr>(Expr);
233 }
234
235 bool hasSymbolSpecifier() const {
236 return isSymbolRefExpr() &&
239 }
240
241 bool isImm() const override { return Kind == Immediate; }
242
243 bool isInlinableImm(MVT type) const;
244 bool isLiteralImm(MVT type) const;
245
246 bool isRegKind() const { return Kind == Register; }
247
248 bool isReg() const override { return isRegKind() && !hasModifiers(); }
249
250 bool isRegOrInline(unsigned RCID, MVT type) const {
251 return isRegClass(RCID) || isInlinableImm(type);
252 }
253
254 bool isRegOrInlineTarget(unsigned TargetRCIdx, MVT type) const {
255 return isRegClassTarget(TargetRCIdx) || isInlinableImm(type);
256 }
257
258 bool isRegOrImmWithInputMods(unsigned RCID, MVT type) const {
259 return isRegOrInline(RCID, type) || isLiteralImm(type);
260 }
261
262 bool isRegOrImmWithInputModsTarget(unsigned TargetRCIdx, MVT type) const {
263 return isRegOrInlineTarget(TargetRCIdx, type) || isLiteralImm(type);
264 }
265
266 template <bool IsFake16> bool isRegOrImmWithIntT16InputMods() const {
268 IsFake16 ? AMDGPU::VS_32RegClassID : AMDGPU::VS_16RegClassID, MVT::i16);
269 }
270
271 bool isRegOrImmWithInt32InputMods() const {
272 return isRegOrImmWithInputMods(AMDGPU::VS_32RegClassID, MVT::i32);
273 }
274
275 template <bool IsFake16> bool isRegOrInlineImmWithIntT16InputMods() const {
276 return isRegOrInline(
277 IsFake16 ? AMDGPU::VS_32RegClassID : AMDGPU::VS_16RegClassID, MVT::i16);
278 }
279
280 bool isRegOrInlineImmWithInt32InputMods() const {
281 return isRegOrInline(AMDGPU::VS_32RegClassID, MVT::i32);
282 }
283
284 bool isRegOrImmWithInt64InputMods() const {
285 return isRegOrImmWithInputModsTarget(AMDGPU::VS_64_AlignTarget, MVT::i64);
286 }
287
288 bool isRegOrImmWithFP16InputMods() const {
289 return isRegOrImmWithInputMods(AMDGPU::VS_32RegClassID, MVT::f16);
290 }
291
292 template <bool IsFake16> bool isRegOrImmWithFPT16InputMods() const {
294 IsFake16 ? AMDGPU::VS_32RegClassID : AMDGPU::VS_16RegClassID, MVT::f16);
295 }
296
297 bool isRegOrImmWithFPT16_LO16InputMods() const {
298 return isRegOrImmWithInputMods(AMDGPU::VS_16_LO16RegClassID, MVT::f16);
299 }
300
301 bool isRegOrImmWithFP32InputMods() const {
302 return isRegOrImmWithInputMods(AMDGPU::VS_32RegClassID, MVT::f32);
303 }
304
305 bool isRegOrImmWithFP64InputMods() const {
306 return isRegOrImmWithInputModsTarget(AMDGPU::VS_64_AlignTarget, MVT::f64);
307 }
308
309 template <bool IsFake16> bool isRegOrInlineImmWithFP16InputMods() const {
310 return isRegOrInline(
311 IsFake16 ? AMDGPU::VS_32RegClassID : AMDGPU::VS_16RegClassID, MVT::f16);
312 }
313
314 bool isRegOrInlineImmWithFP32InputMods() const {
315 return isRegOrInline(AMDGPU::VS_32RegClassID, MVT::f32);
316 }
317
318 bool isRegOrInlineImmWithFP64InputMods() const {
319 return isRegOrInlineTarget(AMDGPU::VS_64_AlignTarget, MVT::f64);
320 }
321
322 bool isVRegWithInputMods(unsigned RCID) const { return isRegClass(RCID); }
323
324 bool isVRegWithFP32InputMods() const {
325 return isVRegWithInputMods(AMDGPU::VGPR_32RegClassID);
326 }
327
328 bool isVRegWithFP64InputMods() const {
329 return isRegClassTarget(AMDGPU::VReg_64_AlignTarget);
330 }
331
332 bool isPackedFP16InputMods() const {
333 return isRegOrImmWithInputMods(AMDGPU::VS_32RegClassID, MVT::v2f16);
334 }
335
336 bool isPackedVGPRFP32InputMods() const {
337 return isRegOrImmWithInputMods(AMDGPU::VReg_64RegClassID, MVT::v2f32);
338 }
339
340 bool isVReg32() const { return isRegClass(AMDGPU::VGPR_32RegClassID); }
341
342 bool isVReg32OrOff() const { return isOff() || isVReg32(); }
343
344 bool isRsrcReg32() const { return isRegClass(AMDGPU::RsrcReg32RegClassID); }
345
346 bool isNull() const { return isRegKind() && getReg() == AMDGPU::SGPR_NULL; }
347
348 bool isAV_LdSt_32_Align2_RegOp() const {
349 return isRegClass(AMDGPU::VGPR_32RegClassID) ||
350 isRegClass(AMDGPU::AGPR_32RegClassID);
351 }
352
353 bool isVRegWithInputMods() const;
354 template <bool IsFake16> bool isT16_Lo128VRegWithInputMods() const;
355 template <bool IsFake16> bool isT16VRegWithInputMods() const;
356 bool isT16_LO16VRegWithInputMods() const;
357
358 bool isSDWAOperand(MVT type) const;
359 bool isSDWAFP16Operand() const;
360 bool isSDWAFP32Operand() const;
361 bool isSDWAInt16Operand() const;
362 bool isSDWAInt32Operand() const;
363
364 bool isImmTy(ImmTy ImmT) const { return isImm() && Imm.Type == ImmT; }
365
366 template <ImmTy Ty> bool isImmTy() const { return isImmTy(Ty); }
367
368 bool isImmLiteral() const { return isImmTy(ImmTyNone); }
369
370 bool isImmModifier() const { return isImm() && Imm.Type != ImmTyNone; }
371
372 bool isOModSI() const { return isImmTy(ImmTyOModSI); }
373 bool isDim() const { return isImmTy(ImmTyDim); }
374 bool isR128A16() const { return isImmTy(ImmTyR128A16); }
375 bool isOff() const { return isImmTy(ImmTyOff); }
376 bool isExpTgt() const { return isImmTy(ImmTyExpTgt); }
377 bool isOffen() const { return isImmTy(ImmTyOffen); }
378 bool isIdxen() const { return isImmTy(ImmTyIdxen); }
379 bool isAddr64() const { return isImmTy(ImmTyAddr64); }
380 bool isSMEMOffsetMod() const { return isImmTy(ImmTySMEMOffsetMod); }
381 bool isFlatOffset() const {
382 return isImmTy(ImmTyOffset) || isImmTy(ImmTyInstOffset);
383 }
384 bool isGDS() const { return isImmTy(ImmTyGDS); }
385 bool isLDS() const { return isImmTy(ImmTyLDS); }
386 bool isCPol() const { return isImmTy(ImmTyCPol); }
387 bool isIndexKey8bit() const { return isImmTy(ImmTyIndexKey8bit); }
388 bool isIndexKey16bit() const { return isImmTy(ImmTyIndexKey16bit); }
389 bool isIndexKey32bit() const { return isImmTy(ImmTyIndexKey32bit); }
390 bool isMatrixAFMT() const { return isImmTy(ImmTyMatrixAFMT); }
391 bool isMatrixBFMT() const { return isImmTy(ImmTyMatrixBFMT); }
392 bool isMatrixAScale() const { return isImmTy(ImmTyMatrixAScale); }
393 bool isMatrixBScale() const { return isImmTy(ImmTyMatrixBScale); }
394 bool isMatrixAScaleFmt() const { return isImmTy(ImmTyMatrixAScaleFmt); }
395 bool isMatrixBScaleFmt() const { return isImmTy(ImmTyMatrixBScaleFmt); }
396 bool isTFE() const { return isImmTy(ImmTyTFE); }
397 bool isFormat() const { return isImmTy(ImmTyFormat) && isUInt<7>(getImm()); }
398 bool isFormatOp() const {
399 return isImmTy(ImmTyFormatOp) && isUInt<7>(getImm());
400 }
401 bool isDppFI() const { return isImmTy(ImmTyDppFI); }
402 bool isSDWADstSel() const { return isImmTy(ImmTySDWADstSel); }
403 bool isSDWASrc0Sel() const { return isImmTy(ImmTySDWASrc0Sel); }
404 bool isSDWASrc1Sel() const { return isImmTy(ImmTySDWASrc1Sel); }
405 bool isSDWADstUnused() const { return isImmTy(ImmTySDWADstUnused); }
406 bool isInterpSlot() const { return isImmTy(ImmTyInterpSlot); }
407 bool isInterpAttr() const { return isImmTy(ImmTyInterpAttr); }
408 bool isInterpAttrChan() const { return isImmTy(ImmTyInterpAttrChan); }
409 bool isOpSel() const { return isImmTy(ImmTyOpSel); }
410 bool isOpSelHi() const { return isImmTy(ImmTyOpSelHi); }
411 bool isNegLo() const { return isImmTy(ImmTyNegLo); }
412 bool isNegHi() const { return isImmTy(ImmTyNegHi); }
413 bool isDone() const { return isImmTy(ImmTyDone); }
414 bool isRowEn() const { return isImmTy(ImmTyRowEn); }
415
416 bool isRegOrImm() const { return isReg() || isImm(); }
417
418 bool isRegClass(unsigned RCID) const;
419
420 // Check the register against the HwMode-resolved operand class.
421 bool isRegClassTarget(unsigned TargetRCIdx) const;
422
423 bool isInlineValue() const;
424
425 bool isRegOrInlineNoMods(unsigned RCID, MVT type) const {
426 return isRegOrInline(RCID, type) && !hasModifiers();
427 }
428
429 bool isRegOrInlineNoModsTarget(unsigned TargetRCIdx, MVT type) const {
430 return isRegOrInlineTarget(TargetRCIdx, type) && !hasModifiers();
431 }
432
433 bool isSCSrcB16() const {
434 return isRegOrInlineNoMods(AMDGPU::SReg_32RegClassID, MVT::i16);
435 }
436
437 bool isSCSrc_b32() const {
438 return isRegOrInlineNoMods(AMDGPU::SReg_32RegClassID, MVT::i32);
439 }
440
441 bool isSCSrc_b64() const {
442 return isRegOrInlineNoMods(AMDGPU::SReg_64RegClassID, MVT::i64);
443 }
444
445 bool isBoolReg() const;
446
447 bool isSSrc_b32() const {
448 return isSCSrc_b32() || isLiteralImm(MVT::i32) || isExpr();
449 }
450
451 bool isSSrc_b16() const { return isSCSrcB16() || isLiteralImm(MVT::i16); }
452
453 bool isSSrc_b64() const {
454 // TODO: Find out how SALU supports extension of 32-bit literals to 64 bits.
455 // See isVSrc64().
456 return isSCSrc_b64() || isLiteralImm(MVT::i64) ||
457 (((const MCTargetAsmParser *)AsmParser)
458 ->getAvailableFeatures()[AMDGPU::Feature64BitLiterals] &&
459 isExpr());
460 }
461
462 bool isSSrc_f32() const {
463 return isSCSrc_b32() || isLiteralImm(MVT::f32) || isExpr();
464 }
465
466 bool isSSrc_bf16() const { return isSCSrcB16() || isLiteralImm(MVT::bf16); }
467
468 bool isSSrc_f16() const { return isSCSrcB16() || isLiteralImm(MVT::f16); }
469
470 bool isSSrc_NoInline_f16() const { return isSSrc_f16(); }
471
472 bool isSSrcOrLds_b32() const {
473 return isRegOrInlineNoMods(AMDGPU::SRegOrLds_32RegClassID, MVT::i32) ||
474 isLiteralImm(MVT::i32) || isExpr();
475 }
476
477 bool isVCSrc_b32() const {
478 return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::i32);
479 }
480
481 bool isVCSrc_b32_Lo256() const {
482 return isRegOrInlineNoMods(AMDGPU::VS_32_Lo256RegClassID, MVT::i32);
483 }
484
485 bool isVCSrc_b64_Lo256() const {
486 return isRegOrInlineNoMods(AMDGPU::VS_64_Lo256RegClassID, MVT::i64);
487 }
488
489 bool isVCSrc_b64() const {
490 return isRegOrInlineNoModsTarget(AMDGPU::VS_64_AlignTarget, MVT::i64);
491 }
492
493 bool isVCSrcT_b16() const {
494 return isRegOrInlineNoMods(AMDGPU::VS_16RegClassID, MVT::i16);
495 }
496
497 bool isVCSrcTB16_Lo128() const {
498 return isRegOrInlineNoMods(AMDGPU::VS_16_Lo128RegClassID, MVT::i16);
499 }
500
501 bool isVCSrcFake16B16_Lo128() const {
502 return isRegOrInlineNoMods(AMDGPU::VS_32_Lo128RegClassID, MVT::i16);
503 }
504
505 bool isVCSrc_b16() const {
506 return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::i16);
507 }
508
509 bool isVCSrc_v2b16() const { return isVCSrc_b16(); }
510
511 bool isVCSrc_f32() const {
512 return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::f32);
513 }
514
515 bool isVCSrc_f64() const {
516 return isRegOrInlineNoModsTarget(AMDGPU::VS_64_AlignTarget, MVT::f64);
517 }
518
519 bool isVCSrcTBF16() const {
520 return isRegOrInlineNoMods(AMDGPU::VS_16RegClassID, MVT::bf16);
521 }
522
523 bool isVCSrcT_f16() const {
524 return isRegOrInlineNoMods(AMDGPU::VS_16RegClassID, MVT::f16);
525 }
526
527 bool isVCSrcT_bf16() const {
528 return isRegOrInlineNoMods(AMDGPU::VS_16RegClassID, MVT::f16);
529 }
530
531 bool isVCSrcTF16_LO16() const {
532 return isRegOrInlineNoMods(AMDGPU::VS_16_LO16RegClassID, MVT::f16);
533 }
534
535 bool isVCSrcTBF16_Lo128() const {
536 return isRegOrInlineNoMods(AMDGPU::VS_16_Lo128RegClassID, MVT::bf16);
537 }
538
539 bool isVCSrcTF16_Lo128() const {
540 return isRegOrInlineNoMods(AMDGPU::VS_16_Lo128RegClassID, MVT::f16);
541 }
542
543 bool isVCSrcFake16BF16_Lo128() const {
544 return isRegOrInlineNoMods(AMDGPU::VS_32_Lo128RegClassID, MVT::bf16);
545 }
546
547 bool isVCSrcFake16F16_Lo128() const {
548 return isRegOrInlineNoMods(AMDGPU::VS_32_Lo128RegClassID, MVT::f16);
549 }
550
551 bool isVCSrc_bf16() const {
552 return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::bf16);
553 }
554
555 bool isVCSrc_f16() const {
556 return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::f16);
557 }
558
559 bool isVCSrc_v2bf16() const { return isVCSrc_bf16(); }
560
561 bool isVCSrc_v2f16() const { return isVCSrc_f16(); }
562
563 bool isVSrc_b32() const {
564 return isVCSrc_f32() || isLiteralImm(MVT::i32) || isExpr();
565 }
566
567 bool isVSrc_b64() const { return isVCSrc_f64() || isLiteralImm(MVT::i64); }
568
569 bool isVSrc_v2b64() const {
570 return isRegOrInlineNoModsTarget(AMDGPU::VS_128_AlignTarget, MVT::i64) ||
571 isLiteralImm(MVT::i64);
572 }
573
574 bool isVSrc_v2f64() const {
575 return isRegOrInlineNoModsTarget(AMDGPU::VS_128_AlignTarget, MVT::f64) ||
576 isLiteralImm(MVT::f64);
577 }
578
579 bool isVSrcT_b16() const { return isVCSrcT_b16() || isLiteralImm(MVT::i16); }
580
581 bool isVSrcT_b16_Lo128() const {
582 return isVCSrcTB16_Lo128() || isLiteralImm(MVT::i16);
583 }
584
585 bool isVSrcFake16_b16_Lo128() const {
586 return isVCSrcFake16B16_Lo128() || isLiteralImm(MVT::i16);
587 }
588
589 bool isVSrc_b16() const { return isVCSrc_b16() || isLiteralImm(MVT::i16); }
590
591 bool isVSrc_v2b16() const { return isVSrc_b16() || isLiteralImm(MVT::v2i16); }
592
593 bool isVSrc_v2f32() const { return isVSrc_f64() || isLiteralImm(MVT::v2f32); }
594
595 bool isVCSrc_v2b32() const { return isVCSrc_b64(); }
596
597 bool isVSrc_v2b32() const { return isVSrc_b64() || isLiteralImm(MVT::v2i32); }
598
599 bool isVSrc_f32() const {
600 return isVCSrc_f32() || isLiteralImm(MVT::f32) || isExpr();
601 }
602
603 bool isVSrc_f64() const {
604 return isRegOrInlineNoModsTarget(AMDGPU::VS_64_AlignTarget, MVT::f64) ||
605 isLiteralImm(MVT::f64);
606 }
607
608 bool isVSrcT_bf16() const {
609 return isVCSrcTBF16() || isLiteralImm(MVT::bf16);
610 }
611
612 bool isVSrcT_f16() const { return isVCSrcT_f16() || isLiteralImm(MVT::f16); }
613
614 bool isVSrcT_f16_LO16() const {
615 return isVCSrcTF16_LO16() || isLiteralImm(MVT::f16);
616 }
617
618 bool isVSrcT_bf16_Lo128() const {
619 return isVCSrcTBF16_Lo128() || isLiteralImm(MVT::bf16);
620 }
621
622 bool isVSrcT_f16_Lo128() const {
623 return isVCSrcTF16_Lo128() || isLiteralImm(MVT::f16);
624 }
625
626 bool isVSrcFake16_bf16_Lo128() const {
627 return isVCSrcFake16BF16_Lo128() || isLiteralImm(MVT::bf16);
628 }
629
630 bool isVSrcFake16_f16_Lo128() const {
631 return isVCSrcFake16F16_Lo128() || isLiteralImm(MVT::f16);
632 }
633
634 bool isVSrc_bf16() const { return isVCSrc_bf16() || isLiteralImm(MVT::bf16); }
635
636 bool isVSrc_f16() const { return isVCSrc_f16() || isLiteralImm(MVT::f16); }
637
638 bool isVSrc_v2bf16() const {
639 return isVSrc_bf16() || isLiteralImm(MVT::v2bf16);
640 }
641
642 bool isVSrc_v2f16() const { return isVSrc_f16() || isLiteralImm(MVT::v2f16); }
643
644 bool isVSrc_v2f16_splat() const { return isVSrc_v2f16(); }
645
646 bool isVSrc_NoInline_v2f16() const { return isVSrc_v2f16(); }
647
648 bool isVISrc_64_bf16() const {
649 return isRegOrInlineNoModsTarget(AMDGPU::VReg_64_AlignTarget, MVT::bf16);
650 }
651
652 bool isVISrc_64_f16() const {
653 return isRegOrInlineNoModsTarget(AMDGPU::VReg_64_AlignTarget, MVT::f16);
654 }
655
656 bool isVISrc_64_b32() const {
657 return isRegOrInlineNoModsTarget(AMDGPU::VReg_64_AlignTarget, MVT::i32);
658 }
659
660 bool isVISrc_64_f64() const {
661 return isRegOrInlineNoModsTarget(AMDGPU::VReg_64_AlignTarget, MVT::f64);
662 }
663
664 bool isVISrc_256_b32() const {
665 return isRegOrInlineNoModsTarget(AMDGPU::VReg_256_AlignTarget, MVT::i32);
666 }
667
668 bool isVISrc_256_f32() const {
669 return isRegOrInlineNoModsTarget(AMDGPU::VReg_256_AlignTarget, MVT::f32);
670 }
671
672 bool isVISrc_256_f64() const {
673 return isRegOrInlineNoModsTarget(AMDGPU::VReg_256_AlignTarget, MVT::f64);
674 }
675
676 bool isVISrc_512_f64() const {
677 return isRegOrInlineNoModsTarget(AMDGPU::VReg_512_AlignTarget, MVT::f64);
678 }
679
680 bool isVISrc_128_b32() const {
681 return isRegOrInlineNoModsTarget(AMDGPU::VReg_128_AlignTarget, MVT::i32);
682 }
683
684 bool isVISrc_128_f32() const {
685 return isRegOrInlineNoModsTarget(AMDGPU::VReg_128_AlignTarget, MVT::f32);
686 }
687
688 bool isVISrc_512_b32() const {
689 return isRegOrInlineNoModsTarget(AMDGPU::VReg_512_AlignTarget, MVT::i32);
690 }
691
692 bool isVISrc_512_f32() const {
693 return isRegOrInlineNoModsTarget(AMDGPU::VReg_512_AlignTarget, MVT::f32);
694 }
695
696 bool isVISrc_1024_b32() const {
697 return isRegOrInlineNoModsTarget(AMDGPU::VReg_1024_AlignTarget, MVT::i32);
698 }
699
700 bool isVISrc_1024_f32() const {
701 return isRegOrInlineNoModsTarget(AMDGPU::VReg_1024_AlignTarget, MVT::f32);
702 }
703
704 bool isAISrc_64_f64() const {
705 return isRegOrInlineNoModsTarget(AMDGPU::AReg_64_AlignTarget, MVT::f64);
706 }
707
708 bool isAISrc_128_b32() const {
709 return isRegOrInlineNoModsTarget(AMDGPU::AReg_128_AlignTarget, MVT::i32);
710 }
711
712 bool isAISrc_128_f32() const {
713 return isRegOrInlineNoModsTarget(AMDGPU::AReg_128_AlignTarget, MVT::f32);
714 }
715
716 bool isVISrc_128_bf16() const {
717 return isRegOrInlineNoModsTarget(AMDGPU::VReg_128_AlignTarget, MVT::bf16);
718 }
719
720 bool isVISrc_128_f16() const {
721 return isRegOrInlineNoModsTarget(AMDGPU::VReg_128_AlignTarget, MVT::f16);
722 }
723
724 bool isAISrc_256_f64() const {
725 return isRegOrInlineNoModsTarget(AMDGPU::AReg_256_AlignTarget, MVT::f64);
726 }
727
728 bool isAISrc_512_b32() const {
729 return isRegOrInlineNoModsTarget(AMDGPU::AReg_512_AlignTarget, MVT::i32);
730 }
731
732 bool isAISrc_512_f32() const {
733 return isRegOrInlineNoModsTarget(AMDGPU::AReg_512_AlignTarget, MVT::f32);
734 }
735
736 bool isAISrc_1024_b32() const {
737 return isRegOrInlineNoModsTarget(AMDGPU::AReg_1024_AlignTarget, MVT::i32);
738 }
739
740 bool isAISrc_1024_f32() const {
741 return isRegOrInlineNoModsTarget(AMDGPU::AReg_1024_AlignTarget, MVT::f32);
742 }
743
744 bool isKImmFP32() const { return isLiteralImm(MVT::f32); }
745
746 bool isKImmFP16() const { return isLiteralImm(MVT::f16); }
747
748 bool isKImmFP64() const { return isLiteralImm(MVT::f64); }
749
750 bool isMem() const override { return false; }
751
752 bool isExpr() const { return Kind == Expression; }
753
754 bool isSOPPBrTarget() const { return isExpr() || isImm(); }
755
756 bool isSMEMOffsetPCRel() const { return isExpr() || isImm(); }
757
758 bool isSWaitCnt() const;
759 bool isDepCtr() const;
760 bool isSDelayALU() const;
761 bool isHwreg() const;
762 bool isSendMsg() const;
763 bool isWaitEvent() const;
764 bool isSplitBarrier() const;
765 bool isSwizzle() const;
766 bool isSMRDOffset8() const;
767 bool isSMEMOffset() const;
768 bool isSMRDLiteralOffset() const;
769 bool isDPP8() const;
770 bool isDPPCtrl() const;
771 bool isBLGP() const;
772 bool isGPRIdxMode() const;
773 bool isS16Imm() const;
774 bool isU16Imm() const;
775 bool isEndpgm() const;
776
777 auto getPredicate(std::function<bool(const AMDGPUOperand &Op)> P) const {
778 return [this, P]() { return P(*this); };
779 }
780
781 StringRef getToken() const {
782 assert(isToken());
783 return StringRef(Tok.Data, Tok.Length);
784 }
785
786 int64_t getImm() const {
787 assert(isImm());
788 return Imm.Val;
789 }
790
791 ImmTy getImmTy() const {
792 assert(isImm());
793 return Imm.Type;
794 }
795
796 MCRegister getReg() const override {
797 assert(isRegKind());
798 return Reg.RegNo;
799 }
800
801 SMLoc getStartLoc() const override { return StartLoc; }
802
803 SMLoc getEndLoc() const override { return EndLoc; }
804
805 int getMCOpIdx() const { return MCOpIdx; }
806
807 Modifiers getModifiers() const {
808 assert(isRegKind() || isImmTy(ImmTyNone));
809 return isRegKind() ? Reg.Mods : Imm.Mods;
810 }
811
812 void setModifiers(Modifiers Mods) {
813 assert(isRegKind() || isImmTy(ImmTyNone));
814 if (isRegKind())
815 Reg.Mods = Mods;
816 else
817 Imm.Mods = Mods;
818 }
819
820 bool hasModifiers() const { return getModifiers().hasModifiers(); }
821
822 bool hasFPModifiers() const { return getModifiers().hasFPModifiers(); }
823
824 bool hasIntModifiers() const { return getModifiers().hasIntModifiers(); }
825
826 bool isForcedLit() const {
827 return isImmLiteral() && getModifiers().isForcedLit();
828 }
829
830 bool isForcedLit64() const {
831 return isImmLiteral() && getModifiers().isForcedLit64();
832 }
833
834 uint64_t applyInputFPModifiers(uint64_t Val, unsigned Size) const;
835
836 void addImmOperands(MCInst &Inst, unsigned N,
837 bool ApplyModifiers = true) const;
838
839 void addLiteralImmOperand(MCInst &Inst, int64_t Val,
840 bool ApplyModifiers) const;
841
842 void addRegOperands(MCInst &Inst, unsigned N) const;
843
844 void addRegOrImmOperands(MCInst &Inst, unsigned N) const {
845 if (isRegKind())
846 addRegOperands(Inst, N);
847 else
848 addImmOperands(Inst, N);
849 }
850
851 void addRegOrImmWithInputModsOperands(MCInst &Inst, unsigned N) const {
852 Modifiers Mods = getModifiers();
853 Inst.addOperand(MCOperand::createImm(Mods.getModifiersOperand()));
854 if (isRegKind()) {
855 addRegOperands(Inst, N);
856 } else {
857 addImmOperands(Inst, N, false);
858 }
859 }
860
861 void addRegOrImmWithFPInputModsOperands(MCInst &Inst, unsigned N) const {
862 assert(!hasIntModifiers());
863 addRegOrImmWithInputModsOperands(Inst, N);
864 }
865
866 void addRegWithInputModsOperands(MCInst &Inst, unsigned N) const {
867 Modifiers Mods = getModifiers();
868 Inst.addOperand(MCOperand::createImm(Mods.getModifiersOperand()));
869 assert(isRegKind());
870 addRegOperands(Inst, N);
871 }
872
873 void addRegWithFPInputModsOperands(MCInst &Inst, unsigned N) const {
874 assert(!hasIntModifiers());
875 addRegWithInputModsOperands(Inst, N);
876 }
877
878 static void printImmTy(raw_ostream &OS, ImmTy Type) {
879 // clang-format off
880 switch (Type) {
881 case ImmTyNone: OS << "None"; break;
882 case ImmTyGDS: OS << "GDS"; break;
883 case ImmTyLDS: OS << "LDS"; break;
884 case ImmTyOffen: OS << "Offen"; break;
885 case ImmTyIdxen: OS << "Idxen"; break;
886 case ImmTyAddr64: OS << "Addr64"; break;
887 case ImmTyOffset: OS << "Offset"; break;
888 case ImmTyInstOffset: OS << "InstOffset"; break;
889 case ImmTyOffset0: OS << "Offset0"; break;
890 case ImmTyOffset1: OS << "Offset1"; break;
891 case ImmTySMEMOffsetMod: OS << "SMEMOffsetMod"; break;
892 case ImmTyCPol: OS << "CPol"; break;
893 case ImmTyIndexKey8bit: OS << "index_key"; break;
894 case ImmTyIndexKey16bit: OS << "index_key"; break;
895 case ImmTyIndexKey32bit: OS << "index_key"; break;
896 case ImmTyTFE: OS << "TFE"; break;
897 case ImmTyIsAsync: OS << "IsAsync"; break;
898 case ImmTyD16: OS << "D16"; break;
899 case ImmTyFormat: OS << "Format"; break;
900 case ImmTyFormatOp: OS << "FormatOp"; break;
901 case ImmTyClamp: OS << "Clamp"; break;
902 case ImmTyOModSI: OS << "OModSI"; break;
903 case ImmTyDPP8: OS << "DPP8"; break;
904 case ImmTyDppCtrl: OS << "DppCtrl"; break;
905 case ImmTyDppRowMask: OS << "DppRowMask"; break;
906 case ImmTyDppBankMask: OS << "DppBankMask"; break;
907 case ImmTyDppBoundCtrl: OS << "DppBoundCtrl"; break;
908 case ImmTyDppFI: OS << "DppFI"; break;
909 case ImmTySDWADstSel: OS << "SDWADstSel"; break;
910 case ImmTySDWASrc0Sel: OS << "SDWASrc0Sel"; break;
911 case ImmTySDWASrc1Sel: OS << "SDWASrc1Sel"; break;
912 case ImmTySDWADstUnused: OS << "SDWADstUnused"; break;
913 case ImmTyDMask: OS << "DMask"; break;
914 case ImmTyDim: OS << "Dim"; break;
915 case ImmTyUNorm: OS << "UNorm"; break;
916 case ImmTyDA: OS << "DA"; break;
917 case ImmTyR128A16: OS << "R128A16"; break;
918 case ImmTyA16: OS << "A16"; break;
919 case ImmTyLWE: OS << "LWE"; break;
920 case ImmTyOff: OS << "Off"; break;
921 case ImmTyExpTgt: OS << "ExpTgt"; break;
922 case ImmTyExpCompr: OS << "ExpCompr"; break;
923 case ImmTyExpVM: OS << "ExpVM"; break;
924 case ImmTyDone: OS << "Done"; break;
925 case ImmTyRowEn: OS << "RowEn"; break;
926 case ImmTyHwreg: OS << "Hwreg"; break;
927 case ImmTySendMsg: OS << "SendMsg"; break;
928 case ImmTyWaitEvent: OS << "WaitEvent"; break;
929 case ImmTyInterpSlot: OS << "InterpSlot"; break;
930 case ImmTyInterpAttr: OS << "InterpAttr"; break;
931 case ImmTyInterpAttrChan: OS << "InterpAttrChan"; break;
932 case ImmTyOpSel: OS << "OpSel"; break;
933 case ImmTyOpSelHi: OS << "OpSelHi"; break;
934 case ImmTyNegLo: OS << "NegLo"; break;
935 case ImmTyNegHi: OS << "NegHi"; break;
936 case ImmTySwizzle: OS << "Swizzle"; break;
937 case ImmTyGprIdxMode: OS << "GprIdxMode"; break;
938 case ImmTyHigh: OS << "High"; break;
939 case ImmTyBLGP: OS << "BLGP"; break;
940 case ImmTyCBSZ: OS << "CBSZ"; break;
941 case ImmTyABID: OS << "ABID"; break;
942 case ImmTyEndpgm: OS << "Endpgm"; break;
943 case ImmTyWaitVDST: OS << "WaitVDST"; break;
944 case ImmTyWaitEXP: OS << "WaitEXP"; break;
945 case ImmTyWaitVAVDst: OS << "WaitVAVDst"; break;
946 case ImmTyWaitVMVSrc: OS << "WaitVMVSrc"; break;
947 case ImmTyBitOp3: OS << "BitOp3"; break;
948 case ImmTyMatrixAFMT: OS << "ImmTyMatrixAFMT"; break;
949 case ImmTyMatrixBFMT: OS << "ImmTyMatrixBFMT"; break;
950 case ImmTyMatrixAScale: OS << "ImmTyMatrixAScale"; break;
951 case ImmTyMatrixBScale: OS << "ImmTyMatrixBScale"; break;
952 case ImmTyMatrixAScaleFmt: OS << "ImmTyMatrixAScaleFmt"; break;
953 case ImmTyMatrixBScaleFmt: OS << "ImmTyMatrixBScaleFmt"; break;
954 case ImmTyMatrixAReuse: OS << "ImmTyMatrixAReuse"; break;
955 case ImmTyMatrixBReuse: OS << "ImmTyMatrixBReuse"; break;
956 case ImmTyScaleSel: OS << "ScaleSel" ; break;
957 case ImmTyByteSel: OS << "ByteSel" ; break;
958 }
959 // clang-format on
960 }
961
962 void print(raw_ostream &OS, const MCAsmInfo &MAI) const override {
963 switch (Kind) {
964 case Register:
965 OS << "<register " << AMDGPUInstPrinter::getRegisterName(getReg())
966 << " mods: " << Reg.Mods << '>';
967 break;
968 case Immediate:
969 OS << '<' << getImm();
970 if (getImmTy() != ImmTyNone) {
971 OS << " type: ";
972 printImmTy(OS, getImmTy());
973 }
974 OS << " mods: " << Imm.Mods << '>';
975 break;
976 case Token:
977 OS << '\'' << getToken() << '\'';
978 break;
979 case Expression:
980 OS << "<expr ";
981 MAI.printExpr(OS, *Expr);
982 OS << '>';
983 break;
984 }
985 }
986
987 static AMDGPUOperand::Ptr CreateImm(const AMDGPUAsmParser *AsmParser,
988 int64_t Val, SMLoc Loc,
989 ImmTy Type = ImmTyNone,
990 bool IsFPImm = false) {
991 auto Op = std::make_unique<AMDGPUOperand>(Immediate, AsmParser);
992 Op->Imm.Val = Val;
993 Op->Imm.IsFPImm = IsFPImm;
994 Op->Imm.Type = Type;
995 Op->Imm.Mods = Modifiers();
996 Op->StartLoc = Loc;
997 Op->EndLoc = Loc;
998 return Op;
999 }
1000
1001 static AMDGPUOperand::Ptr CreateToken(const AMDGPUAsmParser *AsmParser,
1002 StringRef Str, SMLoc Loc,
1003 bool HasExplicitEncodingSize = true) {
1004 auto Res = std::make_unique<AMDGPUOperand>(Token, AsmParser);
1005 Res->Tok.Data = Str.data();
1006 Res->Tok.Length = Str.size();
1007 Res->StartLoc = Loc;
1008 Res->EndLoc = Loc;
1009 return Res;
1010 }
1011
1012 static AMDGPUOperand::Ptr CreateReg(const AMDGPUAsmParser *AsmParser,
1013 MCRegister Reg, SMLoc S, SMLoc E) {
1014 auto Op = std::make_unique<AMDGPUOperand>(Register, AsmParser);
1015 Op->Reg.RegNo = Reg;
1016 Op->Reg.Mods = Modifiers();
1017 Op->StartLoc = S;
1018 Op->EndLoc = E;
1019 return Op;
1020 }
1021
1022 static AMDGPUOperand::Ptr CreateExpr(const AMDGPUAsmParser *AsmParser,
1023 const class MCExpr *Expr, SMLoc S) {
1024 auto Op = std::make_unique<AMDGPUOperand>(Expression, AsmParser);
1025 Op->Expr = Expr;
1026 Op->StartLoc = S;
1027 Op->EndLoc = S;
1028 return Op;
1029 }
1030};
1031
1032raw_ostream &operator<<(raw_ostream &OS, AMDGPUOperand::Modifiers Mods) {
1033 OS << "abs:" << Mods.Abs << " neg: " << Mods.Neg << " sext:" << Mods.Sext;
1034 return OS;
1035}
1036
1037//===----------------------------------------------------------------------===//
1038// AsmParser
1039//===----------------------------------------------------------------------===//
1040
1041// TODO: define GET_SUBTARGET_FEATURE_NAME
1042#define GET_REGISTER_MATCHER
1043#include "AMDGPUGenAsmMatcher.inc"
1044#undef GET_REGISTER_MATCHER
1045#undef GET_SUBTARGET_FEATURE_NAME
1046
1047// Holds info related to the current kernel, e.g. count of SGPRs used.
1048// Kernel scope begins at .amdgpu_hsa_kernel directive, ends at next
1049// .amdgpu_hsa_kernel or at EOF.
1050class KernelScopeInfo {
1051 int SgprIndexUnusedMin = -1;
1052 int VgprIndexUnusedMin = -1;
1053 int AgprIndexUnusedMin = -1;
1054 MCContext *Ctx = nullptr;
1055 MCSubtargetInfo const *MSTI = nullptr;
1056
1057 void usesSgprAt(int i) {
1058 if (i >= SgprIndexUnusedMin) {
1059 SgprIndexUnusedMin = ++i;
1060 if (Ctx) {
1061 MCSymbol *const Sym =
1062 Ctx->getOrCreateSymbol(Twine(".kernel.sgpr_count"));
1063 Sym->setVariableValue(MCConstantExpr::create(SgprIndexUnusedMin, *Ctx));
1064 }
1065 }
1066 }
1067
1068 void usesVgprAt(int i) {
1069 if (i >= VgprIndexUnusedMin) {
1070 VgprIndexUnusedMin = ++i;
1071 if (Ctx) {
1072 MCSymbol *const Sym =
1073 Ctx->getOrCreateSymbol(Twine(".kernel.vgpr_count"));
1074 int totalVGPR =
1075 getTotalNumVGPRs(isGFX90A(*MSTI), std::max(AgprIndexUnusedMin, 0),
1076 VgprIndexUnusedMin);
1077 Sym->setVariableValue(MCConstantExpr::create(totalVGPR, *Ctx));
1078 }
1079 }
1080 }
1081
1082 void usesAgprAt(int i) {
1083 // Instruction will error in AMDGPUAsmParser::matchAndEmitInstruction
1084 if (!hasMAIInsts(*MSTI))
1085 return;
1086
1087 if (i >= AgprIndexUnusedMin) {
1088 AgprIndexUnusedMin = ++i;
1089 if (Ctx) {
1090 MCSymbol *const Sym =
1091 Ctx->getOrCreateSymbol(Twine(".kernel.agpr_count"));
1092 Sym->setVariableValue(MCConstantExpr::create(AgprIndexUnusedMin, *Ctx));
1093
1094 // Also update vgpr_count (dependent on agpr_count for gfx908/gfx90a)
1095 MCSymbol *const vSym =
1096 Ctx->getOrCreateSymbol(Twine(".kernel.vgpr_count"));
1097 int totalVGPR =
1098 getTotalNumVGPRs(isGFX90A(*MSTI), std::max(AgprIndexUnusedMin, 0),
1099 VgprIndexUnusedMin);
1100 vSym->setVariableValue(MCConstantExpr::create(totalVGPR, *Ctx));
1101 }
1102 }
1103 }
1104
1105public:
1106 KernelScopeInfo() = default;
1107
1108 void initialize(MCContext &Context) {
1109 Ctx = &Context;
1110 MSTI = Ctx->getSubtargetInfo();
1111
1112 usesSgprAt(SgprIndexUnusedMin = -1);
1113 usesVgprAt(VgprIndexUnusedMin = -1);
1114 if (hasMAIInsts(*MSTI)) {
1115 usesAgprAt(AgprIndexUnusedMin = -1);
1116 }
1117 }
1118
1119 void usesRegister(RegisterKind RegKind, unsigned DwordRegIndex,
1120 unsigned RegWidth) {
1121 switch (RegKind) {
1122 case IS_SGPR:
1123 usesSgprAt(DwordRegIndex + divideCeil(RegWidth, 32) - 1);
1124 break;
1125 case IS_AGPR:
1126 usesAgprAt(DwordRegIndex + divideCeil(RegWidth, 32) - 1);
1127 break;
1128 case IS_VGPR:
1129 usesVgprAt(DwordRegIndex + divideCeil(RegWidth, 32) - 1);
1130 break;
1131 default:
1132 break;
1133 }
1134 }
1135};
1136
1137class AMDGPUAsmParser : public MCTargetAsmParser {
1138 MCAsmParser &Parser;
1139
1140 unsigned ForcedEncodingSize = 0;
1141 bool ForcedDPP = false;
1142 bool ForcedSDWA = false;
1143 KernelScopeInfo KernelScope;
1144 const unsigned HwMode;
1145 const AMDGPU::GPUKind Gfx;
1146 const AMDGPU::IsaVersion ISA;
1147
1148 /// @name Auto-generated Match Functions
1149 /// {
1150
1151#define GET_ASSEMBLER_HEADER
1152#include "AMDGPUGenAsmMatcher.inc"
1153
1154 /// }
1155
1156 /// Get size of register operand
1157 unsigned getRegOperandSize(const MCInstrDesc &Desc, unsigned OpNo) const {
1158 assert(OpNo < Desc.NumOperands);
1159 int16_t RCID = MII.getOpRegClassID(Desc.operands()[OpNo], HwMode);
1160 return getRegBitWidth(RCID) / 8;
1161 }
1162
1163 std::optional<AMDGPU::InfoSectionData> InfoData;
1164
1165 /// State for checking that every kernel named in a .amdhsa_kernel directive
1166 /// begins with the required prologue instruction sequence. Because the
1167 /// directive may appear either before or after the kernel's label (it is
1168 /// normally emitted after the function body, in .rodata), validation is
1169 /// deferred to onEndOfFile(). We record an order-independent timeline of
1170 /// parsed labels and emitted instruction opcodes, plus the set of symbols
1171 /// named by .amdhsa_kernel directives, and match them up at end of file.
1172 SmallVector<unsigned> OpcodeStream;
1174 OpcodeStreamSymbols;
1175 SmallPtrSet<const MCSymbol *, 8> AMDHSAKernelSymbols;
1176
1177 /// Verify recorded kernel prologues.
1178 void checkKernelPrologues();
1179
1180private:
1181 void createConstantSymbol(StringRef Id, int64_t Val);
1182
1183 bool ParseAsAbsoluteExpression(uint32_t &Ret);
1184 bool OutOfRangeError(SMRange Range);
1185 /// Calculate VGPR/SGPR blocks required for given target, reserved
1186 /// registers, and user-specified NextFreeXGPR values.
1187 ///
1188 /// \param Features [in] Target features, used for bug corrections.
1189 /// \param VCCUsed [in] Whether VCC special SGPR is reserved.
1190 /// \param FlatScrUsed [in] Whether FLAT_SCRATCH special SGPR is reserved.
1191 /// \param XNACKUsed [in] Whether XNACK_MASK special SGPR is reserved.
1192 /// \param EnableWavefrontSize32 [in] Value of ENABLE_WAVEFRONT_SIZE32 kernel
1193 /// descriptor field, if valid.
1194 /// \param NextFreeVGPR [in] Max VGPR number referenced, plus one.
1195 /// \param VGPRRange [in] Token range, used for VGPR diagnostics.
1196 /// \param NextFreeSGPR [in] Max SGPR number referenced, plus one.
1197 /// \param SGPRRange [in] Token range, used for SGPR diagnostics.
1198 /// \param VGPRBlocks [out] Result VGPR block count.
1199 /// \param SGPRBlocks [out] Result SGPR block count.
1200 bool calculateGPRBlocks(const FeatureBitset &Features, const MCExpr *VCCUsed,
1201 const MCExpr *FlatScrUsed, bool XNACKUsed,
1202 std::optional<bool> EnableWavefrontSize32,
1203 const MCExpr *NextFreeVGPR, SMRange VGPRRange,
1204 const MCExpr *NextFreeSGPR, SMRange SGPRRange,
1205 const MCExpr *&VGPRBlocks, const MCExpr *&SGPRBlocks);
1206 bool ParseDirectiveAMDGCNTarget();
1207 bool ParseDirectiveAMDHSACodeObjectVersion();
1208 bool ParseDirectiveAMDHSAKernel();
1209 bool ParseAMDKernelCodeTValue(StringRef ID, AMDGPUMCKernelCodeT &Header);
1210 bool ParseDirectiveAMDKernelCodeT();
1211 // TODO: Possibly make subtargetHasRegister const.
1212 bool subtargetHasRegister(const MCRegisterInfo &MRI, MCRegister Reg);
1213 bool ParseDirectiveAMDGPUHsaKernel();
1214
1215 bool ParseDirectiveISAVersion();
1216 bool ParseDirectiveHSAMetadata();
1217 bool ParseDirectivePALMetadataBegin();
1218 bool ParseDirectivePALMetadata();
1219 bool ParseDirectiveAMDGPULDS();
1220 bool ParseDirectiveAMDGPUInfo();
1221
1222 /// Common code to parse out a block of text (typically YAML) between start
1223 /// and end directives.
1224 bool ParseToEndDirective(const char *AssemblerDirectiveBegin,
1225 const char *AssemblerDirectiveEnd,
1226 std::string &CollectString);
1227
1228 bool AddNextRegisterToList(MCRegister &Reg, unsigned &RegWidth,
1229 RegisterKind RegKind, MCRegister Reg1,
1230 RegisterKind RegKind1, SMLoc Loc);
1231 bool ParseAMDGPURegister(RegisterKind &RegKind, MCRegister &Reg,
1232 unsigned &RegNum, unsigned &RegWidth,
1233 bool RestoreOnFailure = false);
1234 bool ParseAMDGPURegister(RegisterKind &RegKind, MCRegister &Reg,
1235 unsigned &RegNum, unsigned &RegWidth,
1236 SmallVectorImpl<AsmToken> &Tokens);
1237 MCRegister ParseRegularReg(RegisterKind &RegKind, unsigned &RegNum,
1238 unsigned &RegWidth,
1239 SmallVectorImpl<AsmToken> &Tokens);
1240 MCRegister ParseSpecialReg(RegisterKind &RegKind, unsigned &RegNum,
1241 unsigned &RegWidth,
1242 SmallVectorImpl<AsmToken> &Tokens);
1243 MCRegister ParseRegList(RegisterKind &RegKind, unsigned &RegNum,
1244 unsigned &RegWidth,
1245 SmallVectorImpl<AsmToken> &Tokens);
1246 bool ParseRegRange(unsigned &Num, unsigned &Width, unsigned &SubReg);
1247 MCRegister getRegularReg(RegisterKind RegKind, unsigned RegNum,
1248 unsigned SubReg, unsigned RegWidth, SMLoc Loc);
1249
1250 bool isRegister();
1251 bool isRegister(const AsmToken &Token, const AsmToken &NextToken) const;
1252 std::optional<StringRef> getGprCountSymbolName(RegisterKind RegKind);
1253 void initializeGprCountSymbol(RegisterKind RegKind);
1254 bool updateGprCountSymbols(RegisterKind RegKind, unsigned DwordRegIndex,
1255 unsigned RegWidth);
1256 void cvtMubufImpl(MCInst &Inst, const OperandVector &Operands, bool IsAtomic);
1257
1258public:
1259 enum OperandMode {
1260 OperandMode_Default,
1261 OperandMode_NSA,
1262 };
1263
1264 using OptionalImmIndexMap = std::map<AMDGPUOperand::ImmTy, unsigned>;
1265
1266 AMDGPUAsmParser(const MCSubtargetInfo &STI, MCAsmParser &_Parser,
1267 const MCInstrInfo &MII)
1268 : MCTargetAsmParser(STI, MII), Parser(_Parser),
1269 HwMode(STI.getHwMode(MCSubtargetInfo::HwMode_RegInfo)),
1270 Gfx(AMDGPU::parseArchAMDGCN(STI.getCPU())),
1271 ISA(AMDGPU::getIsaVersion(STI.getCPU())) {
1273
1274 setAvailableFeatures(ComputeAvailableFeatures(getFeatureBits()));
1275
1276 if (ISA.Major >= 6 && isHsaAbi(getSTI())) {
1277 createConstantSymbol(".amdgcn.gfx_generation_number", ISA.Major);
1278 createConstantSymbol(".amdgcn.gfx_generation_minor", ISA.Minor);
1279 createConstantSymbol(".amdgcn.gfx_generation_stepping", ISA.Stepping);
1280 } else {
1281 createConstantSymbol(".option.machine_version_major", ISA.Major);
1282 createConstantSymbol(".option.machine_version_minor", ISA.Minor);
1283 createConstantSymbol(".option.machine_version_stepping", ISA.Stepping);
1284 }
1285 if (ISA.Major >= 6 && isHsaAbi(getSTI())) {
1286 initializeGprCountSymbol(IS_VGPR);
1287 initializeGprCountSymbol(IS_SGPR);
1288 } else
1289 KernelScope.initialize(getContext());
1290
1291 for (auto [Symbol, Code] : AMDGPU::UCVersion::getGFXVersions())
1292 createConstantSymbol(Symbol, Code);
1293
1294 createConstantSymbol("UC_VERSION_W64_BIT", 0x2000);
1295 createConstantSymbol("UC_VERSION_W32_BIT", 0x4000);
1296 createConstantSymbol("UC_VERSION_MDP_BIT", 0x8000);
1297 }
1298
1299 bool hasMIMG_R128() const { return AMDGPU::hasMIMG_R128(getSTI()); }
1300
1301 bool hasPackedD16() const { return AMDGPU::hasPackedD16(getSTI()); }
1302
1303 bool hasA16() const { return AMDGPU::hasA16(getSTI()); }
1304
1305 bool hasG16() const { return AMDGPU::hasG16(getSTI()); }
1306
1307 bool hasGDS() const { return AMDGPU::hasGDS(getSTI()); }
1308
1309 bool isSI() const { return AMDGPU::isSI(getSTI()); }
1310
1311 bool isCI() const { return AMDGPU::isCI(getSTI()); }
1312
1313 bool isVI() const { return AMDGPU::isVI(getSTI()); }
1314
1315 bool isGFX9() const { return AMDGPU::isGFX9(getSTI()); }
1316
1317 // TODO: isGFX90A is also true for GFX940. We need to clean it.
1318 bool isGFX90A() const { return AMDGPU::isGFX90A(getSTI()); }
1319
1320 bool isGFX940() const { return AMDGPU::isGFX940(getSTI()); }
1321
1322 bool isGFX9Plus() const { return AMDGPU::isGFX9Plus(getSTI()); }
1323
1324 bool isGFX10Plus() const { return AMDGPU::isGFX10Plus(getSTI()); }
1325
1326 bool isGFX11() const { return AMDGPU::isGFX11(getSTI()); }
1327
1328 bool isGFX11Plus() const { return AMDGPU::isGFX11Plus(getSTI()); }
1329
1330 bool isGFX12() const { return AMDGPU::isGFX12(getSTI()); }
1331
1332 bool isGFX12Plus() const { return AMDGPU::isGFX12Plus(getSTI()); }
1333
1334 bool isGFX1250Plus() const { return AMDGPU::isGFX1250Plus(getSTI()); }
1335
1336 bool hasBVHRayTracingInsts() const {
1337 return getFeatureBits()[AMDGPU::FeatureBVHRayTracingInsts];
1338 }
1339
1340 bool isWave32() const { return getAvailableFeatures()[Feature_isWave32Bit]; }
1341
1342 bool isWave64() const { return getAvailableFeatures()[Feature_isWave64Bit]; }
1343
1344 bool hasInv2PiInlineImm() const {
1345 return getFeatureBits()[AMDGPU::FeatureInv2PiInlineImm];
1346 }
1347
1348 bool has64BitLiterals() const {
1349 return getFeatureBits()[AMDGPU::Feature64BitLiterals];
1350 }
1351
1352 bool hasFlatOffsets() const {
1353 return getFeatureBits()[AMDGPU::FeatureFlatInstOffsets];
1354 }
1355
1356 bool hasTrue16Insts() const {
1357 return getFeatureBits()[AMDGPU::FeatureTrue16BitInsts];
1358 }
1359
1360 bool hasArchitectedFlatScratch() const {
1361 return getFeatureBits()[AMDGPU::FeatureArchitectedFlatScratch];
1362 }
1363
1364 bool hasSGPR102_SGPR103() const { return !isVI() && !isGFX9(); }
1365
1366 bool hasSGPR104_SGPR105() const { return isGFX10Plus(); }
1367
1368 bool hasIntClamp() const { return getFeatureBits()[AMDGPU::FeatureIntClamp]; }
1369
1370 bool hasPartialNSAEncoding() const {
1371 return getFeatureBits()[AMDGPU::FeaturePartialNSAEncoding];
1372 }
1373
1374 bool hasGloballyAddressableScratch() const {
1375 return getFeatureBits()[AMDGPU::FeatureGloballyAddressableScratch];
1376 }
1377
1378 bool hasScaleOffset() const {
1379 return getFeatureBits()[AMDGPU::FeatureScaleOffset];
1380 }
1381
1382 bool hasCacheFillSize() const {
1383 return getFeatureBits()[AMDGPU::FeatureCacheFillSize];
1384 }
1385
1386 unsigned getNSAMaxSize(bool HasSampler = false) const {
1387 return AMDGPU::getNSAMaxSize(getSTI(), HasSampler);
1388 }
1389
1390 unsigned getMaxNumUserSGPRs() const {
1391 return AMDGPU::getMaxNumUserSGPRs(getSTI());
1392 }
1393
1394 bool hasKernargPreload() const { return AMDGPU::hasKernargPreload(getSTI()); }
1395
1396 AMDGPUTargetStreamer &getTargetStreamer() {
1397 MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
1398 return static_cast<AMDGPUTargetStreamer &>(TS);
1399 }
1400
1401 MCContext &getContext() const {
1402 // We need this const_cast because for some reason getContext() is not const
1403 // in MCAsmParser.
1404 return const_cast<AMDGPUAsmParser *>(this)->MCTargetAsmParser::getContext();
1405 }
1406
1407 const MCRegisterInfo *getMRI() const {
1408 return getContext().getRegisterInfo();
1409 }
1410
1411 const MCInstrInfo *getMII() const { return &MII; }
1412
1413 // Resolve a RegClassByHwModeUses index to a register class id for the active
1414 // HwMode; -1 if the mode has no entry.
1415 int16_t getTargetRegClass(unsigned TargetRCIdx) const {
1416 return MII.getRegClassByHwModeTable(HwMode)[TargetRCIdx];
1417 }
1418
1419 // FIXME: This should not be used. Instead, should use queries derived from
1420 // getAvailableFeatures().
1421 const FeatureBitset &getFeatureBits() const {
1422 return getSTI().getFeatureBits();
1423 }
1424
1425 void setForcedEncodingSize(unsigned Size) { ForcedEncodingSize = Size; }
1426 void setForcedDPP(bool ForceDPP_) { ForcedDPP = ForceDPP_; }
1427 void setForcedSDWA(bool ForceSDWA_) { ForcedSDWA = ForceSDWA_; }
1428
1429 unsigned getForcedEncodingSize() const { return ForcedEncodingSize; }
1430 bool isForcedVOP3() const { return ForcedEncodingSize == 64; }
1431 bool isForcedDPP() const { return ForcedDPP; }
1432 bool isForcedSDWA() const { return ForcedSDWA; }
1433 ArrayRef<unsigned> getMatchedVariants() const;
1434 StringRef getMatchedVariantName() const;
1435
1436 std::unique_ptr<AMDGPUOperand> parseRegister(bool RestoreOnFailure = false);
1437 bool ParseRegister(MCRegister &RegNo, SMLoc &StartLoc, SMLoc &EndLoc,
1438 bool RestoreOnFailure);
1439 bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc) override;
1440 ParseStatus tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
1441 SMLoc &EndLoc) override;
1442 unsigned checkTargetMatchPredicate(MCInst &Inst) override;
1443 unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
1444 unsigned Kind) override;
1445 bool matchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1446 OperandVector &Operands, MCStreamer &Out,
1447 uint64_t &ErrorInfo,
1448 bool MatchingInlineAsm) override;
1449 bool ParseDirective(AsmToken DirectiveID) override;
1450 void doBeforeLabelEmit(MCSymbol *Symbol, SMLoc IDLoc) override;
1451 void onEndOfFile() override;
1452 ParseStatus parseOperand(OperandVector &Operands, StringRef Mnemonic,
1453 OperandMode Mode = OperandMode_Default);
1454 StringRef parseMnemonicSuffix(StringRef Name);
1455 bool parseInstruction(ParseInstructionInfo &Info, StringRef Name,
1456 SMLoc NameLoc, OperandVector &Operands) override;
1457 // bool ProcessInstruction(MCInst &Inst);
1458
1459 ParseStatus parseTokenOp(StringRef Name, OperandVector &Operands);
1460
1461 ParseStatus parseIntWithPrefix(const char *Prefix, int64_t &Int);
1462
1463 ParseStatus
1464 parseIntWithPrefix(const char *Prefix, OperandVector &Operands,
1465 AMDGPUOperand::ImmTy ImmTy = AMDGPUOperand::ImmTyNone,
1466 std::function<bool(int64_t &)> ConvertResult = nullptr);
1467
1468 ParseStatus parseOperandArrayWithPrefix(
1469 const char *Prefix, OperandVector &Operands,
1470 AMDGPUOperand::ImmTy ImmTy = AMDGPUOperand::ImmTyNone,
1471 bool (*ConvertResult)(int64_t &) = nullptr);
1472
1473 ParseStatus
1474 parseNamedBit(StringRef Name, OperandVector &Operands,
1475 AMDGPUOperand::ImmTy ImmTy = AMDGPUOperand::ImmTyNone,
1476 bool IgnoreNegative = false);
1477 unsigned getCPolKind(StringRef Id, StringRef Mnemo, bool &Disabling) const;
1478 ParseStatus parseCPol(OperandVector &Operands);
1479 ParseStatus parseScope(OperandVector &Operands, int64_t &Scope);
1480 ParseStatus parseTH(OperandVector &Operands, int64_t &TH);
1481 ParseStatus parseCFS(OperandVector &Operands, int64_t &CFS);
1482 ParseStatus parseStringWithPrefix(StringRef Prefix, StringRef &Value,
1483 SMLoc &StringLoc);
1484 ParseStatus parseStringOrIntWithPrefix(OperandVector &Operands,
1485 StringRef Name,
1486 ArrayRef<const char *> Ids,
1487 int64_t &IntVal);
1488 ParseStatus parseStringOrIntWithPrefix(OperandVector &Operands,
1489 StringRef Name,
1490 ArrayRef<const char *> Ids,
1491 AMDGPUOperand::ImmTy Type);
1492
1493 bool isModifier();
1494 bool isOperandModifier(const AsmToken &Token,
1495 const AsmToken &NextToken) const;
1496 bool isRegOrOperandModifier(const AsmToken &Token,
1497 const AsmToken &NextToken) const;
1498 bool isNamedOperandModifier(const AsmToken &Token,
1499 const AsmToken &NextToken) const;
1500 bool isOpcodeModifierWithVal(const AsmToken &Token,
1501 const AsmToken &NextToken) const;
1502 bool parseSP3NegModifier();
1503 ParseStatus parseImm(OperandVector &Operands, bool HasSP3AbsModifier = false,
1504 LitModifier Lit = LitModifier::None);
1505 ParseStatus parseReg(OperandVector &Operands);
1506 ParseStatus parseRegOrImm(OperandVector &Operands, bool HasSP3AbsMod = false,
1507 LitModifier Lit = LitModifier::None);
1508 ParseStatus parseRegOrImmWithFPInputMods(OperandVector &Operands,
1509 bool AllowImm = true);
1510 ParseStatus parseRegOrImmWithIntInputMods(OperandVector &Operands,
1511 bool AllowImm = true);
1512 ParseStatus parseRegWithFPInputMods(OperandVector &Operands);
1513 ParseStatus parseRegWithIntInputMods(OperandVector &Operands);
1514 ParseStatus parseRsrcReg(OperandVector &Operands);
1515 ParseStatus parseVReg32OrOff(OperandVector &Operands);
1516 ParseStatus tryParseIndexKey(OperandVector &Operands,
1517 AMDGPUOperand::ImmTy ImmTy);
1518 ParseStatus parseIndexKey8bit(OperandVector &Operands);
1519 ParseStatus parseIndexKey16bit(OperandVector &Operands);
1520 ParseStatus parseIndexKey32bit(OperandVector &Operands);
1521 ParseStatus tryParseMatrixFMT(OperandVector &Operands, StringRef Name,
1522 AMDGPUOperand::ImmTy Type);
1523 ParseStatus parseMatrixAFMT(OperandVector &Operands);
1524 ParseStatus parseMatrixBFMT(OperandVector &Operands);
1525 ParseStatus tryParseMatrixScale(OperandVector &Operands, StringRef Name,
1526 AMDGPUOperand::ImmTy Type);
1527 ParseStatus parseMatrixAScale(OperandVector &Operands);
1528 ParseStatus parseMatrixBScale(OperandVector &Operands);
1529 ParseStatus tryParseMatrixScaleFmt(OperandVector &Operands, StringRef Name,
1530 AMDGPUOperand::ImmTy Type);
1531 ParseStatus parseMatrixAScaleFmt(OperandVector &Operands);
1532 ParseStatus parseMatrixBScaleFmt(OperandVector &Operands);
1533
1534 ParseStatus parseDfmtNfmt(int64_t &Format);
1535 ParseStatus parseUfmt(int64_t &Format);
1536 ParseStatus parseSymbolicSplitFormat(StringRef FormatStr, SMLoc Loc,
1537 int64_t &Format);
1538 ParseStatus parseSymbolicUnifiedFormat(StringRef FormatStr, SMLoc Loc,
1539 int64_t &Format);
1540 ParseStatus parseFormat(OperandVector &Operands);
1541 ParseStatus parseFormatOp(OperandVector &Operands);
1542 ParseStatus parseSymbolicOrNumericFormat(int64_t &Format);
1543 ParseStatus parseNumericFormat(int64_t &Format);
1544 ParseStatus parseFlatOffset(OperandVector &Operands);
1545 ParseStatus parseR128A16(OperandVector &Operands);
1546 ParseStatus parseBLGP(OperandVector &Operands);
1547 ParseStatus tryParseFmt(const char *Pref, int64_t MaxVal, int64_t &Fmt);
1548 bool matchDfmtNfmt(int64_t &Dfmt, int64_t &Nfmt, StringRef FormatStr,
1549 SMLoc Loc);
1550
1551 void cvtExp(MCInst &Inst, const OperandVector &Operands);
1552
1553 bool parseCnt(int64_t &IntVal);
1554 ParseStatus parseSWaitCnt(OperandVector &Operands);
1555
1556 bool parseDepCtr(int64_t &IntVal, unsigned &Mask);
1557 void depCtrError(SMLoc Loc, int ErrorId, StringRef DepCtrName);
1558 ParseStatus parseDepCtr(OperandVector &Operands);
1559
1560 bool parseDelay(int64_t &Delay);
1561 ParseStatus parseSDelayALU(OperandVector &Operands);
1562
1563 ParseStatus parseHwreg(OperandVector &Operands);
1564
1565private:
1566 struct OperandInfoTy {
1567 SMLoc Loc;
1568 int64_t Val;
1569 bool IsSymbolic = false;
1570 bool IsDefined = false;
1571
1572 constexpr OperandInfoTy(int64_t Val) : Val(Val) {}
1573 };
1574
1575 struct StructuredOpField : OperandInfoTy {
1576 StringLiteral Id;
1577 StringLiteral Desc;
1578 unsigned Width;
1579 bool IsDefined = false;
1580
1581 constexpr StructuredOpField(StringLiteral Id, StringLiteral Desc,
1582 unsigned Width, int64_t Default)
1583 : OperandInfoTy(Default), Id(Id), Desc(Desc), Width(Width) {}
1584 virtual ~StructuredOpField() = default;
1585
1586 bool Error(AMDGPUAsmParser &Parser, const Twine &Err) const {
1587 Parser.Error(Loc, "invalid " + Desc + ": " + Err);
1588 return false;
1589 }
1590
1591 virtual bool validate(AMDGPUAsmParser &Parser) const {
1592 if (IsSymbolic && Val == OPR_ID_UNSUPPORTED)
1593 return Error(Parser, "not supported on this GPU");
1594 if (!isUIntN(Width, Val))
1595 return Error(Parser, "only " + Twine(Width) + "-bit values are legal");
1596 return true;
1597 }
1598 };
1599
1600 ParseStatus parseStructuredOpFields(ArrayRef<StructuredOpField *> Fields);
1601 bool validateStructuredOpFields(ArrayRef<const StructuredOpField *> Fields);
1602
1603 bool parseSendMsgBody(OperandInfoTy &Msg, OperandInfoTy &Op,
1604 OperandInfoTy &Stream);
1605 bool validateSendMsg(const OperandInfoTy &Msg, const OperandInfoTy &Op,
1606 const OperandInfoTy &Stream);
1607
1608 ParseStatus parseHwregFunc(OperandInfoTy &HwReg, OperandInfoTy &Offset,
1609 OperandInfoTy &Width);
1610
1611 const AMDGPUOperand &findMCOperand(const OperandVector &Operands,
1612 int MCOpIdx) const;
1613
1614 static SMLoc getLaterLoc(SMLoc a, SMLoc b);
1615
1616 SMLoc getFlatOffsetLoc(const OperandVector &Operands) const;
1617 SMLoc getSMEMOffsetLoc(const OperandVector &Operands) const;
1618 SMLoc getBLGPLoc(const OperandVector &Operands) const;
1619
1620 SMLoc getOperandLoc(const OperandVector &Operands, int MCOpIdx) const;
1621 SMLoc getOperandLoc(std::function<bool(const AMDGPUOperand &)> Test,
1622 const OperandVector &Operands) const;
1623 SMLoc getImmLoc(AMDGPUOperand::ImmTy Type,
1624 const OperandVector &Operands) const;
1625 SMLoc getInstLoc(const OperandVector &Operands) const;
1626
1627 bool validateInstruction(const MCInst &Inst, SMLoc IDLoc,
1628 const OperandVector &Operands);
1629 bool validateOffset(const MCInst &Inst, const OperandVector &Operands);
1630 bool validateFlatOffset(const MCInst &Inst, const OperandVector &Operands);
1631 bool validateSMEMOffset(const MCInst &Inst, const OperandVector &Operands);
1632 bool validateSMEMSData(const MCInst &Inst, const OperandVector &Operands);
1633 bool validateBF16InlineConst(const MCInst &Inst,
1634 const OperandVector &Operands);
1635 bool validateSOPLiteral(const MCInst &Inst, const OperandVector &Operands);
1636 bool validateConstantBusLimitations(const MCInst &Inst,
1637 const OperandVector &Operands);
1638 std::optional<unsigned> checkVOPDRegBankConstraints(const MCInst &Inst,
1639 bool AsVOPD3);
1640 bool validateVOPD(const MCInst &Inst, const OperandVector &Operands);
1641 bool tryVOPD(const MCInst &Inst);
1642 bool tryVOPD3(const MCInst &Inst);
1643 bool tryAnotherVOPDEncoding(const MCInst &Inst);
1644
1645 bool validateIntClampSupported(const MCInst &Inst);
1646 bool validateMIMGAtomicDMask(const MCInst &Inst);
1647 bool validateMIMGGatherDMask(const MCInst &Inst);
1648 bool validateMovrels(const MCInst &Inst, const OperandVector &Operands);
1649 bool validateMIMGDataSize(const MCInst &Inst, SMLoc IDLoc);
1650 bool validateMIMGAddrSize(const MCInst &Inst, SMLoc IDLoc);
1651 bool validateMIMGD16(const MCInst &Inst);
1652 bool validateMIMGDim(const MCInst &Inst, const OperandVector &Operands);
1653 bool validateTensorR128(const MCInst &Inst);
1654 bool validateMIMGMSAA(const MCInst &Inst);
1655 bool validateOpSel(const MCInst &Inst);
1656 bool validateTrue16OpSel(const MCInst &Inst);
1657 bool validateNeg(const MCInst &Inst, AMDGPU::OpName OpName);
1658 bool validateDPP(const MCInst &Inst, const OperandVector &Operands);
1659 bool validateVccOperand(MCRegister Reg) const;
1660 bool validateVOPLiteral(const MCInst &Inst, const OperandVector &Operands);
1661 bool validateMAIAccWrite(const MCInst &Inst, const OperandVector &Operands);
1662 bool validateMAISrc2(const MCInst &Inst, const OperandVector &Operands);
1663 bool validateMFMA(const MCInst &Inst, const OperandVector &Operands);
1664 bool validateAGPRLdSt(const MCInst &Inst) const;
1665 bool validateVGPRAlign(const MCInst &Inst) const;
1666 bool validateBLGP(const MCInst &Inst, const OperandVector &Operands);
1667 bool validateDS(const MCInst &Inst, const OperandVector &Operands);
1668 bool validateGWS(const MCInst &Inst, const OperandVector &Operands);
1669 bool validateDivScale(const MCInst &Inst);
1670 bool validateWaitCnt(const MCInst &Inst, const OperandVector &Operands);
1671 bool validateCoherencyBits(const MCInst &Inst, const OperandVector &Operands,
1672 SMLoc IDLoc);
1673 bool validateTHAndScopeBits(const MCInst &Inst, const OperandVector &Operands,
1674 const unsigned CPol);
1675 bool validateCFSBits(const MCInst &Inst, const OperandVector &Operands);
1676 bool validateTFE(const MCInst &Inst, const OperandVector &Operands);
1677 bool validateLdsDirect(const MCInst &Inst, const OperandVector &Operands);
1678 bool validateWMMA(const MCInst &Inst, const OperandVector &Operands);
1679 bool validateMonitorSleep(const MCInst &Inst, const OperandVector &Operands);
1680 bool validateClusterBarrierIsFirst(const MCInst &Inst,
1681 const OperandVector &Operands);
1682 bool validateScaleSel(const MCInst &Inst, const OperandVector &Operands);
1683 unsigned getConstantBusLimit(unsigned Opcode) const;
1684 bool usesConstantBus(const MCInst &Inst, unsigned OpIdx);
1685 bool isInlineConstant(const MCInst &Inst, unsigned OpIdx) const;
1686 MCRegister findImplicitSGPRReadInVOP(const MCInst &Inst) const;
1687
1688 bool isSupportedMnemo(StringRef Mnemo, const FeatureBitset &FBS);
1689 bool isSupportedMnemo(StringRef Mnemo, const FeatureBitset &FBS,
1690 ArrayRef<unsigned> Variants);
1691 bool checkUnsupportedInstruction(StringRef Name, SMLoc IDLoc);
1692
1693 bool isId(const StringRef Id) const;
1694 bool isId(const AsmToken &Token, const StringRef Id) const;
1695 bool isToken(const AsmToken::TokenKind Kind) const;
1696 StringRef getId() const;
1697 bool trySkipId(const StringRef Id);
1698 bool trySkipId(const StringRef Pref, const StringRef Id);
1699 bool trySkipId(const StringRef Id, const AsmToken::TokenKind Kind);
1700 bool trySkipToken(const AsmToken::TokenKind Kind);
1701 bool skipToken(const AsmToken::TokenKind Kind, const StringRef ErrMsg);
1702 bool parseString(StringRef &Val,
1703 const StringRef ErrMsg = "expected a string");
1704 bool parseId(StringRef &Val, const StringRef ErrMsg = "");
1705
1706 void peekTokens(MutableArrayRef<AsmToken> Tokens);
1707 AsmToken::TokenKind getTokenKind() const;
1708 bool parseExpr(int64_t &Imm, StringRef Expected = "");
1710 StringRef getTokenStr() const;
1711 AsmToken peekToken(bool ShouldSkipSpace = true);
1712 AsmToken getToken() const;
1713 SMLoc getLoc() const;
1714 void lex();
1715
1716public:
1717 void onBeginOfFile() override;
1718 /// Emit the deferred leading .amdgcn_target directive if it has not been
1719 /// emitted yet. Called before emitting the first instruction or kernel
1720 /// descriptor, so that any leading .amdgcn_target/.amd_amdgpu_isa directive
1721 /// in the source has had a chance to update the target ID first.
1722 void emitTargetDirective();
1723 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
1724
1725 ParseStatus parseCustomOperand(OperandVector &Operands, unsigned MCK);
1726
1727 ParseStatus parseExpTgt(OperandVector &Operands);
1728 ParseStatus parseSendMsg(OperandVector &Operands);
1729 ParseStatus parseWaitEvent(OperandVector &Operands);
1730 ParseStatus parseInterpSlot(OperandVector &Operands);
1731 ParseStatus parseInterpAttr(OperandVector &Operands);
1732 ParseStatus parseSOPPBrTarget(OperandVector &Operands);
1733 ParseStatus parseSMEMOffsetPCRel(OperandVector &Operands);
1734 ParseStatus parseBoolReg(OperandVector &Operands);
1735
1736 bool parseSwizzleOperand(int64_t &Op, const unsigned MinVal,
1737 const unsigned MaxVal, const Twine &ErrMsg,
1738 SMLoc &Loc);
1739 bool parseSwizzleOperands(const unsigned OpNum, int64_t *Op,
1740 const unsigned MinVal, const unsigned MaxVal,
1741 const StringRef ErrMsg);
1742 ParseStatus parseSwizzle(OperandVector &Operands);
1743 bool parseSwizzleOffset(int64_t &Imm);
1744 bool parseSwizzleMacro(int64_t &Imm);
1745 bool parseSwizzleQuadPerm(int64_t &Imm);
1746 bool parseSwizzleBitmaskPerm(int64_t &Imm);
1747 bool parseSwizzleBroadcast(int64_t &Imm);
1748 bool parseSwizzleSwap(int64_t &Imm);
1749 bool parseSwizzleReverse(int64_t &Imm);
1750 bool parseSwizzleFFT(int64_t &Imm);
1751 bool parseSwizzleRotate(int64_t &Imm);
1752
1753 ParseStatus parseGPRIdxMode(OperandVector &Operands);
1754 int64_t parseGPRIdxMacro();
1755
1756 void cvtMubuf(MCInst &Inst, const OperandVector &Operands) {
1757 cvtMubufImpl(Inst, Operands, false);
1758 }
1759 void cvtMubufAtomic(MCInst &Inst, const OperandVector &Operands) {
1760 cvtMubufImpl(Inst, Operands, true);
1761 }
1762
1763 ParseStatus parseOModSI(OperandVector &Operands);
1764
1765 void cvtVOP3(MCInst &Inst, const OperandVector &Operands,
1766 OptionalImmIndexMap &OptionalIdx);
1767 void cvtScaledMFMA(MCInst &Inst, const OperandVector &Operands);
1768 void cvtVOP3OpSel(MCInst &Inst, const OperandVector &Operands);
1769 void cvtVOP3(MCInst &Inst, const OperandVector &Operands);
1770 void cvtVOP3P(MCInst &Inst, const OperandVector &Operands);
1771 void cvtSWMMAC(MCInst &Inst, const OperandVector &Operands);
1772
1773 void cvtVOPD(MCInst &Inst, const OperandVector &Operands);
1774 void cvtVOP3OpSel(MCInst &Inst, const OperandVector &Operands,
1775 OptionalImmIndexMap &OptionalIdx);
1776 void cvtVOP3P(MCInst &Inst, const OperandVector &Operands,
1777 OptionalImmIndexMap &OptionalIdx);
1778
1779 void cvtVOP3Interp(MCInst &Inst, const OperandVector &Operands);
1780 void cvtVINTERP(MCInst &Inst, const OperandVector &Operands);
1781 void cvtOpSelHelper(MCInst &Inst, unsigned OpSel);
1782
1783 bool parseDimId(unsigned &Encoding);
1784 ParseStatus parseDim(OperandVector &Operands);
1785 bool convertDppBoundCtrl(int64_t &BoundCtrl);
1786 ParseStatus parseDPP8(OperandVector &Operands);
1787 ParseStatus parseDPPCtrl(OperandVector &Operands);
1788 bool isSupportedDPPCtrl(StringRef Ctrl, const OperandVector &Operands);
1789 int64_t parseDPPCtrlSel(StringRef Ctrl);
1790 int64_t parseDPPCtrlPerm();
1791 void cvtDPP(MCInst &Inst, const OperandVector &Operands, bool IsDPP8 = false);
1792 void cvtDPP8(MCInst &Inst, const OperandVector &Operands) {
1793 cvtDPP(Inst, Operands, true);
1794 }
1795 void cvtVOP3DPP(MCInst &Inst, const OperandVector &Operands,
1796 bool IsDPP8 = false);
1797 void cvtVOP3DPP8(MCInst &Inst, const OperandVector &Operands) {
1798 cvtVOP3DPP(Inst, Operands, true);
1799 }
1800
1801 ParseStatus parseSDWASel(OperandVector &Operands, StringRef Prefix,
1802 AMDGPUOperand::ImmTy Type);
1803 ParseStatus parseSDWADstUnused(OperandVector &Operands);
1804 void cvtSdwaVOP1(MCInst &Inst, const OperandVector &Operands);
1805 void cvtSdwaVOP2(MCInst &Inst, const OperandVector &Operands);
1806 void cvtSdwaVOP2b(MCInst &Inst, const OperandVector &Operands);
1807 void cvtSdwaVOP2e(MCInst &Inst, const OperandVector &Operands);
1808 void cvtSdwaVOPC(MCInst &Inst, const OperandVector &Operands);
1809
1810 enum class SDWAInstType : unsigned { VOP1 = 0, VOP2 = 1, VOPC = 2 };
1811
1812 void cvtSDWA(MCInst &Inst, const OperandVector &Operands,
1813 SDWAInstType BasicInstType, bool SkipDstVcc = false,
1814 bool SkipSrcVcc = false);
1815
1816 ParseStatus parseEndpgm(OperandVector &Operands);
1817
1818 ParseStatus parseVOPD(OperandVector &Operands);
1819};
1820
1821} // end anonymous namespace
1822
1823// May be called with integer type with equivalent bitwidth.
1824static const fltSemantics *getFltSemantics(unsigned Size) {
1825 switch (Size) {
1826 case 4:
1827 return &APFloat::IEEEsingle();
1828 case 8:
1829 return &APFloat::IEEEdouble();
1830 case 2:
1831 return &APFloat::IEEEhalf();
1832 default:
1833 llvm_unreachable("unsupported fp type");
1834 }
1835}
1836
1838 return getFltSemantics(VT.getScalarSizeInBits() / 8);
1839}
1840
1842 switch (OperandType) {
1843 // When floating-point immediate is used as operand of type i16, the 32-bit
1844 // representation of the constant truncated to the 16 LSBs should be used.
1859 return &APFloat::IEEEsingle();
1868 return &APFloat::IEEEdouble();
1877 return &APFloat::IEEEhalf();
1882 return &APFloat::BFloat();
1883 default:
1884 llvm_unreachable("unsupported fp type");
1885 }
1886}
1887
1888//===----------------------------------------------------------------------===//
1889// Operand
1890//===----------------------------------------------------------------------===//
1891
1892static bool canLosslesslyConvertToFPType(APFloat &FPLiteral, MVT VT) {
1893 bool Lost;
1894
1895 // Convert literal to single precision
1896 APFloat::opStatus Status = FPLiteral.convert(
1898 // We allow precision lost but not overflow or underflow
1899 if (Status != APFloat::opOK && Lost &&
1900 ((Status & APFloat::opOverflow) != 0 ||
1901 (Status & APFloat::opUnderflow) != 0)) {
1902 return false;
1903 }
1904
1905 return true;
1906}
1907
1908static bool isSafeTruncation(int64_t Val, unsigned Size) {
1909 return isUIntN(Size, Val) || isIntN(Size, Val);
1910}
1911
1912static bool isInlineableLiteralOp16(int64_t Val, MVT VT, bool HasInv2Pi) {
1913 if (VT.getScalarType() == MVT::i16)
1914 return isInlinableLiteral32(Val, HasInv2Pi);
1915
1916 if (VT.getScalarType() == MVT::f16)
1917 return AMDGPU::isInlinableLiteralFP16(Val, HasInv2Pi);
1918
1919 assert(VT.getScalarType() == MVT::bf16);
1920
1921 return AMDGPU::isInlinableLiteralBF16(Val, HasInv2Pi);
1922}
1923
1924bool AMDGPUOperand::isInlinableImm(MVT type) const {
1925
1926 // This is a hack to enable named inline values like
1927 // shared_base with both 32-bit and 64-bit operands.
1928 // Note that these values are defined as
1929 // 32-bit operands only.
1930 if (isInlineValue()) {
1931 return true;
1932 }
1933
1934 if (!isImmTy(ImmTyNone)) {
1935 // Only plain immediates are inlinable (e.g. "clamp" attribute is not)
1936 return false;
1937 }
1938
1939 if (getModifiers().Lit != LitModifier::None)
1940 return false;
1941
1942 // TODO: We should avoid using host float here. It would be better to
1943 // check the float bit values which is what a few other places do.
1944 // We've had bot failures before due to weird NaN support on mips hosts.
1945
1946 APInt Literal(64, Imm.Val);
1947
1948 if (Imm.IsFPImm) { // We got fp literal token
1949 if (type == MVT::f64 || type == MVT::i64) { // Expected 64-bit operand
1951 AsmParser->hasInv2PiInlineImm());
1952 }
1953
1954 APFloat FPLiteral(APFloat::IEEEdouble(), APInt(64, Imm.Val));
1955 if (!canLosslesslyConvertToFPType(FPLiteral, type))
1956 return false;
1957
1958 if (type.getScalarSizeInBits() == 16) {
1959 bool Lost = false;
1960 switch (type.getScalarType().SimpleTy) {
1961 default:
1962 llvm_unreachable("unknown 16-bit type");
1963 case MVT::bf16:
1964 FPLiteral.convert(APFloatBase::BFloat(), APFloat::rmNearestTiesToEven,
1965 &Lost);
1966 break;
1967 case MVT::f16:
1968 FPLiteral.convert(APFloatBase::IEEEhalf(), APFloat::rmNearestTiesToEven,
1969 &Lost);
1970 break;
1971 case MVT::i16:
1972 FPLiteral.convert(APFloatBase::IEEEsingle(),
1973 APFloat::rmNearestTiesToEven, &Lost);
1974 break;
1975 }
1976 // We need to use 32-bit representation here because when a floating-point
1977 // inline constant is used as an i16 operand, its 32-bit representation
1978 // representation will be used. We will need the 32-bit value to check if
1979 // it is FP inline constant.
1980 uint32_t ImmVal = FPLiteral.bitcastToAPInt().getZExtValue();
1981 return isInlineableLiteralOp16(ImmVal, type,
1982 AsmParser->hasInv2PiInlineImm());
1983 }
1984
1985 // Check if single precision literal is inlinable
1987 static_cast<int32_t>(FPLiteral.bitcastToAPInt().getZExtValue()),
1988 AsmParser->hasInv2PiInlineImm());
1989 }
1990
1991 // We got int literal token.
1992 if (type == MVT::f64 || type == MVT::i64) { // Expected 64-bit operand
1994 AsmParser->hasInv2PiInlineImm());
1995 }
1996
1997 if (!isSafeTruncation(Imm.Val, type.getScalarSizeInBits())) {
1998 return false;
1999 }
2000
2001 if (type.getScalarSizeInBits() == 16) {
2003 static_cast<int16_t>(Literal.getLoBits(16).getSExtValue()), type,
2004 AsmParser->hasInv2PiInlineImm());
2005 }
2006
2008 static_cast<int32_t>(Literal.getLoBits(32).getZExtValue()),
2009 AsmParser->hasInv2PiInlineImm());
2010}
2011
2012bool AMDGPUOperand::isLiteralImm(MVT type) const {
2013 // Check that this immediate can be added as literal
2014 if (!isImmTy(ImmTyNone)) {
2015 return false;
2016 }
2017
2018 bool Allow64Bit =
2019 (type == MVT::i64 || type == MVT::f64) && AsmParser->has64BitLiterals();
2020
2021 if (!Imm.IsFPImm) {
2022 // We got int literal token.
2023
2024 if (type == MVT::f64 && hasFPModifiers()) {
2025 // Cannot apply fp modifiers to int literals preserving the same semantics
2026 // for VOP1/2/C and VOP3 because of integer truncation. To avoid
2027 // ambiguity, disable these cases.
2028 return false;
2029 }
2030
2031 unsigned Size = type.getSizeInBits();
2032 if (Size == 64) {
2033 if (Allow64Bit && !AMDGPU::isValid32BitLiteral(Imm.Val, false))
2034 return true;
2035 Size = 32;
2036 }
2037
2038 // FIXME: 64-bit operands can zero extend, sign extend, or pad zeroes for FP
2039 // types.
2040 return isSafeTruncation(Imm.Val, Size);
2041 }
2042
2043 // We got fp literal token
2044 if (type == MVT::f64) { // Expected 64-bit fp operand
2045 // We would set low 64-bits of literal to zeroes but we accept this literals
2046 return true;
2047 }
2048
2049 if (type == MVT::i64) { // Expected 64-bit int operand
2050 // We don't allow fp literals in 64-bit integer instructions. It is
2051 // unclear how we should encode them.
2052 return false;
2053 }
2054
2055 // We allow fp literals with f16x2 operands assuming that the specified
2056 // literal goes into the lower half and the upper half is zero. We also
2057 // require that the literal may be losslessly converted to f16.
2058 //
2059 // For i16x2 operands, we assume that the specified literal is encoded as a
2060 // single-precision float. This is pretty odd, but it matches SP3 and what
2061 // happens in hardware.
2062 MVT ExpectedType = (type == MVT::v2f16) ? MVT::f16
2063 : (type == MVT::v2i16) ? MVT::f32
2064 : (type == MVT::v2f32) ? MVT::f32
2065 : type;
2066
2067 APFloat FPLiteral(APFloat::IEEEdouble(), APInt(64, Imm.Val));
2068 return canLosslesslyConvertToFPType(FPLiteral, ExpectedType);
2069}
2070
2071bool AMDGPUOperand::isRegClassTarget(unsigned TargetRCIdx) const {
2072 if (!isRegKind())
2073 return false;
2074 int16_t RCID = AsmParser->getTargetRegClass(TargetRCIdx);
2075 return RCID >= 0 && isRegClass(RCID);
2076}
2077
2078bool AMDGPUOperand::isRegClass(unsigned RCID) const {
2079 return isRegKind() &&
2080 AsmParser->getMRI()->getRegClass(RCID).contains(getReg());
2081}
2082
2083bool AMDGPUOperand::isVRegWithInputMods() const {
2084 return isRegClass(AMDGPU::VGPR_32RegClassID) ||
2085 // GFX90A allows DPP on 64-bit operands.
2086 (AsmParser->getFeatureBits()[AMDGPU::FeatureDPALU_DPP] &&
2087 isRegClassTarget(AMDGPU::VReg_64_AlignTarget));
2088}
2089
2090template <bool IsFake16>
2091bool AMDGPUOperand::isT16_Lo128VRegWithInputMods() const {
2092 return isRegClass(IsFake16 ? AMDGPU::VGPR_32_Lo128RegClassID
2093 : AMDGPU::VGPR_16_Lo128RegClassID);
2094}
2095
2096template <bool IsFake16> bool AMDGPUOperand::isT16VRegWithInputMods() const {
2097 return isRegClass(IsFake16 ? AMDGPU::VGPR_32RegClassID
2098 : AMDGPU::VGPR_16RegClassID);
2099}
2100
2101bool AMDGPUOperand::isT16_LO16VRegWithInputMods() const {
2102 return isRegClass(AMDGPU::VGPR_16_LO16RegClassID);
2103}
2104
2105bool AMDGPUOperand::isSDWAOperand(MVT type) const {
2106 if (AsmParser->isVI())
2107 return isVReg32();
2108 if (AsmParser->isGFX9Plus())
2109 return isRegClass(AMDGPU::VS_32RegClassID) || isInlinableImm(type);
2110 return false;
2111}
2112
2113bool AMDGPUOperand::isSDWAFP16Operand() const {
2114 return isSDWAOperand(MVT::f16);
2115}
2116
2117bool AMDGPUOperand::isSDWAFP32Operand() const {
2118 return isSDWAOperand(MVT::f32);
2119}
2120
2121bool AMDGPUOperand::isSDWAInt16Operand() const {
2122 return isSDWAOperand(MVT::i16);
2123}
2124
2125bool AMDGPUOperand::isSDWAInt32Operand() const {
2126 return isSDWAOperand(MVT::i32);
2127}
2128
2129bool AMDGPUOperand::isBoolReg() const {
2130 return isReg() && ((AsmParser->isWave64() && isSCSrc_b64()) ||
2131 (AsmParser->isWave32() && isSCSrc_b32()));
2132}
2133
2134uint64_t AMDGPUOperand::applyInputFPModifiers(uint64_t Val,
2135 unsigned Size) const {
2136 assert(isImmTy(ImmTyNone) && Imm.Mods.hasFPModifiers());
2137 assert(Size == 2 || Size == 4 || Size == 8);
2138
2139 const uint64_t FpSignMask = (1ULL << (Size * 8 - 1));
2140
2141 if (Imm.Mods.Abs) {
2142 Val &= ~FpSignMask;
2143 }
2144 if (Imm.Mods.Neg) {
2145 Val ^= FpSignMask;
2146 }
2147
2148 return Val;
2149}
2150
2151void AMDGPUOperand::addImmOperands(MCInst &Inst, unsigned N,
2152 bool ApplyModifiers) const {
2153 MCOpIdx = Inst.getNumOperands();
2154
2155 if (isExpr()) {
2157 return;
2158 }
2159
2160 if (AMDGPU::isSISrcOperand(AsmParser->getMII()->get(Inst.getOpcode()),
2161 Inst.getNumOperands())) {
2162 addLiteralImmOperand(Inst, Imm.Val,
2163 ApplyModifiers & isImmTy(ImmTyNone) &&
2164 Imm.Mods.hasFPModifiers());
2165 } else {
2166 assert(!isImmTy(ImmTyNone) || !hasModifiers());
2168 }
2169}
2170
2171void AMDGPUOperand::addLiteralImmOperand(MCInst &Inst, int64_t Val,
2172 bool ApplyModifiers) const {
2173 const auto &InstDesc = AsmParser->getMII()->get(Inst.getOpcode());
2174 auto OpNum = Inst.getNumOperands();
2175 // Check that this operand accepts literals
2176 assert(AMDGPU::isSISrcOperand(InstDesc, OpNum));
2177
2178 if (ApplyModifiers) {
2179 assert(AMDGPU::isSISrcFPOperand(InstDesc, OpNum));
2180 const unsigned Size =
2181 Imm.IsFPImm ? sizeof(double) : getOperandSize(InstDesc, OpNum);
2182 Val = applyInputFPModifiers(Val, Size);
2183 }
2184
2185 APInt Literal(64, Val);
2186 uint8_t OpTy = InstDesc.operands()[OpNum].OperandType;
2187
2188 bool CanUse64BitLiterals =
2189 AsmParser->has64BitLiterals() && !SIInstrFlags::isVOP3Like(InstDesc);
2190 LitModifier Lit = getModifiers().Lit;
2191 MCContext &Ctx = AsmParser->getContext();
2192
2193 if (Imm.IsFPImm) { // We got fp literal token
2194 switch (OpTy) {
2202 if (Lit == LitModifier::None &&
2204 AsmParser->hasInv2PiInlineImm())) {
2205 Inst.addOperand(MCOperand::createImm(Literal.getZExtValue()));
2206 return;
2207 }
2208
2209 // Non-inlineable
2210 if (AMDGPU::isSISrcFPOperand(InstDesc,
2211 OpNum)) { // Expected 64-bit fp operand
2212 bool HasMandatoryLiteral =
2213 AMDGPU::hasNamedOperand(Inst.getOpcode(), AMDGPU::OpName::imm);
2214 // For fp operands we check if low 32 bits are zeros
2215 if (Literal.getLoBits(32) != 0 &&
2216 (InstDesc.getSize() != 4 || !AsmParser->has64BitLiterals()) &&
2217 !HasMandatoryLiteral) {
2218 const_cast<AMDGPUAsmParser *>(AsmParser)->Warning(
2219 Inst.getLoc(),
2220 "Can't encode literal as exact 64-bit floating-point operand. "
2221 "Low 32-bits will be set to zero");
2222 Val &= 0xffffffff00000000u;
2223 }
2224
2225 if ((OpTy == AMDGPU::OPERAND_REG_IMM_FP64 ||
2228 if (CanUse64BitLiterals && Lit == LitModifier::None &&
2229 (isInt<32>(Val) || isUInt<32>(Val))) {
2230 // The floating-point operand will be verbalized as an
2231 // integer one. If that integer happens to fit 32 bits, on
2232 // re-assembling it will be intepreted as the high half of
2233 // the actual value, so we have to wrap it into lit64().
2234 Lit = LitModifier::Lit64;
2235 } else if (Lit == LitModifier::Lit) {
2236 // For FP64 operands lit() specifies the high half of the value.
2237 Val = Hi_32(Val);
2238 }
2239 }
2240 break;
2241 }
2242
2243 // We don't allow fp literals in 64-bit integer instructions. It is
2244 // unclear how we should encode them. This case should be checked earlier
2245 // in predicate methods (isLiteralImm())
2246 llvm_unreachable("fp literal in 64-bit integer instruction.");
2247
2249 if (CanUse64BitLiterals && Lit == LitModifier::None &&
2250 (isInt<32>(Val) || isUInt<32>(Val)))
2251 Lit = LitModifier::Lit64;
2252 break;
2253
2258 if (Lit == LitModifier::None && AsmParser->hasInv2PiInlineImm() &&
2259 Literal == 0x3fc45f306725feed) {
2260 // This is the 1/(2*pi) which is going to be truncated to bf16 with the
2261 // loss of precision. The constant represents idiomatic fp32 value of
2262 // 1/(2*pi) = 0.15915494 since bf16 is in fact fp32 with cleared low 16
2263 // bits. Prevent rounding below.
2264 Inst.addOperand(MCOperand::createImm(0x3e22));
2265 return;
2266 }
2267 [[fallthrough]];
2268
2291 bool lost;
2292 APFloat FPLiteral(APFloat::IEEEdouble(), Literal);
2293 // Convert literal to single precision
2294 FPLiteral.convert(*getOpFltSemantics(OpTy), APFloat::rmNearestTiesToEven,
2295 &lost);
2296 // We allow precision lost but not overflow or underflow. This should be
2297 // checked earlier in isLiteralImm()
2298
2299 Val = FPLiteral.bitcastToAPInt().getZExtValue();
2300 break;
2301 }
2302 default:
2303 llvm_unreachable("invalid operand size");
2304 }
2305
2306 if (Lit != LitModifier::None) {
2307 Inst.addOperand(
2309 } else {
2311 }
2312 return;
2313 }
2314
2315 // We got int literal token.
2316 // Only sign extend inline immediates.
2317 switch (OpTy) {
2332 break;
2333
2337 if (Lit == LitModifier::None &&
2338 AMDGPU::isInlinableLiteral64(Val, AsmParser->hasInv2PiInlineImm())) {
2340 return;
2341 }
2342
2343 // When the 32 MSBs are not zero (effectively means it can't be safely
2344 // truncated to uint32_t), if the target doesn't support 64-bit literals, or
2345 // the lit modifier is explicitly used, we need to truncate it to the 32
2346 // LSBs.
2347 if (!AsmParser->has64BitLiterals() || Lit == LitModifier::Lit)
2348 Val = Lo_32(Val);
2349 break;
2350
2355 if (Lit == LitModifier::None &&
2356 AMDGPU::isInlinableLiteral64(Val, AsmParser->hasInv2PiInlineImm())) {
2358 return;
2359 }
2360
2361 // If the target doesn't support 64-bit literals, we need to use the
2362 // constant as the high 32 MSBs of a double-precision floating point value.
2363 if (!AsmParser->has64BitLiterals()) {
2364 Val = static_cast<uint64_t>(Val) << 32;
2365 } else {
2366 // Now the target does support 64-bit literals, there are two cases
2367 // where we still want to use src_literal encoding:
2368 // 1) explicitly forced by using lit modifier;
2369 // 2) the value is a valid 32-bit representation (signed or unsigned),
2370 // meanwhile not forced by lit64 modifier.
2371 if (Lit == LitModifier::Lit ||
2372 (Lit != LitModifier::Lit64 && (isInt<32>(Val) || isUInt<32>(Val))))
2373 Val = static_cast<uint64_t>(Val) << 32;
2374 }
2375
2376 // For FP64 operands lit() specifies the high half of the value.
2377 if (Lit == LitModifier::Lit)
2378 Val = Hi_32(Val);
2379 break;
2380
2393 break;
2394
2396 if ((isInt<32>(Val) || isUInt<32>(Val)) && Lit != LitModifier::Lit64)
2397 Val <<= 32;
2398 break;
2399
2400 default:
2401 llvm_unreachable("invalid operand type");
2402 }
2403
2404 if (Lit != LitModifier::None) {
2405 Inst.addOperand(
2407 } else {
2409 }
2410}
2411
2412void AMDGPUOperand::addRegOperands(MCInst &Inst, unsigned N) const {
2413 MCOpIdx = Inst.getNumOperands();
2414 Inst.addOperand(
2415 MCOperand::createReg(AMDGPU::getMCReg(getReg(), AsmParser->getSTI())));
2416}
2417
2418bool AMDGPUOperand::isInlineValue() const {
2419 return isRegKind() && ::isInlineValue(getReg());
2420}
2421
2422//===----------------------------------------------------------------------===//
2423// AsmParser
2424//===----------------------------------------------------------------------===//
2425
2426void AMDGPUAsmParser::createConstantSymbol(StringRef Id, int64_t Val) {
2427 // TODO: make those pre-defined variables read-only.
2428 // Currently there is none suitable machinery in the core llvm-mc for this.
2429 // MCSymbol::isRedefinable is intended for another purpose, and
2430 // AsmParser::parseDirectiveSet() cannot be specialized for specific target.
2431 MCContext &Ctx = getContext();
2432 MCSymbol *Sym = Ctx.getOrCreateSymbol(Id);
2434}
2435
2436static int getRegClass(RegisterKind Is, unsigned RegWidth) {
2437 if (Is == IS_VGPR) {
2438 switch (RegWidth) {
2439 default:
2440 return -1;
2441 case 32:
2442 return AMDGPU::VGPR_32RegClassID;
2443 case 64:
2444 return AMDGPU::VReg_64RegClassID;
2445 case 96:
2446 return AMDGPU::VReg_96RegClassID;
2447 case 128:
2448 return AMDGPU::VReg_128RegClassID;
2449 case 160:
2450 return AMDGPU::VReg_160RegClassID;
2451 case 192:
2452 return AMDGPU::VReg_192RegClassID;
2453 case 224:
2454 return AMDGPU::VReg_224RegClassID;
2455 case 256:
2456 return AMDGPU::VReg_256RegClassID;
2457 case 288:
2458 return AMDGPU::VReg_288RegClassID;
2459 case 320:
2460 return AMDGPU::VReg_320RegClassID;
2461 case 352:
2462 return AMDGPU::VReg_352RegClassID;
2463 case 384:
2464 return AMDGPU::VReg_384RegClassID;
2465 case 512:
2466 return AMDGPU::VReg_512RegClassID;
2467 case 1024:
2468 return AMDGPU::VReg_1024RegClassID;
2469 }
2470 } else if (Is == IS_TTMP) {
2471 switch (RegWidth) {
2472 default:
2473 return -1;
2474 case 32:
2475 return AMDGPU::TTMP_32RegClassID;
2476 case 64:
2477 return AMDGPU::TTMP_64RegClassID;
2478 case 128:
2479 return AMDGPU::TTMP_128RegClassID;
2480 case 256:
2481 return AMDGPU::TTMP_256RegClassID;
2482 case 512:
2483 return AMDGPU::TTMP_512RegClassID;
2484 }
2485 } else if (Is == IS_SGPR) {
2486 switch (RegWidth) {
2487 default:
2488 return -1;
2489 case 32:
2490 return AMDGPU::SGPR_32RegClassID;
2491 case 64:
2492 return AMDGPU::SGPR_64RegClassID;
2493 case 96:
2494 return AMDGPU::SGPR_96RegClassID;
2495 case 128:
2496 return AMDGPU::SGPR_128RegClassID;
2497 case 160:
2498 return AMDGPU::SGPR_160RegClassID;
2499 case 192:
2500 return AMDGPU::SGPR_192RegClassID;
2501 case 224:
2502 return AMDGPU::SGPR_224RegClassID;
2503 case 256:
2504 return AMDGPU::SGPR_256RegClassID;
2505 case 288:
2506 return AMDGPU::SGPR_288RegClassID;
2507 case 320:
2508 return AMDGPU::SGPR_320RegClassID;
2509 case 352:
2510 return AMDGPU::SGPR_352RegClassID;
2511 case 384:
2512 return AMDGPU::SGPR_384RegClassID;
2513 case 512:
2514 return AMDGPU::SGPR_512RegClassID;
2515 }
2516 } else if (Is == IS_AGPR) {
2517 switch (RegWidth) {
2518 default:
2519 return -1;
2520 case 32:
2521 return AMDGPU::AGPR_32RegClassID;
2522 case 64:
2523 return AMDGPU::AReg_64RegClassID;
2524 case 96:
2525 return AMDGPU::AReg_96RegClassID;
2526 case 128:
2527 return AMDGPU::AReg_128RegClassID;
2528 case 160:
2529 return AMDGPU::AReg_160RegClassID;
2530 case 192:
2531 return AMDGPU::AReg_192RegClassID;
2532 case 224:
2533 return AMDGPU::AReg_224RegClassID;
2534 case 256:
2535 return AMDGPU::AReg_256RegClassID;
2536 case 288:
2537 return AMDGPU::AReg_288RegClassID;
2538 case 320:
2539 return AMDGPU::AReg_320RegClassID;
2540 case 352:
2541 return AMDGPU::AReg_352RegClassID;
2542 case 384:
2543 return AMDGPU::AReg_384RegClassID;
2544 case 512:
2545 return AMDGPU::AReg_512RegClassID;
2546 case 1024:
2547 return AMDGPU::AReg_1024RegClassID;
2548 }
2549 }
2550 return -1;
2551}
2552
2555 .Case("exec", AMDGPU::EXEC)
2556 .Case("vcc", AMDGPU::VCC)
2557 .Case("flat_scratch", AMDGPU::FLAT_SCR)
2558 .Case("xnack_mask", AMDGPU::XNACK_MASK)
2559 .Case("shared_base", AMDGPU::SRC_SHARED_BASE)
2560 .Case("src_shared_base", AMDGPU::SRC_SHARED_BASE)
2561 .Case("shared_limit", AMDGPU::SRC_SHARED_LIMIT)
2562 .Case("src_shared_limit", AMDGPU::SRC_SHARED_LIMIT)
2563 .Case("private_base", AMDGPU::SRC_PRIVATE_BASE)
2564 .Case("src_private_base", AMDGPU::SRC_PRIVATE_BASE)
2565 .Case("private_limit", AMDGPU::SRC_PRIVATE_LIMIT)
2566 .Case("src_private_limit", AMDGPU::SRC_PRIVATE_LIMIT)
2567 .Case("src_flat_scratch_base_lo", AMDGPU::SRC_FLAT_SCRATCH_BASE_LO)
2568 .Case("src_flat_scratch_base_hi", AMDGPU::SRC_FLAT_SCRATCH_BASE_HI)
2569 .Case("pops_exiting_wave_id", AMDGPU::SRC_POPS_EXITING_WAVE_ID)
2570 .Case("src_pops_exiting_wave_id", AMDGPU::SRC_POPS_EXITING_WAVE_ID)
2571 .Case("lds_direct", AMDGPU::LDS_DIRECT)
2572 .Case("src_lds_direct", AMDGPU::LDS_DIRECT)
2573 .Case("m0", AMDGPU::M0)
2574 .Case("vccz", AMDGPU::SRC_VCCZ)
2575 .Case("src_vccz", AMDGPU::SRC_VCCZ)
2576 .Case("execz", AMDGPU::SRC_EXECZ)
2577 .Case("src_execz", AMDGPU::SRC_EXECZ)
2578 .Case("scc", AMDGPU::SRC_SCC)
2579 .Case("src_scc", AMDGPU::SRC_SCC)
2580 .Case("tba", AMDGPU::TBA)
2581 .Case("tma", AMDGPU::TMA)
2582 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2583 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2584 .Case("xnack_mask_lo", AMDGPU::XNACK_MASK_LO)
2585 .Case("xnack_mask_hi", AMDGPU::XNACK_MASK_HI)
2586 .Case("vcc_lo", AMDGPU::VCC_LO)
2587 .Case("vcc_hi", AMDGPU::VCC_HI)
2588 .Case("exec_lo", AMDGPU::EXEC_LO)
2589 .Case("exec_hi", AMDGPU::EXEC_HI)
2590 .Case("tma_lo", AMDGPU::TMA_LO)
2591 .Case("tma_hi", AMDGPU::TMA_HI)
2592 .Case("tba_lo", AMDGPU::TBA_LO)
2593 .Case("tba_hi", AMDGPU::TBA_HI)
2594 .Case("pc", AMDGPU::PC_REG)
2595 .Case("null", AMDGPU::SGPR_NULL)
2596 .Default(AMDGPU::NoRegister);
2597}
2598
2599bool AMDGPUAsmParser::ParseRegister(MCRegister &RegNo, SMLoc &StartLoc,
2600 SMLoc &EndLoc, bool RestoreOnFailure) {
2601 auto R = parseRegister();
2602 if (!R)
2603 return true;
2604 assert(R->isReg());
2605 RegNo = R->getReg();
2606 StartLoc = R->getStartLoc();
2607 EndLoc = R->getEndLoc();
2608 return false;
2609}
2610
2611bool AMDGPUAsmParser::parseRegister(MCRegister &Reg, SMLoc &StartLoc,
2612 SMLoc &EndLoc) {
2613 return ParseRegister(Reg, StartLoc, EndLoc, /*RestoreOnFailure=*/false);
2614}
2615
2616ParseStatus AMDGPUAsmParser::tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
2617 SMLoc &EndLoc) {
2618 bool Result = ParseRegister(Reg, StartLoc, EndLoc, /*RestoreOnFailure=*/true);
2619 bool PendingErrors = getParser().hasPendingError();
2620 getParser().clearPendingErrors();
2621 if (PendingErrors)
2622 return ParseStatus::Failure;
2623 if (Result)
2624 return ParseStatus::NoMatch;
2625 return ParseStatus::Success;
2626}
2627
2628bool AMDGPUAsmParser::AddNextRegisterToList(MCRegister &Reg, unsigned &RegWidth,
2629 RegisterKind RegKind,
2630 MCRegister Reg1,
2631 RegisterKind RegKind1, SMLoc Loc) {
2632 // Allow VCC_LO/HI at the end of SGPR lists.
2633 if (RegKind == IS_SGPR) {
2634 unsigned RegIdx = (Reg - AMDGPU::SGPR0) + RegWidth / 32;
2635 if ((RegIdx == 106 && Reg1 == AMDGPU::VCC_LO) ||
2636 (RegIdx == 107 && Reg1 == AMDGPU::VCC_HI)) {
2637 RegWidth += 32;
2638 return true;
2639 }
2640 }
2641
2642 if (RegKind != RegKind1) {
2643 Error(Loc, "registers in a list must be of the same kind");
2644 return false;
2645 }
2646
2647 switch (RegKind) {
2648 case IS_SPECIAL:
2649 if (Reg == AMDGPU::EXEC_LO && Reg1 == AMDGPU::EXEC_HI) {
2650 Reg = AMDGPU::EXEC;
2651 RegWidth = 64;
2652 return true;
2653 }
2654 if (Reg == AMDGPU::FLAT_SCR_LO && Reg1 == AMDGPU::FLAT_SCR_HI) {
2655 Reg = AMDGPU::FLAT_SCR;
2656 RegWidth = 64;
2657 return true;
2658 }
2659 if (Reg == AMDGPU::XNACK_MASK_LO && Reg1 == AMDGPU::XNACK_MASK_HI) {
2660 Reg = AMDGPU::XNACK_MASK;
2661 RegWidth = 64;
2662 return true;
2663 }
2664 if (Reg == AMDGPU::VCC_LO && Reg1 == AMDGPU::VCC_HI) {
2665 Reg = AMDGPU::VCC;
2666 RegWidth = 64;
2667 return true;
2668 }
2669 if (Reg == AMDGPU::TBA_LO && Reg1 == AMDGPU::TBA_HI) {
2670 Reg = AMDGPU::TBA;
2671 RegWidth = 64;
2672 return true;
2673 }
2674 if (Reg == AMDGPU::TMA_LO && Reg1 == AMDGPU::TMA_HI) {
2675 Reg = AMDGPU::TMA;
2676 RegWidth = 64;
2677 return true;
2678 }
2679 Error(Loc, "register does not fit in the list");
2680 return false;
2681 case IS_VGPR:
2682 case IS_SGPR:
2683 case IS_AGPR:
2684 case IS_TTMP:
2685 if (Reg1 != Reg + RegWidth / 32) {
2686 Error(Loc, "registers in a list must have consecutive indices");
2687 return false;
2688 }
2689 RegWidth += 32;
2690 return true;
2691 default:
2692 llvm_unreachable("unexpected register kind");
2693 }
2694}
2695
2696struct RegInfo {
2698 RegisterKind Kind;
2699};
2700
2701static constexpr RegInfo RegularRegisters[] = {
2702 {{"v"}, IS_VGPR}, {{"s"}, IS_SGPR}, {{"ttmp"}, IS_TTMP},
2703 {{"acc"}, IS_AGPR}, {{"a"}, IS_AGPR},
2704};
2705
2706static bool isRegularReg(RegisterKind Kind) {
2707 return Kind == IS_VGPR || Kind == IS_SGPR || Kind == IS_TTMP ||
2708 Kind == IS_AGPR;
2709}
2710
2712 for (const RegInfo &Reg : RegularRegisters)
2713 if (Str.starts_with(Reg.Name))
2714 return &Reg;
2715 return nullptr;
2716}
2717
2718static bool getRegNum(StringRef Str, unsigned &Num) {
2719 return !Str.getAsInteger(10, Num);
2720}
2721
2722bool AMDGPUAsmParser::isRegister(const AsmToken &Token,
2723 const AsmToken &NextToken) const {
2724
2725 // A list of consecutive registers: [s0,s1,s2,s3]
2726 if (Token.is(AsmToken::LBrac))
2727 return true;
2728
2729 if (!Token.is(AsmToken::Identifier))
2730 return false;
2731
2732 // A single register like s0 or a range of registers like s[0:1]
2733
2734 StringRef Str = Token.getString();
2735 const RegInfo *Reg = getRegularRegInfo(Str);
2736 if (Reg) {
2737 StringRef RegName = Reg->Name;
2738 StringRef RegSuffix = Str.substr(RegName.size());
2739 if (!RegSuffix.empty()) {
2740 RegSuffix.consume_back(".l");
2741 RegSuffix.consume_back(".h");
2742 unsigned Num;
2743 // A single register with an index: rXX
2744 if (getRegNum(RegSuffix, Num))
2745 return true;
2746 } else {
2747 // A range of registers: r[XX:YY].
2748 if (NextToken.is(AsmToken::LBrac))
2749 return true;
2750 }
2751 }
2752
2753 return getSpecialRegForName(Str).isValid();
2754}
2755
2756bool AMDGPUAsmParser::isRegister() {
2757 return isRegister(getToken(), peekToken());
2758}
2759
2760MCRegister AMDGPUAsmParser::getRegularReg(RegisterKind RegKind, unsigned RegNum,
2761 unsigned SubReg, unsigned RegWidth,
2762 SMLoc Loc) {
2763 assert(isRegularReg(RegKind));
2764
2765 unsigned AlignSize = 1;
2766 if (RegKind == IS_SGPR || RegKind == IS_TTMP) {
2767 // SGPR and TTMP registers must be aligned.
2768 // Max required alignment is 4 dwords.
2769 AlignSize = std::min(llvm::bit_ceil(RegWidth / 32), 4u);
2770 }
2771
2772 if (RegNum % AlignSize != 0) {
2773 Error(Loc, "invalid register alignment");
2774 return MCRegister();
2775 }
2776
2777 unsigned RegIdx = RegNum / AlignSize;
2778 int RCID = getRegClass(RegKind, RegWidth);
2779 if (RCID == -1) {
2780 Error(Loc, "invalid or unsupported register size");
2781 return MCRegister();
2782 }
2783
2784 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
2785 const MCRegisterClass &RC = TRI->getRegClass(RCID);
2786 if (RegIdx >= RC.getNumRegs() || (RegKind == IS_VGPR && RegIdx > 255)) {
2787 Error(Loc, "register index is out of range");
2788 return AMDGPU::NoRegister;
2789 }
2790
2791 if (RegKind == IS_VGPR && !isGFX1250Plus() && RegIdx + RegWidth / 32 > 256) {
2792 Error(Loc, "register index is out of range");
2793 return MCRegister();
2794 }
2795
2796 MCRegister Reg = RC.getRegister(RegIdx);
2797
2798 if (SubReg) {
2799 Reg = TRI->getSubReg(Reg, SubReg);
2800
2801 if (!Reg)
2802 Error(Loc, "invalid subregister");
2803 }
2804
2805 return Reg;
2806}
2807
2808bool AMDGPUAsmParser::ParseRegRange(unsigned &Num, unsigned &RegWidth,
2809 unsigned &SubReg) {
2810 int64_t RegLo, RegHi;
2811 if (!skipToken(AsmToken::LBrac, "missing register index"))
2812 return false;
2813
2814 SMLoc FirstIdxLoc = getLoc();
2815 SMLoc SecondIdxLoc;
2816
2817 if (!parseExpr(RegLo))
2818 return false;
2819
2820 if (trySkipToken(AsmToken::Colon)) {
2821 SecondIdxLoc = getLoc();
2822 if (!parseExpr(RegHi))
2823 return false;
2824 } else {
2825 RegHi = RegLo;
2826 }
2827
2828 if (!skipToken(AsmToken::RBrac, "expected a closing square bracket"))
2829 return false;
2830
2831 if (!isUInt<32>(RegLo)) {
2832 Error(FirstIdxLoc, "invalid register index");
2833 return false;
2834 }
2835
2836 if (!isUInt<32>(RegHi)) {
2837 Error(SecondIdxLoc, "invalid register index");
2838 return false;
2839 }
2840
2841 if (RegLo > RegHi) {
2842 Error(FirstIdxLoc, "first register index should not exceed second index");
2843 return false;
2844 }
2845
2846 if (RegHi == RegLo) {
2847 StringRef RegSuffix = getTokenStr();
2848 if (RegSuffix == ".l") {
2849 SubReg = AMDGPU::lo16;
2850 lex();
2851 } else if (RegSuffix == ".h") {
2852 SubReg = AMDGPU::hi16;
2853 lex();
2854 }
2855 }
2856
2857 Num = static_cast<unsigned>(RegLo);
2858 RegWidth = 32 * ((RegHi - RegLo) + 1);
2859
2860 return true;
2861}
2862
2863MCRegister AMDGPUAsmParser::ParseSpecialReg(RegisterKind &RegKind,
2864 unsigned &RegNum,
2865 unsigned &RegWidth,
2866 SmallVectorImpl<AsmToken> &Tokens) {
2867 assert(isToken(AsmToken::Identifier));
2868 MCRegister Reg = getSpecialRegForName(getTokenStr());
2869 if (Reg) {
2870 RegNum = 0;
2871 RegWidth = 32;
2872 RegKind = IS_SPECIAL;
2873 Tokens.push_back(getToken());
2874 lex(); // skip register name
2875 }
2876 return Reg;
2877}
2878
2879MCRegister AMDGPUAsmParser::ParseRegularReg(RegisterKind &RegKind,
2880 unsigned &RegNum,
2881 unsigned &RegWidth,
2882 SmallVectorImpl<AsmToken> &Tokens) {
2883 assert(isToken(AsmToken::Identifier));
2884 StringRef RegName = getTokenStr();
2885 auto Loc = getLoc();
2886
2887 const RegInfo *RI = getRegularRegInfo(RegName);
2888 if (!RI) {
2889 Error(Loc, "invalid register name");
2890 return MCRegister();
2891 }
2892
2893 Tokens.push_back(getToken());
2894 lex(); // skip register name
2895
2896 RegKind = RI->Kind;
2897 StringRef RegSuffix = RegName.substr(RI->Name.size());
2898 unsigned SubReg = NoSubRegister;
2899 bool IsRange = false;
2900 if (!RegSuffix.empty()) {
2901 if (RegSuffix.consume_back(".l"))
2902 SubReg = AMDGPU::lo16;
2903 else if (RegSuffix.consume_back(".h"))
2904 SubReg = AMDGPU::hi16;
2905
2906 // Single 32-bit register: vXX.
2907 if (!getRegNum(RegSuffix, RegNum)) {
2908 Error(Loc, "invalid register index");
2909 return MCRegister();
2910 }
2911 RegWidth = 32;
2912 } else {
2913 // Range of registers: v[XX:YY]. ":YY" is optional.
2914 IsRange = true;
2915 if (!ParseRegRange(RegNum, RegWidth, SubReg))
2916 return MCRegister();
2917 }
2918
2919 // Do not allow vcc_lo/hi be referred as s106/107.
2920 MCRegister Reg = getRegularReg(RegKind, RegNum, SubReg, RegWidth, Loc);
2921 const MCRegisterInfo &TRI = *getContext().getRegisterInfo();
2922 if (RegKind == IS_SGPR && IsRange
2923 ? (TRI.isSubRegister(Reg, VCC_LO) || TRI.isSubRegister(Reg, VCC_HI))
2924 : (Reg == VCC_LO || Reg == VCC_HI)) {
2925 Error(Loc, "register index is out of range");
2926 return MCRegister();
2927 }
2928
2929 return Reg;
2930}
2931
2932MCRegister AMDGPUAsmParser::ParseRegList(RegisterKind &RegKind,
2933 unsigned &RegNum, unsigned &RegWidth,
2934 SmallVectorImpl<AsmToken> &Tokens) {
2935 MCRegister Reg;
2936 auto ListLoc = getLoc();
2937
2938 if (!skipToken(AsmToken::LBrac,
2939 "expected a register or a list of registers")) {
2940 return MCRegister();
2941 }
2942
2943 // List of consecutive registers, e.g.: [s0,s1,s2,s3]
2944
2945 auto Loc = getLoc();
2946 if (!ParseAMDGPURegister(RegKind, Reg, RegNum, RegWidth))
2947 return MCRegister();
2948 if (RegWidth != 32) {
2949 Error(Loc, "expected a single 32-bit register");
2950 return MCRegister();
2951 }
2952
2953 for (; trySkipToken(AsmToken::Comma);) {
2954 RegisterKind NextRegKind;
2955 MCRegister NextReg;
2956 unsigned NextRegNum, NextRegWidth;
2957 Loc = getLoc();
2958
2959 if (!ParseAMDGPURegister(NextRegKind, NextReg, NextRegNum, NextRegWidth,
2960 Tokens)) {
2961 return MCRegister();
2962 }
2963 if (NextRegWidth != 32) {
2964 Error(Loc, "expected a single 32-bit register");
2965 return MCRegister();
2966 }
2967 if (!AddNextRegisterToList(Reg, RegWidth, RegKind, NextReg, NextRegKind,
2968 Loc))
2969 return MCRegister();
2970 }
2971
2972 if (!skipToken(AsmToken::RBrac,
2973 "expected a comma or a closing square bracket")) {
2974 return MCRegister();
2975 }
2976
2977 if (isRegularReg(RegKind))
2978 Reg = getRegularReg(RegKind, RegNum, NoSubRegister, RegWidth, ListLoc);
2979
2980 return Reg;
2981}
2982
2983bool AMDGPUAsmParser::ParseAMDGPURegister(RegisterKind &RegKind,
2984 MCRegister &Reg, unsigned &RegNum,
2985 unsigned &RegWidth,
2986 SmallVectorImpl<AsmToken> &Tokens) {
2987 auto Loc = getLoc();
2988 Reg = MCRegister();
2989
2990 if (isToken(AsmToken::Identifier)) {
2991 Reg = ParseSpecialReg(RegKind, RegNum, RegWidth, Tokens);
2992 if (!Reg)
2993 Reg = ParseRegularReg(RegKind, RegNum, RegWidth, Tokens);
2994 } else {
2995 Reg = ParseRegList(RegKind, RegNum, RegWidth, Tokens);
2996 }
2997
2998 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
2999 if (!Reg) {
3000 assert(Parser.hasPendingError());
3001 return false;
3002 }
3003
3004 if (!subtargetHasRegister(*TRI, Reg)) {
3005 if (Reg == AMDGPU::SGPR_NULL) {
3006 Error(Loc, "'null' operand is not supported on this GPU");
3007 } else {
3009 " register not available on this GPU");
3010 }
3011 return false;
3012 }
3013
3014 return true;
3015}
3016
3017bool AMDGPUAsmParser::ParseAMDGPURegister(RegisterKind &RegKind,
3018 MCRegister &Reg, unsigned &RegNum,
3019 unsigned &RegWidth,
3020 bool RestoreOnFailure /*=false*/) {
3021 Reg = MCRegister();
3022
3024 if (ParseAMDGPURegister(RegKind, Reg, RegNum, RegWidth, Tokens)) {
3025 if (RestoreOnFailure) {
3026 while (!Tokens.empty()) {
3027 getLexer().UnLex(Tokens.pop_back_val());
3028 }
3029 }
3030 return true;
3031 }
3032 return false;
3033}
3034
3035std::optional<StringRef>
3036AMDGPUAsmParser::getGprCountSymbolName(RegisterKind RegKind) {
3037 switch (RegKind) {
3038 case IS_VGPR:
3039 return StringRef(".amdgcn.next_free_vgpr");
3040 case IS_SGPR:
3041 return StringRef(".amdgcn.next_free_sgpr");
3042 default:
3043 return std::nullopt;
3044 }
3045}
3046
3047void AMDGPUAsmParser::initializeGprCountSymbol(RegisterKind RegKind) {
3048 auto SymbolName = getGprCountSymbolName(RegKind);
3049 assert(SymbolName && "initializing invalid register kind");
3050 MCSymbol *Sym = getContext().getOrCreateSymbol(*SymbolName);
3052 Sym->setRedefinable(true);
3053}
3054
3055bool AMDGPUAsmParser::updateGprCountSymbols(RegisterKind RegKind,
3056 unsigned DwordRegIndex,
3057 unsigned RegWidth) {
3058 // Symbols are only defined for GCN targets
3059 if (ISA.Major < 6)
3060 return true;
3061
3062 auto SymbolName = getGprCountSymbolName(RegKind);
3063 if (!SymbolName)
3064 return true;
3065 MCSymbol *Sym = getContext().getOrCreateSymbol(*SymbolName);
3066
3067 int64_t NewMax = DwordRegIndex + divideCeil(RegWidth, 32) - 1;
3068 int64_t OldCount;
3069
3070 if (!Sym->isVariable())
3071 return !Error(getLoc(),
3072 ".amdgcn.next_free_{v,s}gpr symbols must be variable");
3073 if (!Sym->getVariableValue()->evaluateAsAbsolute(OldCount))
3074 return !Error(
3075 getLoc(),
3076 ".amdgcn.next_free_{v,s}gpr symbols must be absolute expressions");
3077
3078 if (OldCount <= NewMax)
3080
3081 return true;
3082}
3083
3084std::unique_ptr<AMDGPUOperand>
3085AMDGPUAsmParser::parseRegister(bool RestoreOnFailure) {
3086 const auto &Tok = getToken();
3087 SMLoc StartLoc = Tok.getLoc();
3088 SMLoc EndLoc = Tok.getEndLoc();
3089 RegisterKind RegKind;
3090 MCRegister Reg;
3091 unsigned RegNum, RegWidth;
3092
3093 if (!ParseAMDGPURegister(RegKind, Reg, RegNum, RegWidth)) {
3094 return nullptr;
3095 }
3096 if (isHsaAbi(getSTI())) {
3097 if (!updateGprCountSymbols(RegKind, RegNum, RegWidth))
3098 return nullptr;
3099 } else
3100 KernelScope.usesRegister(RegKind, RegNum, RegWidth);
3101 return AMDGPUOperand::CreateReg(this, Reg, StartLoc, EndLoc);
3102}
3103
3104ParseStatus AMDGPUAsmParser::parseImm(OperandVector &Operands,
3105 bool HasSP3AbsModifier, LitModifier Lit) {
3106 // TODO: add syntactic sugar for 1/(2*PI)
3107
3108 if (isRegister() || isModifier())
3109 return ParseStatus::NoMatch;
3110
3111 if (Lit == LitModifier::None) {
3112 if (trySkipId("lit"))
3113 Lit = LitModifier::Lit;
3114 else if (trySkipId("lit64"))
3115 Lit = LitModifier::Lit64;
3116
3117 if (Lit != LitModifier::None) {
3118 if (!skipToken(AsmToken::LParen, "expected left paren after lit"))
3119 return ParseStatus::Failure;
3120 ParseStatus S = parseImm(Operands, HasSP3AbsModifier, Lit);
3121 if (S.isSuccess() &&
3122 !skipToken(AsmToken::RParen, "expected closing parentheses"))
3123 return ParseStatus::Failure;
3124 return S;
3125 }
3126 }
3127
3128 const auto &Tok = getToken();
3129 const auto &NextTok = peekToken();
3130 bool IsReal = Tok.is(AsmToken::Real);
3131 SMLoc S = getLoc();
3132 bool Negate = false;
3133
3134 if (!IsReal && Tok.is(AsmToken::Minus) && NextTok.is(AsmToken::Real)) {
3135 lex();
3136 IsReal = true;
3137 Negate = true;
3138 }
3139
3140 AMDGPUOperand::Modifiers Mods;
3141 Mods.Lit = Lit;
3142
3143 if (IsReal) {
3144 // Floating-point expressions are not supported.
3145 // Can only allow floating-point literals with an
3146 // optional sign.
3147
3148 StringRef Num = getTokenStr();
3149 lex();
3150
3151 APFloat RealVal(APFloat::IEEEdouble());
3152 auto roundMode = APFloat::rmNearestTiesToEven;
3153 if (errorToBool(RealVal.convertFromString(Num, roundMode).takeError()))
3154 return ParseStatus::Failure;
3155 if (Negate)
3156 RealVal.changeSign();
3157
3158 Operands.push_back(
3159 AMDGPUOperand::CreateImm(this, RealVal.bitcastToAPInt().getZExtValue(),
3160 S, AMDGPUOperand::ImmTyNone, true));
3161 AMDGPUOperand &Op = static_cast<AMDGPUOperand &>(*Operands.back());
3162 Op.setModifiers(Mods);
3163
3164 return ParseStatus::Success;
3165
3166 } else {
3167 int64_t IntVal;
3168 const MCExpr *Expr;
3169 SMLoc S = getLoc();
3170
3171 if (HasSP3AbsModifier) {
3172 // This is a workaround for handling expressions
3173 // as arguments of SP3 'abs' modifier, for example:
3174 // |1.0|
3175 // |-1|
3176 // |1+x|
3177 // This syntax is not compatible with syntax of standard
3178 // MC expressions (due to the trailing '|').
3179 SMLoc EndLoc;
3180 if (getParser().parsePrimaryExpr(Expr, EndLoc, nullptr))
3181 return ParseStatus::Failure;
3182 } else {
3183 if (Parser.parseExpression(Expr))
3184 return ParseStatus::Failure;
3185 }
3186
3187 if (Expr->evaluateAsAbsolute(IntVal)) {
3188 if (Lit == LitModifier::Lit && !isInt<32>(IntVal) && !isUInt<32>(IntVal))
3189 return Error(S, "literal value out of range");
3190 Operands.push_back(AMDGPUOperand::CreateImm(this, IntVal, S));
3191 AMDGPUOperand &Op = static_cast<AMDGPUOperand &>(*Operands.back());
3192 Op.setModifiers(Mods);
3193 } else {
3194 if (Lit != LitModifier::None)
3195 return ParseStatus::NoMatch;
3196 Operands.push_back(AMDGPUOperand::CreateExpr(this, Expr, S));
3197 }
3198
3199 return ParseStatus::Success;
3200 }
3201
3202 return ParseStatus::NoMatch;
3203}
3204
3205ParseStatus AMDGPUAsmParser::parseReg(OperandVector &Operands) {
3206 if (!isRegister())
3207 return ParseStatus::NoMatch;
3208
3209 if (auto R = parseRegister()) {
3210 assert(R->isReg());
3211 Operands.push_back(std::move(R));
3212 return ParseStatus::Success;
3213 }
3214 return ParseStatus::Failure;
3215}
3216
3217ParseStatus AMDGPUAsmParser::parseRegOrImm(OperandVector &Operands,
3218 bool HasSP3AbsMod, LitModifier Lit) {
3219 ParseStatus Res = parseReg(Operands);
3220 if (!Res.isNoMatch())
3221 return Res;
3222 if (isModifier())
3223 return ParseStatus::NoMatch;
3224 return parseImm(Operands, HasSP3AbsMod, Lit);
3225}
3226
3227bool AMDGPUAsmParser::isNamedOperandModifier(const AsmToken &Token,
3228 const AsmToken &NextToken) const {
3229 if (Token.is(AsmToken::Identifier) && NextToken.is(AsmToken::LParen)) {
3230 const auto &str = Token.getString();
3231 return str == "abs" || str == "neg" || str == "sext";
3232 }
3233 return false;
3234}
3235
3236bool AMDGPUAsmParser::isOpcodeModifierWithVal(const AsmToken &Token,
3237 const AsmToken &NextToken) const {
3238 return Token.is(AsmToken::Identifier) && NextToken.is(AsmToken::Colon);
3239}
3240
3241bool AMDGPUAsmParser::isOperandModifier(const AsmToken &Token,
3242 const AsmToken &NextToken) const {
3243 return isNamedOperandModifier(Token, NextToken) || Token.is(AsmToken::Pipe);
3244}
3245
3246bool AMDGPUAsmParser::isRegOrOperandModifier(const AsmToken &Token,
3247 const AsmToken &NextToken) const {
3248 return isRegister(Token, NextToken) || isOperandModifier(Token, NextToken);
3249}
3250
3251// Check if this is an operand modifier or an opcode modifier
3252// which may look like an expression but it is not. We should
3253// avoid parsing these modifiers as expressions. Currently
3254// recognized sequences are:
3255// |...|
3256// abs(...)
3257// neg(...)
3258// sext(...)
3259// -reg
3260// -|...|
3261// -abs(...)
3262// name:...
3263// "name ::" is the VOPD separator, not an opcode modifier.
3264//
3265bool AMDGPUAsmParser::isModifier() {
3266
3267 AsmToken Tok = getToken();
3268 AsmToken NextToken[2];
3269 peekTokens(NextToken);
3270
3271 // "name:value" is an opcode modifier. The second colon of "::" is the
3272 // VOPD separator, so a symbol written immediately before "::" is a literal.
3273 bool IsOpcodeModifier = isOpcodeModifierWithVal(Tok, NextToken[0]) &&
3274 !NextToken[1].is(AsmToken::Colon);
3275
3276 return isOperandModifier(Tok, NextToken[0]) ||
3277 (Tok.is(AsmToken::Minus) &&
3278 isRegOrOperandModifier(NextToken[0], NextToken[1])) ||
3279 IsOpcodeModifier;
3280}
3281
3282// Check if the current token is an SP3 'neg' modifier.
3283// Currently this modifier is allowed in the following context:
3284//
3285// 1. Before a register, e.g. "-v0", "-v[...]" or "-[v0,v1]".
3286// 2. Before an 'abs' modifier: -abs(...)
3287// 3. Before an SP3 'abs' modifier: -|...|
3288//
3289// In all other cases "-" is handled as a part
3290// of an expression that follows the sign.
3291//
3292// Note: When "-" is followed by an integer literal,
3293// this is interpreted as integer negation rather
3294// than a floating-point NEG modifier applied to N.
3295// Beside being contr-intuitive, such use of floating-point
3296// NEG modifier would have resulted in different meaning
3297// of integer literals used with VOP1/2/C and VOP3,
3298// for example:
3299// v_exp_f32_e32 v5, -1 // VOP1: src0 = 0xFFFFFFFF
3300// v_exp_f32_e64 v5, -1 // VOP3: src0 = 0x80000001
3301// Negative fp literals with preceding "-" are
3302// handled likewise for uniformity
3303//
3304bool AMDGPUAsmParser::parseSP3NegModifier() {
3305
3306 AsmToken NextToken[2];
3307 peekTokens(NextToken);
3308
3309 if (isToken(AsmToken::Minus) &&
3310 (isRegister(NextToken[0], NextToken[1]) ||
3311 NextToken[0].is(AsmToken::Pipe) || isId(NextToken[0], "abs"))) {
3312 lex();
3313 return true;
3314 }
3315
3316 return false;
3317}
3318
3319ParseStatus
3320AMDGPUAsmParser::parseRegOrImmWithFPInputMods(OperandVector &Operands,
3321 bool AllowImm) {
3322 bool Neg, SP3Neg;
3323 bool Abs, SP3Abs;
3324 SMLoc Loc;
3325
3326 // Disable ambiguous constructs like '--1' etc. Should use neg(-1) instead.
3327 if (isToken(AsmToken::Minus) && peekToken().is(AsmToken::Minus))
3328 return Error(getLoc(), "invalid syntax, expected 'neg' modifier");
3329
3330 SP3Neg = parseSP3NegModifier();
3331
3332 Loc = getLoc();
3333 Neg = trySkipId("neg");
3334 if (Neg && SP3Neg)
3335 return Error(Loc, "expected register or immediate");
3336 if (Neg && !skipToken(AsmToken::LParen, "expected left paren after neg"))
3337 return ParseStatus::Failure;
3338
3339 Abs = trySkipId("abs");
3340 if (Abs && !skipToken(AsmToken::LParen, "expected left paren after abs"))
3341 return ParseStatus::Failure;
3342
3343 LitModifier Lit = LitModifier::None;
3344 if (trySkipId("lit")) {
3345 Lit = LitModifier::Lit;
3346 if (!skipToken(AsmToken::LParen, "expected left paren after lit"))
3347 return ParseStatus::Failure;
3348 } else if (trySkipId("lit64")) {
3349 Lit = LitModifier::Lit64;
3350 if (!skipToken(AsmToken::LParen, "expected left paren after lit64"))
3351 return ParseStatus::Failure;
3352 if (!has64BitLiterals())
3353 return Error(Loc, "lit64 is not supported on this GPU");
3354 }
3355
3356 Loc = getLoc();
3357 SP3Abs = trySkipToken(AsmToken::Pipe);
3358 if (Abs && SP3Abs)
3359 return Error(Loc, "expected register or immediate");
3360
3361 ParseStatus Res;
3362 if (AllowImm) {
3363 Res = parseRegOrImm(Operands, SP3Abs, Lit);
3364 } else {
3365 Res = parseReg(Operands);
3366 }
3367 if (!Res.isSuccess())
3368 return (SP3Neg || Neg || SP3Abs || Abs || Lit != LitModifier::None)
3370 : Res;
3371
3372 if (Lit != LitModifier::None && !Operands.back()->isImm())
3373 Error(Loc, "expected immediate with lit modifier");
3374
3375 if (SP3Abs && !skipToken(AsmToken::Pipe, "expected vertical bar"))
3376 return ParseStatus::Failure;
3377 if (Abs && !skipToken(AsmToken::RParen, "expected closing parentheses"))
3378 return ParseStatus::Failure;
3379 if (Neg && !skipToken(AsmToken::RParen, "expected closing parentheses"))
3380 return ParseStatus::Failure;
3381 if (Lit != LitModifier::None &&
3382 !skipToken(AsmToken::RParen, "expected closing parentheses"))
3383 return ParseStatus::Failure;
3384
3385 AMDGPUOperand::Modifiers Mods;
3386 Mods.Abs = Abs || SP3Abs;
3387 Mods.Neg = Neg || SP3Neg;
3388 Mods.Lit = Lit;
3389
3390 if (Mods.hasFPModifiers() || Lit != LitModifier::None) {
3391 AMDGPUOperand &Op = static_cast<AMDGPUOperand &>(*Operands.back());
3392 if (Op.isExpr())
3393 return Error(Op.getStartLoc(), "expected an absolute expression");
3394 Op.setModifiers(Mods);
3395 }
3396 return ParseStatus::Success;
3397}
3398
3399ParseStatus
3400AMDGPUAsmParser::parseRegOrImmWithIntInputMods(OperandVector &Operands,
3401 bool AllowImm) {
3402 bool Sext = trySkipId("sext");
3403 if (Sext && !skipToken(AsmToken::LParen, "expected left paren after sext"))
3404 return ParseStatus::Failure;
3405
3406 ParseStatus Res;
3407 if (AllowImm) {
3408 Res = parseRegOrImm(Operands);
3409 } else {
3410 Res = parseReg(Operands);
3411 }
3412 if (!Res.isSuccess())
3413 return Sext ? ParseStatus::Failure : Res;
3414
3415 if (Sext && !skipToken(AsmToken::RParen, "expected closing parentheses"))
3416 return ParseStatus::Failure;
3417
3418 AMDGPUOperand::Modifiers Mods;
3419 Mods.Sext = Sext;
3420
3421 if (Mods.hasIntModifiers()) {
3422 AMDGPUOperand &Op = static_cast<AMDGPUOperand &>(*Operands.back());
3423 if (Op.isExpr())
3424 return Error(Op.getStartLoc(), "expected an absolute expression");
3425 Op.setModifiers(Mods);
3426 }
3427
3428 return ParseStatus::Success;
3429}
3430
3431ParseStatus AMDGPUAsmParser::parseRegWithFPInputMods(OperandVector &Operands) {
3432 return parseRegOrImmWithFPInputMods(Operands, false);
3433}
3434
3435ParseStatus AMDGPUAsmParser::parseRegWithIntInputMods(OperandVector &Operands) {
3436 return parseRegOrImmWithIntInputMods(Operands, false);
3437}
3438
3439ParseStatus AMDGPUAsmParser::parseRsrcReg(OperandVector &Operands) {
3440 // Without the marker, fall back to plain register parsing so the legacy
3441 // bare-register form (e.g. `s8`, `v8`) still assembles for indexed
3442 // buffer/image instructions.
3443 if (!trySkipId("rsrcidx"))
3444 return parseReg(Operands);
3445
3446 if (!skipToken(AsmToken::LParen, "expected left paren after rsrcidx"))
3447 return ParseStatus::Failure;
3448
3449 SMLoc RegLoc = getLoc();
3450 std::unique_ptr<AMDGPUOperand> Reg = parseRegister();
3451 if (!Reg)
3452 return ParseStatus::Failure;
3453
3454 // Enforce that the inner register is a valid index register. The matcher
3455 // predicate alone is not sufficient: if it fails, the matcher will fall back
3456 // to a non-indexed instruction variant whose resource operand happens to
3457 // accept the same register, silently dropping the `rsrcidx` intent.
3458 if (!Reg->isRsrcReg32())
3459 return Error(RegLoc, "rsrcidx operand must be a 32-bit SGPR or VGPR");
3460
3461 if (!skipToken(AsmToken::RParen, "expected closing parenthesis"))
3462 return ParseStatus::Failure;
3463
3464 Operands.push_back(std::move(Reg));
3465 return ParseStatus::Success;
3466}
3467
3468ParseStatus AMDGPUAsmParser::parseVReg32OrOff(OperandVector &Operands) {
3469 auto Loc = getLoc();
3470 if (trySkipId("off")) {
3471 Operands.push_back(
3472 AMDGPUOperand::CreateImm(this, 0, Loc, AMDGPUOperand::ImmTyOff, false));
3473 return ParseStatus::Success;
3474 }
3475
3476 if (!isRegister())
3477 return ParseStatus::NoMatch;
3478
3479 std::unique_ptr<AMDGPUOperand> Reg = parseRegister();
3480 if (Reg) {
3481 Operands.push_back(std::move(Reg));
3482 return ParseStatus::Success;
3483 }
3484
3485 return ParseStatus::Failure;
3486}
3487
3488unsigned AMDGPUAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
3489 if ((getForcedEncodingSize() == 32 && SIInstrFlags::isVOP3(MII, Inst)) ||
3490 (getForcedEncodingSize() == 64 && !SIInstrFlags::isVOP3(MII, Inst)) ||
3491 (isForcedDPP() && !SIInstrFlags::isDPP(MII, Inst)) ||
3492 (isForcedSDWA() && !SIInstrFlags::isSDWA(MII, Inst)))
3493 return Match_InvalidOperand;
3494
3495 if (Inst.getOpcode() == AMDGPU::V_MAC_F32_sdwa_vi ||
3496 Inst.getOpcode() == AMDGPU::V_MAC_F16_sdwa_vi) {
3497 // v_mac_f32/16 allow only dst_sel == DWORD;
3498 auto OpNum =
3499 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::dst_sel);
3500 const auto &Op = Inst.getOperand(OpNum);
3501 if (!Op.isImm() || Op.getImm() != AMDGPU::SDWA::SdwaSel::DWORD) {
3502 return Match_InvalidOperand;
3503 }
3504 }
3505
3506 // Asm can first try to match VOPD or VOPD3. By failing early here with
3507 // Match_InvalidOperand, the parser will retry parsing as VOPD3 or VOPD.
3508 // Checking later during validateInstruction does not give a chance to retry
3509 // parsing as a different encoding.
3510 if (tryAnotherVOPDEncoding(Inst))
3511 return Match_InvalidOperand;
3512
3513 return Match_Success;
3514}
3515
3524
3525// What asm variants we should check
3526ArrayRef<unsigned> AMDGPUAsmParser::getMatchedVariants() const {
3527 if (isForcedDPP() && isForcedVOP3()) {
3528 static const unsigned Variants[] = {AMDGPUAsmVariants::VOP3_DPP};
3529 return ArrayRef(Variants);
3530 }
3531 if (getForcedEncodingSize() == 32) {
3532 static const unsigned Variants[] = {AMDGPUAsmVariants::DEFAULT};
3533 return ArrayRef(Variants);
3534 }
3535
3536 if (isForcedVOP3()) {
3537 static const unsigned Variants[] = {AMDGPUAsmVariants::VOP3};
3538 return ArrayRef(Variants);
3539 }
3540
3541 if (isForcedSDWA()) {
3542 static const unsigned Variants[] = {AMDGPUAsmVariants::SDWA,
3544 return ArrayRef(Variants);
3545 }
3546
3547 if (isForcedDPP()) {
3548 static const unsigned Variants[] = {AMDGPUAsmVariants::DPP};
3549 return ArrayRef(Variants);
3550 }
3551
3552 return getAllVariants();
3553}
3554
3555StringRef AMDGPUAsmParser::getMatchedVariantName() const {
3556 if (isForcedDPP() && isForcedVOP3())
3557 return "e64_dpp";
3558
3559 if (getForcedEncodingSize() == 32)
3560 return "e32";
3561
3562 if (isForcedVOP3())
3563 return "e64";
3564
3565 if (isForcedSDWA())
3566 return "sdwa";
3567
3568 if (isForcedDPP())
3569 return "dpp";
3570
3571 return "";
3572}
3573
3574MCRegister
3575AMDGPUAsmParser::findImplicitSGPRReadInVOP(const MCInst &Inst) const {
3576 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
3577 for (MCPhysReg Reg : Desc.implicit_uses()) {
3578 switch (Reg) {
3579 case AMDGPU::FLAT_SCR:
3580 case AMDGPU::VCC:
3581 case AMDGPU::VCC_LO:
3582 case AMDGPU::VCC_HI:
3583 case AMDGPU::M0:
3584 return Reg;
3585 default:
3586 break;
3587 }
3588 }
3589 return MCRegister();
3590}
3591
3592// NB: This code is correct only when used to check constant
3593// bus limitations because GFX7 support no f16 inline constants.
3594// Note that there are no cases when a GFX7 opcode violates
3595// constant bus limitations due to the use of an f16 constant.
3596bool AMDGPUAsmParser::isInlineConstant(const MCInst &Inst,
3597 unsigned OpIdx) const {
3598 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
3599
3600 if (!AMDGPU::isSISrcOperand(Desc, OpIdx) ||
3601 AMDGPU::isKImmOperand(Desc, OpIdx)) {
3602 return false;
3603 }
3604
3605 const MCOperand &MO = Inst.getOperand(OpIdx);
3606
3607 int64_t Val = MO.isImm() ? MO.getImm() : getLitValue(MO.getExpr());
3608 auto OpSize = AMDGPU::getOperandSize(Desc, OpIdx);
3609
3610 switch (OpSize) { // expected operand size
3611 case 8:
3612 return AMDGPU::isInlinableLiteral64(Val, hasInv2PiInlineImm());
3613 case 4:
3614 return AMDGPU::isInlinableLiteral32(Val, hasInv2PiInlineImm());
3615 case 2: {
3616 const unsigned OperandType = Desc.operands()[OpIdx].OperandType;
3619 return AMDGPU::isInlinableLiteralI16(Val, hasInv2PiInlineImm());
3620
3624
3628
3631
3635
3638 return AMDGPU::isInlinableLiteralFP16(Val, hasInv2PiInlineImm());
3639
3642 return AMDGPU::isInlinableLiteralBF16(Val, hasInv2PiInlineImm());
3643
3646 return false;
3647
3648 llvm_unreachable("invalid operand type");
3649 }
3650 default:
3651 llvm_unreachable("invalid operand size");
3652 }
3653}
3654
3655unsigned AMDGPUAsmParser::getConstantBusLimit(unsigned Opcode) const {
3656 if (!isGFX10Plus())
3657 return 1;
3658
3659 switch (Opcode) {
3660 // 64-bit shift instructions can use only one scalar value input
3661 case AMDGPU::V_LSHLREV_B64_e64:
3662 case AMDGPU::V_LSHLREV_B64_gfx10:
3663 case AMDGPU::V_LSHLREV_B64_e64_gfx11:
3664 case AMDGPU::V_LSHLREV_B64_e32_gfx12:
3665 case AMDGPU::V_LSHLREV_B64_e64_gfx12:
3666 case AMDGPU::V_LSHRREV_B64_e64:
3667 case AMDGPU::V_LSHRREV_B64_gfx10:
3668 case AMDGPU::V_LSHRREV_B64_e64_gfx11:
3669 case AMDGPU::V_LSHRREV_B64_e64_gfx12:
3670 case AMDGPU::V_ASHRREV_I64_e64:
3671 case AMDGPU::V_ASHRREV_I64_gfx10:
3672 case AMDGPU::V_ASHRREV_I64_e64_gfx11:
3673 case AMDGPU::V_ASHRREV_I64_e64_gfx12:
3674 case AMDGPU::V_LSHL_B64_e64:
3675 case AMDGPU::V_LSHR_B64_e64:
3676 case AMDGPU::V_ASHR_I64_e64:
3677 return 1;
3678 default:
3679 return 2;
3680 }
3681}
3682
3683constexpr unsigned MAX_SRC_OPERANDS_NUM = 6;
3685
3686// Get regular operand indices in the same order as specified
3687// in the instruction (but append mandatory literals to the end).
3689 bool AddMandatoryLiterals = false) {
3690
3691 int16_t ImmIdx =
3692 AddMandatoryLiterals ? getNamedOperandIdx(Opcode, OpName::imm) : -1;
3693
3694 if (isVOPD(Opcode)) {
3695 int16_t ImmXIdx =
3696 AddMandatoryLiterals ? getNamedOperandIdx(Opcode, OpName::immX) : -1;
3697
3698 return {getNamedOperandIdx(Opcode, OpName::src0X),
3699 getNamedOperandIdx(Opcode, OpName::vsrc1X),
3700 getNamedOperandIdx(Opcode, OpName::vsrc2X),
3701 getNamedOperandIdx(Opcode, OpName::src0Y),
3702 getNamedOperandIdx(Opcode, OpName::vsrc1Y),
3703 getNamedOperandIdx(Opcode, OpName::vsrc2Y),
3704 ImmXIdx,
3705 ImmIdx};
3706 }
3707
3708 return {getNamedOperandIdx(Opcode, OpName::src0),
3709 getNamedOperandIdx(Opcode, OpName::src1),
3710 getNamedOperandIdx(Opcode, OpName::src2), ImmIdx};
3711}
3712
3713bool AMDGPUAsmParser::usesConstantBus(const MCInst &Inst, unsigned OpIdx) {
3714 const MCOperand &MO = Inst.getOperand(OpIdx);
3715 if (MO.isImm())
3716 return !isInlineConstant(Inst, OpIdx);
3717 if (MO.isReg()) {
3718 auto Reg = MO.getReg();
3719 if (!Reg)
3720 return false;
3721 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
3722 auto PReg = mc2PseudoReg(Reg);
3723 return isSGPR(PReg, TRI) && PReg != SGPR_NULL;
3724 }
3725 return true;
3726}
3727
3728// Based on the comment for `AMDGPUInstructionSelector::selectWritelane`:
3729// Writelane is special in that it can use SGPR and M0 (which would normally
3730// count as using the constant bus twice - but in this case it is allowed since
3731// the lane selector doesn't count as a use of the constant bus). However, it is
3732// still required to abide by the 1 SGPR rule.
3733static bool checkWriteLane(const MCInst &Inst) {
3734 const unsigned Opcode = Inst.getOpcode();
3735 if (Opcode != V_WRITELANE_B32_gfx6_gfx7 && Opcode != V_WRITELANE_B32_vi)
3736 return false;
3737 const MCOperand &LaneSelOp = Inst.getOperand(2);
3738 if (!LaneSelOp.isReg())
3739 return false;
3740 auto LaneSelReg = mc2PseudoReg(LaneSelOp.getReg());
3741 return LaneSelReg == M0 || LaneSelReg == M0_gfxpre11;
3742}
3743
3744bool AMDGPUAsmParser::validateConstantBusLimitations(
3745 const MCInst &Inst, const OperandVector &Operands) {
3746 const unsigned Opcode = Inst.getOpcode();
3747 const MCInstrDesc &Desc = MII.get(Opcode);
3748 MCRegister LastSGPR;
3749 unsigned ConstantBusUseCount = 0;
3750 unsigned NumLiterals = 0;
3751 unsigned LiteralSize;
3752
3755 !SIInstrFlags::isSDWA(Desc) && !isVOPD(Opcode))
3756 return true;
3757
3758 if (checkWriteLane(Inst))
3759 return true;
3760
3761 // Check special imm operands (used by madmk, etc)
3762 if (AMDGPU::hasNamedOperand(Opcode, AMDGPU::OpName::imm)) {
3763 ++NumLiterals;
3764 LiteralSize = 4;
3765 }
3766
3767 SmallDenseSet<MCRegister> SGPRsUsed;
3768 MCRegister SGPRUsed = findImplicitSGPRReadInVOP(Inst);
3769 if (SGPRUsed) {
3770 SGPRsUsed.insert(SGPRUsed);
3771 ++ConstantBusUseCount;
3772 }
3773
3774 OperandIndices OpIndices = getSrcOperandIndices(Opcode);
3775
3776 unsigned ConstantBusLimit = getConstantBusLimit(Opcode);
3777
3778 for (int OpIdx : OpIndices) {
3779 if (OpIdx == -1)
3780 continue;
3781
3782 const MCOperand &MO = Inst.getOperand(OpIdx);
3783 if (usesConstantBus(Inst, OpIdx)) {
3784 if (MO.isReg()) {
3785 LastSGPR = mc2PseudoReg(MO.getReg());
3786 // Pairs of registers with a partial intersections like these
3787 // s0, s[0:1]
3788 // flat_scratch_lo, flat_scratch
3789 // flat_scratch_lo, flat_scratch_hi
3790 // are theoretically valid but they are disabled anyway.
3791 // Note that this code mimics SIInstrInfo::verifyInstruction
3792 if (SGPRsUsed.insert(LastSGPR).second) {
3793 ++ConstantBusUseCount;
3794 }
3795 } else { // Expression or a literal
3796
3797 if (Desc.operands()[OpIdx].OperandType == MCOI::OPERAND_IMMEDIATE)
3798 continue; // special operand like VINTERP attr_chan
3799
3800 // An instruction may use only one literal.
3801 // This has been validated on the previous step.
3802 // See validateVOPLiteral.
3803 // This literal may be used as more than one operand.
3804 // If all these operands are of the same size,
3805 // this literal counts as one scalar value.
3806 // Otherwise it counts as 2 scalar values.
3807 // See "GFX10 Shader Programming", section 3.6.2.3.
3808
3809 unsigned Size = AMDGPU::getOperandSize(Desc, OpIdx);
3810 if (Size < 4)
3811 Size = 4;
3812
3813 if (NumLiterals == 0) {
3814 NumLiterals = 1;
3815 LiteralSize = Size;
3816 } else if (LiteralSize != Size) {
3817 NumLiterals = 2;
3818 }
3819 }
3820 }
3821
3822 if (ConstantBusUseCount + NumLiterals > ConstantBusLimit) {
3823 Error(getOperandLoc(Operands, OpIdx),
3824 "invalid operand (violates constant bus restrictions)");
3825 return false;
3826 }
3827 }
3828 return true;
3829}
3830
3831std::optional<unsigned>
3832AMDGPUAsmParser::checkVOPDRegBankConstraints(const MCInst &Inst, bool AsVOPD3) {
3833
3834 const unsigned Opcode = Inst.getOpcode();
3835 if (!isVOPD(Opcode))
3836 return {};
3837
3838 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
3839
3840 auto getVRegIdx = [&](unsigned, unsigned OperandIdx) {
3841 const MCOperand &Opr = Inst.getOperand(OperandIdx);
3842 return (Opr.isReg() && !isSGPR(mc2PseudoReg(Opr.getReg()), TRI))
3843 ? Opr.getReg()
3844 : MCRegister();
3845 };
3846
3847 // On GFX1170+ if both OpX and OpY are V_MOV_B32 then OPY uses SRC2
3848 // source-cache.
3849 bool SkipSrc =
3850 Opcode == AMDGPU::V_DUAL_MOV_B32_e32_X_MOV_B32_e32_gfx1170 ||
3851 Opcode == AMDGPU::V_DUAL_MOV_B32_e32_X_MOV_B32_e32_gfx12 ||
3852 Opcode == AMDGPU::V_DUAL_MOV_B32_e32_X_MOV_B32_e32_gfx1250 ||
3853 Opcode == AMDGPU::V_DUAL_MOV_B32_e32_X_MOV_B32_e32_gfx13 ||
3854 Opcode == AMDGPU::V_DUAL_MOV_B32_e32_X_MOV_B32_e32_e96_gfx1250 ||
3855 Opcode == AMDGPU::V_DUAL_MOV_B32_e32_X_MOV_B32_e32_e96_gfx13;
3856 bool AllowSameVGPR = isGFX12Plus();
3857
3858 if (AsVOPD3) { // Literal constants are not allowed with VOPD3.
3859 for (auto OpName : {OpName::src0X, OpName::src0Y}) {
3860 int I = getNamedOperandIdx(Opcode, OpName);
3861 const MCOperand &Op = Inst.getOperand(I);
3862 if (!Op.isImm())
3863 continue;
3864 int64_t Imm = Op.getImm();
3865 if (!AMDGPU::isInlinableLiteral32(Imm, hasInv2PiInlineImm()) &&
3866 !AMDGPU::isInlinableLiteral64(Imm, hasInv2PiInlineImm()))
3867 return (unsigned)I;
3868 }
3869
3870 for (auto OpName : {OpName::vsrc1X, OpName::vsrc1Y, OpName::vsrc2X,
3871 OpName::vsrc2Y, OpName::imm}) {
3872 int I = getNamedOperandIdx(Opcode, OpName);
3873 if (I == -1)
3874 continue;
3875 const MCOperand &Op = Inst.getOperand(I);
3876 if (Op.isImm())
3877 return (unsigned)I;
3878 }
3879 }
3880
3881 const auto &InstInfo = getVOPDInstInfo(Opcode, &MII);
3882 auto InvalidCompOprIdx = InstInfo.getInvalidCompOperandIndex(
3883 getVRegIdx, *TRI, SkipSrc, AllowSameVGPR, AsVOPD3);
3884
3885 return InvalidCompOprIdx;
3886}
3887
3888bool AMDGPUAsmParser::validateVOPD(const MCInst &Inst,
3889 const OperandVector &Operands) {
3890
3891 unsigned Opcode = Inst.getOpcode();
3892 bool AsVOPD3 = SIInstrFlags::isVOPD3(MII, Inst);
3893
3894 if (AsVOPD3) {
3895 for (const std::unique_ptr<MCParsedAsmOperand> &Operand : Operands) {
3896 AMDGPUOperand &Op = (AMDGPUOperand &)*Operand;
3897 if ((Op.isRegKind() || Op.isImmTy(AMDGPUOperand::ImmTyNone)) &&
3898 (Op.getModifiers().getFPModifiersOperand() & SISrcMods::ABS))
3899 Error(Op.getStartLoc(), "ABS not allowed in VOPD3 instructions");
3900 }
3901 }
3902
3903 auto InvalidCompOprIdx = checkVOPDRegBankConstraints(Inst, AsVOPD3);
3904 if (!InvalidCompOprIdx.has_value())
3905 return true;
3906
3907 auto CompOprIdx = *InvalidCompOprIdx;
3908 const auto &InstInfo = getVOPDInstInfo(Opcode, &MII);
3909 auto ParsedIdx =
3910 std::max(InstInfo[VOPD::X].getIndexInParsedOperands(CompOprIdx),
3911 InstInfo[VOPD::Y].getIndexInParsedOperands(CompOprIdx));
3912 assert(ParsedIdx > 0 && ParsedIdx < Operands.size());
3913
3914 auto Loc = ((AMDGPUOperand &)*Operands[ParsedIdx]).getStartLoc();
3915 if (CompOprIdx == VOPD::Component::DST) {
3916 if (AsVOPD3)
3917 Error(Loc, "dst registers must be distinct");
3918 else
3919 Error(Loc, "one dst register must be even and the other odd");
3920 } else {
3921 auto CompSrcIdx = CompOprIdx - VOPD::Component::DST_NUM;
3922 Error(Loc, Twine("src") + Twine(CompSrcIdx) +
3923 " operands must use different VGPR banks");
3924 }
3925
3926 return false;
3927}
3928
3929// \returns true if \p Inst does not satisfy VOPD constraints, but can be
3930// potentially used as VOPD3 with the same operands.
3931bool AMDGPUAsmParser::tryVOPD3(const MCInst &Inst) {
3932 // First check if it fits VOPD
3933 auto InvalidCompOprIdx = checkVOPDRegBankConstraints(Inst, false);
3934 if (!InvalidCompOprIdx.has_value())
3935 return false;
3936
3937 // Then if it fits VOPD3
3938 InvalidCompOprIdx = checkVOPDRegBankConstraints(Inst, true);
3939 if (InvalidCompOprIdx.has_value()) {
3940 // If failed operand is dst it is better to show error about VOPD3
3941 // instruction as it has more capabilities and error message will be
3942 // more informative. If the dst is not legal for VOPD3, then it is not
3943 // legal for VOPD either.
3944 if (*InvalidCompOprIdx == VOPD::Component::DST)
3945 return true;
3946
3947 // Otherwise prefer VOPD as we may find ourselves in an awkward situation
3948 // with a conflict in tied implicit src2 of fmac and no asm operand to
3949 // to point to.
3950 return false;
3951 }
3952 return true;
3953}
3954
3955// \returns true is a VOPD3 instruction can be also represented as a shorter
3956// VOPD encoding.
3957bool AMDGPUAsmParser::tryVOPD(const MCInst &Inst) {
3958 const unsigned Opcode = Inst.getOpcode();
3959 const auto &II = getVOPDInstInfo(Opcode, &MII);
3960 unsigned EncodingFamily = AMDGPU::getVOPDEncodingFamily(getSTI());
3961 if (!getCanBeVOPD(II[VOPD::X].getOpcode(), EncodingFamily, false).X ||
3962 !getCanBeVOPD(II[VOPD::Y].getOpcode(), EncodingFamily, false).Y)
3963 return false;
3964
3965 // This is an awkward exception, VOPD3 variant of V_DUAL_CNDMASK_B32 has
3966 // explicit src2 even if it is vcc_lo. If it was parsed as VOPD3 it cannot
3967 // be parsed as VOPD which does not accept src2.
3968 if (II[VOPD::X].getOpcode() == AMDGPU::V_CNDMASK_B32_e32 ||
3969 II[VOPD::Y].getOpcode() == AMDGPU::V_CNDMASK_B32_e32)
3970 return false;
3971
3972 // If any modifiers are set this cannot be VOPD.
3973 for (auto OpName : {OpName::src0X_modifiers, OpName::src0Y_modifiers,
3974 OpName::vsrc1X_modifiers, OpName::vsrc1Y_modifiers,
3975 OpName::vsrc2X_modifiers, OpName::vsrc2Y_modifiers}) {
3976 int I = getNamedOperandIdx(Opcode, OpName);
3977 if (I == -1)
3978 continue;
3979 if (Inst.getOperand(I).getImm())
3980 return false;
3981 }
3982
3983 return !tryVOPD3(Inst);
3984}
3985
3986// VOPD3 has more relaxed register constraints than VOPD. We prefer shorter VOPD
3987// form but switch to VOPD3 otherwise.
3988bool AMDGPUAsmParser::tryAnotherVOPDEncoding(const MCInst &Inst) {
3989 if (!isGFX1250Plus() || !isVOPD(Inst.getOpcode()))
3990 return false;
3991
3992 if (SIInstrFlags::isVOPD3(MII, Inst))
3993 return tryVOPD(Inst);
3994 return tryVOPD3(Inst);
3995}
3996
3997bool AMDGPUAsmParser::validateIntClampSupported(const MCInst &Inst) {
3998
3999 const unsigned Opc = Inst.getOpcode();
4000
4001 if (SIInstrFlags::hasIntClamp(MII, Inst) && !hasIntClamp()) {
4002 int ClampIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp);
4003 assert(ClampIdx != -1);
4004 return Inst.getOperand(ClampIdx).getImm() == 0;
4005 }
4006
4007 return true;
4008}
4009
4010bool AMDGPUAsmParser::validateMIMGDataSize(const MCInst &Inst, SMLoc IDLoc) {
4011
4012 const unsigned Opc = Inst.getOpcode();
4013 const MCInstrDesc &Desc = MII.get(Opc);
4014
4015 if ((SIInstrFlags::isImage(Desc)) == 0)
4016 return true;
4017
4018 int VDataIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdata);
4019 int DMaskIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::dmask);
4020 int TFEIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::tfe);
4021
4022 if (VDataIdx == -1 && isGFX10Plus()) // no return image_sample
4023 return true;
4024
4025 if ((DMaskIdx == -1 || TFEIdx == -1) &&
4026 hasBVHRayTracingInsts()) // intersect_ray
4027 return true;
4028
4029 unsigned VDataSize = getRegOperandSize(Desc, VDataIdx);
4030 unsigned TFESize = (TFEIdx != -1 && Inst.getOperand(TFEIdx).getImm()) ? 1 : 0;
4031 unsigned DMask = Inst.getOperand(DMaskIdx).getImm() & 0xf;
4032 if (DMask == 0)
4033 DMask = 1;
4034
4035 bool IsPackedD16 = false;
4036 unsigned DataSize = SIInstrFlags::isGather4(Desc) ? 4 : llvm::popcount(DMask);
4037 if (hasPackedD16()) {
4038 int D16Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::d16);
4039 IsPackedD16 = D16Idx >= 0;
4040 if (IsPackedD16 && Inst.getOperand(D16Idx).getImm())
4041 DataSize = (DataSize + 1) / 2;
4042 }
4043
4044 if ((VDataSize / 4) == DataSize + TFESize)
4045 return true;
4046
4047 StringRef Modifiers;
4048 if (isGFX90A())
4049 Modifiers = IsPackedD16 ? "dmask and d16" : "dmask";
4050 else
4051 Modifiers = IsPackedD16 ? "dmask, d16 and tfe" : "dmask and tfe";
4052
4053 Error(IDLoc, Twine("image data size does not match ") + Modifiers);
4054 return false;
4055}
4056
4057bool AMDGPUAsmParser::validateMIMGAddrSize(const MCInst &Inst, SMLoc IDLoc) {
4058 const unsigned Opc = Inst.getOpcode();
4059 const MCInstrDesc &Desc = MII.get(Opc);
4060
4062 return true;
4063
4064 const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Opc);
4065
4066 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
4068 int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
4069 AMDGPU::OpName RSrcOpName =
4070 SIInstrFlags::isMIMG(Desc) ? AMDGPU::OpName::srsrc : AMDGPU::OpName::rsrc;
4071 int SrsrcIdx = AMDGPU::getNamedOperandIdx(Opc, RSrcOpName);
4072 int DimIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::dim);
4073 int A16Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::a16);
4074
4075 assert(VAddr0Idx != -1);
4076 assert(SrsrcIdx != -1);
4077 assert(SrsrcIdx > VAddr0Idx);
4078
4079 bool IsA16 = (A16Idx != -1 && Inst.getOperand(A16Idx).getImm());
4080 if (BaseOpcode->BVH) {
4081 if (IsA16 == BaseOpcode->A16)
4082 return true;
4083 Error(IDLoc, "image address size does not match a16");
4084 return false;
4085 }
4086
4087 unsigned Dim = Inst.getOperand(DimIdx).getImm();
4088 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfoByEncoding(Dim);
4089 bool IsNSA = SrsrcIdx - VAddr0Idx > 1;
4090 unsigned ActualAddrSize =
4091 IsNSA ? SrsrcIdx - VAddr0Idx : getRegOperandSize(Desc, VAddr0Idx) / 4;
4092
4093 unsigned ExpectedAddrSize =
4094 AMDGPU::getAddrSizeMIMGOp(BaseOpcode, DimInfo, IsA16, hasG16());
4095
4096 if (IsNSA) {
4097 if (hasPartialNSAEncoding() &&
4098 ExpectedAddrSize > getNSAMaxSize(SIInstrFlags::isVSAMPLE(Desc))) {
4099 int VAddrLastIdx = SrsrcIdx - 1;
4100 unsigned VAddrLastSize = getRegOperandSize(Desc, VAddrLastIdx) / 4;
4101
4102 ActualAddrSize = VAddrLastIdx - VAddr0Idx + VAddrLastSize;
4103 }
4104 } else {
4105 if (ExpectedAddrSize > 12)
4106 ExpectedAddrSize = 16;
4107
4108 // Allow oversized 8 VGPR vaddr when only 5/6/7 VGPRs are required.
4109 // This provides backward compatibility for assembly created
4110 // before 160b/192b/224b types were directly supported.
4111 if (ActualAddrSize == 8 && (ExpectedAddrSize >= 5 && ExpectedAddrSize <= 7))
4112 return true;
4113 }
4114
4115 if (ActualAddrSize == ExpectedAddrSize)
4116 return true;
4117
4118 Error(IDLoc, "image address size does not match dim and a16");
4119 return false;
4120}
4121
4122bool AMDGPUAsmParser::validateMIMGAtomicDMask(const MCInst &Inst) {
4123
4124 const unsigned Opc = Inst.getOpcode();
4125 const MCInstrDesc &Desc = MII.get(Opc);
4126
4127 if ((SIInstrFlags::isImage(Desc)) == 0)
4128 return true;
4129 if (!Desc.mayLoad() || !Desc.mayStore())
4130 return true; // Not atomic
4131
4132 int DMaskIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::dmask);
4133 unsigned DMask = Inst.getOperand(DMaskIdx).getImm() & 0xf;
4134
4135 // This is an incomplete check because image_atomic_cmpswap
4136 // may only use 0x3 and 0xf while other atomic operations
4137 // may use 0x1 and 0x3. However these limitations are
4138 // verified when we check that dmask matches dst size.
4139 return DMask == 0x1 || DMask == 0x3 || DMask == 0xf;
4140}
4141
4142bool AMDGPUAsmParser::validateMIMGGatherDMask(const MCInst &Inst) {
4143
4144 const unsigned Opc = Inst.getOpcode();
4145
4146 if (!SIInstrFlags::isGather4(MII, Inst))
4147 return true;
4148
4149 int DMaskIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::dmask);
4150 unsigned DMask = Inst.getOperand(DMaskIdx).getImm() & 0xf;
4151
4152 // GATHER4 instructions use dmask in a different fashion compared to
4153 // other MIMG instructions. The only useful DMASK values are
4154 // 1=red, 2=green, 4=blue, 8=alpha. (e.g. 1 returns
4155 // (red,red,red,red) etc.) The ISA document doesn't mention
4156 // this.
4157 return DMask == 0x1 || DMask == 0x2 || DMask == 0x4 || DMask == 0x8;
4158}
4159
4160bool AMDGPUAsmParser::validateMIMGDim(const MCInst &Inst,
4161 const OperandVector &Operands) {
4162 if (!isGFX10Plus())
4163 return true;
4164
4165 const unsigned Opc = Inst.getOpcode();
4166
4167 if ((SIInstrFlags::isImage(MII, Inst)) == 0)
4168 return true;
4169
4170 // image_bvh_intersect_ray instructions do not have dim
4172 return true;
4173
4174 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
4175 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
4176 if (Op.isDim())
4177 return true;
4178 }
4179 return false;
4180}
4181
4182bool AMDGPUAsmParser::validateMIMGMSAA(const MCInst &Inst) {
4183 const unsigned Opc = Inst.getOpcode();
4184
4185 if ((SIInstrFlags::isImage(MII, Inst)) == 0)
4186 return true;
4187
4188 const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Opc);
4189 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
4191
4192 if (!BaseOpcode->MSAA)
4193 return true;
4194
4195 int DimIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::dim);
4196 assert(DimIdx != -1);
4197
4198 unsigned Dim = Inst.getOperand(DimIdx).getImm();
4199 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfoByEncoding(Dim);
4200
4201 return DimInfo->MSAA;
4202}
4203
4204static bool IsMovrelsSDWAOpcode(const unsigned Opcode) {
4205 switch (Opcode) {
4206 case AMDGPU::V_MOVRELS_B32_sdwa_gfx10:
4207 case AMDGPU::V_MOVRELSD_B32_sdwa_gfx10:
4208 case AMDGPU::V_MOVRELSD_2_B32_sdwa_gfx10:
4209 return true;
4210 default:
4211 return false;
4212 }
4213}
4214
4215// movrels* opcodes should only allow VGPRS as src0.
4216// This is specified in .td description for vop1/vop3,
4217// but sdwa is handled differently. See isSDWAOperand.
4218bool AMDGPUAsmParser::validateMovrels(const MCInst &Inst,
4219 const OperandVector &Operands) {
4220
4221 const unsigned Opc = Inst.getOpcode();
4222
4223 if (!SIInstrFlags::isSDWA(MII, Inst) || !IsMovrelsSDWAOpcode(Opc))
4224 return true;
4225
4226 const int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
4227 assert(Src0Idx != -1);
4228
4229 const MCOperand &Src0 = Inst.getOperand(Src0Idx);
4230 if (Src0.isReg()) {
4231 auto Reg = mc2PseudoReg(Src0.getReg());
4232 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
4233 if (!isSGPR(Reg, TRI))
4234 return true;
4235 }
4236
4237 Error(getOperandLoc(Operands, Src0Idx), "source operand must be a VGPR");
4238 return false;
4239}
4240
4241bool AMDGPUAsmParser::validateMAIAccWrite(const MCInst &Inst,
4242 const OperandVector &Operands) {
4243
4244 const unsigned Opc = Inst.getOpcode();
4245
4246 if (Opc != AMDGPU::V_ACCVGPR_WRITE_B32_vi)
4247 return true;
4248
4249 const int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
4250 assert(Src0Idx != -1);
4251
4252 const MCOperand &Src0 = Inst.getOperand(Src0Idx);
4253 if (!Src0.isReg())
4254 return true;
4255
4256 auto Reg = mc2PseudoReg(Src0.getReg());
4257 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
4258 if (!isGFX90A() && isSGPR(Reg, TRI)) {
4259 Error(getOperandLoc(Operands, Src0Idx),
4260 "source operand must be either a VGPR or an inline constant");
4261 return false;
4262 }
4263
4264 return true;
4265}
4266
4267bool AMDGPUAsmParser::validateMAISrc2(const MCInst &Inst,
4268 const OperandVector &Operands) {
4269 unsigned Opcode = Inst.getOpcode();
4270
4271 if (!SIInstrFlags::isMAI(MII, Inst) ||
4272 !getFeatureBits()[FeatureMFMAInlineLiteralBug])
4273 return true;
4274
4275 const int Src2Idx = getNamedOperandIdx(Opcode, OpName::src2);
4276 if (Src2Idx == -1)
4277 return true;
4278
4279 if (Inst.getOperand(Src2Idx).isImm() && isInlineConstant(Inst, Src2Idx)) {
4280 Error(getOperandLoc(Operands, Src2Idx),
4281 "inline constants are not allowed for this operand");
4282 return false;
4283 }
4284
4285 return true;
4286}
4287
4288bool AMDGPUAsmParser::validateMFMA(const MCInst &Inst,
4289 const OperandVector &Operands) {
4290 const unsigned Opc = Inst.getOpcode();
4291 const MCInstrDesc &Desc = MII.get(Opc);
4292
4294 return true;
4295
4296 int BlgpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::blgp);
4297 if (BlgpIdx != -1) {
4298 if (const MFMA_F8F6F4_Info *Info = AMDGPU::isMFMA_F8F6F4(Opc)) {
4299 int CbszIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::cbsz);
4300
4301 unsigned CBSZ = Inst.getOperand(CbszIdx).getImm();
4302 unsigned BLGP = Inst.getOperand(BlgpIdx).getImm();
4303
4304 // Validate the correct register size was used for the floating point
4305 // format operands
4306
4307 bool Success = true;
4308 if (Info->NumRegsSrcA != mfmaScaleF8F6F4FormatToNumRegs(CBSZ)) {
4309 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
4310 Error(getOperandLoc(Operands, Src0Idx),
4311 "wrong register tuple size for cbsz value " + Twine(CBSZ));
4312 Success = false;
4313 }
4314
4315 if (Info->NumRegsSrcB != mfmaScaleF8F6F4FormatToNumRegs(BLGP)) {
4316 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
4317 Error(getOperandLoc(Operands, Src1Idx),
4318 "wrong register tuple size for blgp value " + Twine(BLGP));
4319 Success = false;
4320 }
4321
4322 return Success;
4323 }
4324 }
4325
4326 const int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
4327 if (Src2Idx == -1)
4328 return true;
4329
4330 const MCOperand &Src2 = Inst.getOperand(Src2Idx);
4331 if (!Src2.isReg())
4332 return true;
4333
4334 MCRegister Src2Reg = Src2.getReg();
4335 MCRegister DstReg = Inst.getOperand(0).getReg();
4336 if (Src2Reg == DstReg)
4337 return true;
4338
4339 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
4340 if (TRI->getRegClass(MII.getOpRegClassID(Desc.operands()[0], HwMode))
4341 .getSizeInBits() <= 128)
4342 return true;
4343
4344 if (TRI->regsOverlap(Src2Reg, DstReg)) {
4345 Error(getOperandLoc(Operands, Src2Idx),
4346 "source 2 operand must not partially overlap with dst");
4347 return false;
4348 }
4349
4350 return true;
4351}
4352
4353bool AMDGPUAsmParser::validateDivScale(const MCInst &Inst) {
4354 switch (Inst.getOpcode()) {
4355 default:
4356 return true;
4357 case V_DIV_SCALE_F32_gfx6_gfx7:
4358 case V_DIV_SCALE_F32_vi:
4359 case V_DIV_SCALE_F32_gfx10:
4360 case V_DIV_SCALE_F64_gfx6_gfx7:
4361 case V_DIV_SCALE_F64_vi:
4362 case V_DIV_SCALE_F64_gfx10:
4363 break;
4364 }
4365
4366 // TODO: Check that src0 = src1 or src2.
4367
4368 for (auto Name :
4369 {AMDGPU::OpName::src0_modifiers, AMDGPU::OpName::src2_modifiers,
4370 AMDGPU::OpName::src2_modifiers}) {
4371 if (Inst.getOperand(AMDGPU::getNamedOperandIdx(Inst.getOpcode(), Name))
4372 .getImm() &
4374 return false;
4375 }
4376 }
4377
4378 return true;
4379}
4380
4381bool AMDGPUAsmParser::validateMIMGD16(const MCInst &Inst) {
4382
4383 const unsigned Opc = Inst.getOpcode();
4384
4385 if ((SIInstrFlags::isImage(MII, Inst)) == 0)
4386 return true;
4387
4388 int D16Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::d16);
4389 if (D16Idx >= 0 && Inst.getOperand(D16Idx).getImm()) {
4390 if (isCI() || isSI())
4391 return false;
4392 }
4393
4394 return true;
4395}
4396
4397bool AMDGPUAsmParser::validateTensorR128(const MCInst &Inst) {
4398 const unsigned Opc = Inst.getOpcode();
4399
4400 if (!SIInstrFlags::usesTENSOR_CNT(MII, Inst))
4401 return true;
4402
4403 int R128Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::r128);
4404
4405 return R128Idx < 0 || !Inst.getOperand(R128Idx).getImm();
4406}
4407
4408static bool IsRevOpcode(const unsigned Opcode) {
4409 switch (Opcode) {
4410 case AMDGPU::V_SUBREV_F32_e32:
4411 case AMDGPU::V_SUBREV_F32_e64:
4412 case AMDGPU::V_SUBREV_F32_e32_gfx10:
4413 case AMDGPU::V_SUBREV_F32_e32_gfx6_gfx7:
4414 case AMDGPU::V_SUBREV_F32_e32_vi:
4415 case AMDGPU::V_SUBREV_F32_e64_gfx10:
4416 case AMDGPU::V_SUBREV_F32_e64_gfx6_gfx7:
4417 case AMDGPU::V_SUBREV_F32_e64_vi:
4418
4419 case AMDGPU::V_SUBREV_CO_U32_e32:
4420 case AMDGPU::V_SUBREV_CO_U32_e64:
4421 case AMDGPU::V_SUBREV_I32_e32_gfx6_gfx7:
4422 case AMDGPU::V_SUBREV_I32_e64_gfx6_gfx7:
4423
4424 case AMDGPU::V_SUBBREV_U32_e32:
4425 case AMDGPU::V_SUBBREV_U32_e64:
4426 case AMDGPU::V_SUBBREV_U32_e32_gfx6_gfx7:
4427 case AMDGPU::V_SUBBREV_U32_e32_vi:
4428 case AMDGPU::V_SUBBREV_U32_e64_gfx6_gfx7:
4429 case AMDGPU::V_SUBBREV_U32_e64_vi:
4430
4431 case AMDGPU::V_SUBREV_U32_e32:
4432 case AMDGPU::V_SUBREV_U32_e64:
4433 case AMDGPU::V_SUBREV_U32_e32_gfx9:
4434 case AMDGPU::V_SUBREV_U32_e32_vi:
4435 case AMDGPU::V_SUBREV_U32_e64_gfx9:
4436 case AMDGPU::V_SUBREV_U32_e64_vi:
4437
4438 case AMDGPU::V_SUBREV_F16_e32:
4439 case AMDGPU::V_SUBREV_F16_e64:
4440 case AMDGPU::V_SUBREV_F16_e32_gfx10:
4441 case AMDGPU::V_SUBREV_F16_e32_vi:
4442 case AMDGPU::V_SUBREV_F16_e64_gfx10:
4443 case AMDGPU::V_SUBREV_F16_e64_vi:
4444
4445 case AMDGPU::V_SUBREV_U16_e32:
4446 case AMDGPU::V_SUBREV_U16_e64:
4447 case AMDGPU::V_SUBREV_U16_e32_vi:
4448 case AMDGPU::V_SUBREV_U16_e64_vi:
4449
4450 case AMDGPU::V_SUBREV_CO_U32_e32_gfx9:
4451 case AMDGPU::V_SUBREV_CO_U32_e64_gfx10:
4452 case AMDGPU::V_SUBREV_CO_U32_e64_gfx9:
4453
4454 case AMDGPU::V_SUBBREV_CO_U32_e32_gfx9:
4455 case AMDGPU::V_SUBBREV_CO_U32_e64_gfx9:
4456
4457 case AMDGPU::V_SUBREV_NC_U32_e32_gfx10:
4458 case AMDGPU::V_SUBREV_NC_U32_e64_gfx10:
4459
4460 case AMDGPU::V_SUBREV_CO_CI_U32_e32_gfx10:
4461 case AMDGPU::V_SUBREV_CO_CI_U32_e64_gfx10:
4462
4463 case AMDGPU::V_LSHRREV_B32_e32:
4464 case AMDGPU::V_LSHRREV_B32_e64:
4465 case AMDGPU::V_LSHRREV_B32_e32_gfx6_gfx7:
4466 case AMDGPU::V_LSHRREV_B32_e64_gfx6_gfx7:
4467 case AMDGPU::V_LSHRREV_B32_e32_vi:
4468 case AMDGPU::V_LSHRREV_B32_e64_vi:
4469 case AMDGPU::V_LSHRREV_B32_e32_gfx10:
4470 case AMDGPU::V_LSHRREV_B32_e64_gfx10:
4471
4472 case AMDGPU::V_ASHRREV_I32_e32:
4473 case AMDGPU::V_ASHRREV_I32_e64:
4474 case AMDGPU::V_ASHRREV_I32_e32_gfx10:
4475 case AMDGPU::V_ASHRREV_I32_e32_gfx6_gfx7:
4476 case AMDGPU::V_ASHRREV_I32_e32_vi:
4477 case AMDGPU::V_ASHRREV_I32_e64_gfx10:
4478 case AMDGPU::V_ASHRREV_I32_e64_gfx6_gfx7:
4479 case AMDGPU::V_ASHRREV_I32_e64_vi:
4480
4481 case AMDGPU::V_LSHLREV_B32_e32:
4482 case AMDGPU::V_LSHLREV_B32_e64:
4483 case AMDGPU::V_LSHLREV_B32_e32_gfx10:
4484 case AMDGPU::V_LSHLREV_B32_e32_gfx6_gfx7:
4485 case AMDGPU::V_LSHLREV_B32_e32_vi:
4486 case AMDGPU::V_LSHLREV_B32_e64_gfx10:
4487 case AMDGPU::V_LSHLREV_B32_e64_gfx6_gfx7:
4488 case AMDGPU::V_LSHLREV_B32_e64_vi:
4489
4490 case AMDGPU::V_LSHLREV_B16_e32:
4491 case AMDGPU::V_LSHLREV_B16_e64:
4492 case AMDGPU::V_LSHLREV_B16_e32_vi:
4493 case AMDGPU::V_LSHLREV_B16_e64_vi:
4494 case AMDGPU::V_LSHLREV_B16_gfx10:
4495
4496 case AMDGPU::V_LSHRREV_B16_e32:
4497 case AMDGPU::V_LSHRREV_B16_e64:
4498 case AMDGPU::V_LSHRREV_B16_e32_vi:
4499 case AMDGPU::V_LSHRREV_B16_e64_vi:
4500 case AMDGPU::V_LSHRREV_B16_gfx10:
4501
4502 case AMDGPU::V_ASHRREV_I16_e32:
4503 case AMDGPU::V_ASHRREV_I16_e64:
4504 case AMDGPU::V_ASHRREV_I16_e32_vi:
4505 case AMDGPU::V_ASHRREV_I16_e64_vi:
4506 case AMDGPU::V_ASHRREV_I16_gfx10:
4507
4508 case AMDGPU::V_LSHLREV_B64_e64:
4509 case AMDGPU::V_LSHLREV_B64_gfx10:
4510 case AMDGPU::V_LSHLREV_B64_vi:
4511
4512 case AMDGPU::V_LSHRREV_B64_e64:
4513 case AMDGPU::V_LSHRREV_B64_gfx10:
4514 case AMDGPU::V_LSHRREV_B64_vi:
4515
4516 case AMDGPU::V_ASHRREV_I64_e64:
4517 case AMDGPU::V_ASHRREV_I64_gfx10:
4518 case AMDGPU::V_ASHRREV_I64_vi:
4519
4520 case AMDGPU::V_PK_LSHLREV_B16:
4521 case AMDGPU::V_PK_LSHLREV_B16_gfx10:
4522 case AMDGPU::V_PK_LSHLREV_B16_vi:
4523
4524 case AMDGPU::V_PK_LSHRREV_B16:
4525 case AMDGPU::V_PK_LSHRREV_B16_gfx10:
4526 case AMDGPU::V_PK_LSHRREV_B16_vi:
4527 case AMDGPU::V_PK_ASHRREV_I16:
4528 case AMDGPU::V_PK_ASHRREV_I16_gfx10:
4529 case AMDGPU::V_PK_ASHRREV_I16_vi:
4530 return true;
4531 default:
4532 return false;
4533 }
4534}
4535
4536bool AMDGPUAsmParser::validateLdsDirect(const MCInst &Inst,
4537 const OperandVector &Operands) {
4538 const unsigned Opcode = Inst.getOpcode();
4539
4540 // lds_direct register is defined so that it can be used
4541 // with 9-bit operands only. Ignore encodings which do not accept these.
4542 if (!SIInstrFlags::isVOP1(MII, Inst) && !SIInstrFlags::isVOP2(MII, Inst) &&
4543 !SIInstrFlags::isVOP3Like(MII, Inst) &&
4544 !SIInstrFlags::isVOPC(MII, Inst) && !SIInstrFlags::isSDWA(MII, Inst))
4545 return true;
4546
4547 for (auto SrcName : {OpName::src0, OpName::src1, OpName::src2}) {
4548 auto SrcIdx = getNamedOperandIdx(Opcode, SrcName);
4549 if (SrcIdx == -1)
4550 break;
4551 const auto &Src = Inst.getOperand(SrcIdx);
4552 if (Src.isReg() && Src.getReg() == LDS_DIRECT) {
4553
4554 if (isGFX90A() || isGFX11Plus()) {
4555 Error(getOperandLoc(Operands, SrcIdx),
4556 "lds_direct is not supported on this GPU");
4557 return false;
4558 }
4559
4560 if (IsRevOpcode(Opcode) || SIInstrFlags::isSDWA(MII, Inst)) {
4561 Error(getOperandLoc(Operands, SrcIdx),
4562 "lds_direct cannot be used with this instruction");
4563 return false;
4564 }
4565
4566 if (SrcName != OpName::src0) {
4567 Error(getOperandLoc(Operands, SrcIdx),
4568 "lds_direct may be used as src0 only");
4569 return false;
4570 }
4571 }
4572 }
4573
4574 return true;
4575}
4576
4577SMLoc AMDGPUAsmParser::getFlatOffsetLoc(const OperandVector &Operands) const {
4578 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
4579 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
4580 if (Op.isFlatOffset())
4581 return Op.getStartLoc();
4582 }
4583 return getLoc();
4584}
4585
4586bool AMDGPUAsmParser::validateOffset(const MCInst &Inst,
4587 const OperandVector &Operands) {
4588 auto Opcode = Inst.getOpcode();
4589 auto OpNum = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::offset);
4590 if (OpNum == -1)
4591 return true;
4592
4593 if (SIInstrFlags::isFLAT(MII, Inst))
4594 return validateFlatOffset(Inst, Operands);
4595
4596 if (SIInstrFlags::isSMRD(MII, Inst))
4597 return validateSMEMOffset(Inst, Operands);
4598
4599 const auto &Op = Inst.getOperand(OpNum);
4600 // GFX12+ buffer ops: InstOffset is signed 24, but must not be a negative.
4601 if (isGFX12Plus() && SIInstrFlags::isBuffer(MII, Inst)) {
4602 const unsigned OffsetSize = 24;
4603 if (!isUIntN(OffsetSize - 1, Op.getImm())) {
4604 Error(getFlatOffsetLoc(Operands),
4605 Twine("expected a ") + Twine(OffsetSize - 1) +
4606 "-bit unsigned offset for buffer ops");
4607 return false;
4608 }
4609 } else {
4610 const unsigned OffsetSize = 16;
4611 if (!isUIntN(OffsetSize, Op.getImm())) {
4612 Error(getFlatOffsetLoc(Operands),
4613 Twine("expected a ") + Twine(OffsetSize) + "-bit unsigned offset");
4614 return false;
4615 }
4616 }
4617 return true;
4618}
4619
4620bool AMDGPUAsmParser::validateFlatOffset(const MCInst &Inst,
4621 const OperandVector &Operands) {
4622 if (!SIInstrFlags::isFLAT(MII, Inst))
4623 return true;
4624
4625 auto Opcode = Inst.getOpcode();
4626 auto OpNum = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::offset);
4627 assert(OpNum != -1);
4628
4629 const auto &Op = Inst.getOperand(OpNum);
4630 if (!hasFlatOffsets() && Op.getImm() != 0) {
4631 Error(getFlatOffsetLoc(Operands),
4632 "flat offset modifier is not supported on this GPU");
4633 return false;
4634 }
4635
4636 // For pre-GFX12 FLAT instructions the offset must be positive;
4637 // MSB is ignored and forced to zero.
4638 unsigned OffsetSize = AMDGPU::getNumFlatOffsetBits(getSTI());
4639 bool AllowNegative =
4641 if (!isIntN(OffsetSize, Op.getImm()) || (!AllowNegative && Op.getImm() < 0)) {
4642 Error(getFlatOffsetLoc(Operands),
4643 Twine("expected a ") +
4644 (AllowNegative ? Twine(OffsetSize) + "-bit signed offset"
4645 : Twine(OffsetSize - 1) + "-bit unsigned offset"));
4646 return false;
4647 }
4648
4649 return true;
4650}
4651
4652SMLoc AMDGPUAsmParser::getSMEMOffsetLoc(const OperandVector &Operands) const {
4653 // Start with second operand because SMEM Offset cannot be dst or src0.
4654 for (unsigned i = 2, e = Operands.size(); i != e; ++i) {
4655 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
4656 if (Op.isSMEMOffset() || Op.isSMEMOffsetMod())
4657 return Op.getStartLoc();
4658 }
4659 return getLoc();
4660}
4661
4662bool AMDGPUAsmParser::validateSMEMOffset(const MCInst &Inst,
4663 const OperandVector &Operands) {
4664 if (isCI() || isSI())
4665 return true;
4666
4667 if (!SIInstrFlags::isSMRD(MII, Inst))
4668 return true;
4669
4670 auto Opcode = Inst.getOpcode();
4671 auto OpNum = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::offset);
4672 if (OpNum == -1)
4673 return true;
4674
4675 const auto &Op = Inst.getOperand(OpNum);
4676 if (!Op.isImm())
4677 return true;
4678
4679 uint64_t Offset = Op.getImm();
4680 bool IsBuffer = AMDGPU::getSMEMIsBuffer(Opcode);
4683 return true;
4684
4685 Error(getSMEMOffsetLoc(Operands),
4686 isGFX12Plus() && IsBuffer
4687 ? "expected a 23-bit unsigned offset for buffer ops"
4688 : isGFX12Plus() ? "expected a 24-bit signed offset"
4689 : (isVI() || IsBuffer) ? "expected a 20-bit unsigned offset"
4690 : "expected a 21-bit signed offset");
4691
4692 return false;
4693}
4694
4695// GFX12+ SMEM prefetches and probes encode an immediate sdata in 5 bits.
4696bool AMDGPUAsmParser::validateSMEMSData(const MCInst &Inst,
4697 const OperandVector &Operands) {
4698 if (!isGFX12Plus() || !SIInstrFlags::isSMRD(MII, Inst))
4699 return true;
4700
4701 int OpNum =
4702 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::sdata);
4703 if (OpNum == -1 || !Inst.getOperand(OpNum).isImm() ||
4704 isUInt<5>(Inst.getOperand(OpNum).getImm()))
4705 return true;
4706
4707 Error(getOperandLoc(Operands, OpNum), "expected a 5-bit unsigned immediate");
4708 return false;
4709}
4710
4711// On subtargets with FeatureBF16InlineConstFromUpperFP32 the hardware generates
4712// a bf16 inline constant in the high half of the corresponding fp32 inline
4713// constant. A VOP1 bf16 opcode (v_cvt_f32_bf16 and the bf16 transcendentals)
4714// reads the low half of its source, so it must use the VOP3 encoding with
4715// op_sel[0] set in order to see the constant at all.
4716bool AMDGPUAsmParser::validateBF16InlineConst(const MCInst &Inst,
4717 const OperandVector &Operands) {
4718 if (!getFeatureBits()[AMDGPU::FeatureBF16InlineConstFromUpperFP32])
4719 return true;
4720
4721 const unsigned Opc = Inst.getOpcode();
4722 const MCInstrDesc &Desc = MII.get(Opc);
4723 const bool IsVOP3 =
4725 if (!SIInstrFlags::isVOP1(Desc) && !IsVOP3)
4726 return true;
4727
4728 // Only the single-source VOP1 bf16 opcodes are affected. Multi-source and
4729 // packed bf16 instructions such as v_fma_mix*_bf16 are not.
4730 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::src1))
4731 return true;
4732
4733 const int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
4734 if (Src0Idx == -1)
4735 return true;
4736
4737 const MCOperandInfo &Src0Info = Desc.operands()[Src0Idx];
4738 if (!AMDGPU::isBF16SrcOperand(Src0Info))
4739 return true;
4740
4741 const MCOperand &Src0 = Inst.getOperand(Src0Idx);
4742 if (!Src0.isImm() ||
4743 !AMDGPU::isInlinableLiteralBF16(static_cast<int16_t>(Src0.getImm()),
4744 hasInv2PiInlineImm()))
4745 return true;
4746
4747 if (IsVOP3) {
4748 const int ModsIdx =
4749 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers);
4750 if (ModsIdx != -1 &&
4751 (Inst.getOperand(ModsIdx).getImm() & SISrcMods::OP_SEL_0))
4752 return true;
4753 }
4754
4755 Error(getOperandLoc(Operands, Src0Idx),
4756 "bf16 inline constant is read from the high half of the fp32 inline "
4757 "constant on this GPU; use the e64 encoding with op_sel:[1,0]");
4758 return false;
4759}
4760
4761bool AMDGPUAsmParser::validateSOPLiteral(const MCInst &Inst,
4762 const OperandVector &Operands) {
4763 unsigned Opcode = Inst.getOpcode();
4764 const MCInstrDesc &Desc = MII.get(Opcode);
4766 return true;
4767
4768 const int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
4769 const int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
4770
4771 const int OpIndices[] = {Src0Idx, Src1Idx};
4772
4773 unsigned NumExprs = 0;
4774 unsigned NumLiterals = 0;
4775 int64_t LiteralValue;
4776
4777 for (int OpIdx : OpIndices) {
4778 if (OpIdx == -1)
4779 break;
4780
4781 const MCOperand &MO = Inst.getOperand(OpIdx);
4782 // Exclude special imm operands (like that used by s_set_gpr_idx_on)
4783 if (AMDGPU::isSISrcOperand(Desc, OpIdx)) {
4784 bool IsLit = false;
4785 std::optional<int64_t> Imm;
4786 if (MO.isImm()) {
4787 Imm = MO.getImm();
4788 } else if (MO.isExpr()) {
4789 if (isLitExpr(MO.getExpr())) {
4790 IsLit = true;
4791 Imm = getLitValue(MO.getExpr());
4792 }
4793 } else {
4794 continue;
4795 }
4796
4797 if (!Imm.has_value()) {
4798 ++NumExprs;
4799 } else if (!isInlineConstant(Inst, OpIdx)) {
4800 auto OpType = static_cast<AMDGPU::OperandType>(
4801 Desc.operands()[OpIdx].OperandType);
4802 int64_t Value = encode32BitLiteral(*Imm, OpType, IsLit);
4803 if (NumLiterals == 0 || LiteralValue != Value) {
4805 ++NumLiterals;
4806 }
4807 }
4808 }
4809 }
4810
4811 if (NumLiterals + NumExprs <= 1)
4812 return true;
4813
4814 Error(getOperandLoc(Operands, Src1Idx),
4815 "only one unique literal operand is allowed");
4816 return false;
4817}
4818
4819bool AMDGPUAsmParser::validateOpSel(const MCInst &Inst) {
4820 const unsigned Opc = Inst.getOpcode();
4821 if (isPermlane16(Opc)) {
4822 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
4823 unsigned OpSel = Inst.getOperand(OpSelIdx).getImm();
4824
4825 if (OpSel & ~3)
4826 return false;
4827 }
4828
4829 if (isGFX940() && SIInstrFlags::isDOT(MII, Inst)) {
4830 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
4831 if (OpSelIdx != -1) {
4832 if (Inst.getOperand(OpSelIdx).getImm() != 0)
4833 return false;
4834 }
4835 int OpSelHiIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel_hi);
4836 if (OpSelHiIdx != -1) {
4837 if (Inst.getOperand(OpSelHiIdx).getImm() != -1)
4838 return false;
4839 }
4840 }
4841
4842 // op_sel[0:1] must be 0 for v_dot2_bf16_bf16 and v_dot2_f16_f16 (VOP3 Dot).
4843 if (isGFX11Plus() && SIInstrFlags::isDOT(MII, Inst) &&
4844 SIInstrFlags::isVOP3(MII, Inst) && !SIInstrFlags::isVOP3P(MII, Inst)) {
4845 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
4846 unsigned OpSel = Inst.getOperand(OpSelIdx).getImm();
4847 if (OpSel & 3)
4848 return false;
4849 }
4850
4851 // gfx950 v_pk_add/mul/fma_f32 have several invalid op_sel encodings
4852 if (getFeatureBits()[AMDGPU::FeatureGFX950Insts] &&
4853 (Opc == AMDGPU::V_PK_ADD_F32_vi || Opc == AMDGPU::V_PK_MUL_F32_vi ||
4854 Opc == AMDGPU::V_PK_FMA_F32_vi)) {
4855 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
4856 unsigned OpSel = Inst.getOperand(OpSelIdx).getImm();
4857
4858 // op_sel[2:1] == 2'b01, 2'b10, or 2'b11 for v_pk_fma.
4859 if (Opc == AMDGPU::V_PK_FMA_F32_vi &&
4860 (((OpSel >> 1) & 1) || ((OpSel >> 2) & 1)))
4861 return false;
4862 // op_sel[1:0] == 2'b10 for v_pk_add/mul_f32.
4863 else if ((OpSel & 3) == 2)
4864 return false;
4865 }
4866
4867 // Packed math FP32 instructions typically accept SGPRs or VGPRs as source
4868 // operands. On gfx12+, if a source operand uses SGPRs, the HW can only read
4869 // the first SGPR and use it for both the low and high operations.
4871 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
4872 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
4873 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
4874 int OpSelHiIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel_hi);
4875
4876 const MCOperand &Src0 = Inst.getOperand(Src0Idx);
4877 const MCOperand &Src1 = Inst.getOperand(Src1Idx);
4878 unsigned OpSel = Inst.getOperand(OpSelIdx).getImm();
4879 unsigned OpSelHi = Inst.getOperand(OpSelHiIdx).getImm();
4880
4881 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
4882
4883 auto VerifyOneSGPR = [OpSel, OpSelHi](unsigned Index) -> bool {
4884 unsigned Mask = 1U << Index;
4885 return ((OpSel & Mask) == 0) && ((OpSelHi & Mask) == 0);
4886 };
4887
4888 if (Src0.isReg() && isSGPR(Src0.getReg(), TRI) &&
4889 !VerifyOneSGPR(/*Index=*/0))
4890 return false;
4891 if (Src1.isReg() && isSGPR(Src1.getReg(), TRI) &&
4892 !VerifyOneSGPR(/*Index=*/1))
4893 return false;
4894
4895 int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
4896 if (Src2Idx != -1) {
4897 const MCOperand &Src2 = Inst.getOperand(Src2Idx);
4898 if (Src2.isReg() && isSGPR(Src2.getReg(), TRI) &&
4899 !VerifyOneSGPR(/*Index=*/2))
4900 return false;
4901 }
4902 }
4903
4904 return true;
4905}
4906
4907bool AMDGPUAsmParser::validateTrue16OpSel(const MCInst &Inst) {
4908 if (!hasTrue16Insts())
4909 return true;
4910 const MCRegisterInfo *MRI = getMRI();
4911 const unsigned Opc = Inst.getOpcode();
4912 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
4913 if (OpSelIdx == -1)
4914 return true;
4915 unsigned OpSelOpValue = Inst.getOperand(OpSelIdx).getImm();
4916 // If the value is 0 we could have a default OpSel Operand, so conservatively
4917 // allow it.
4918 if (OpSelOpValue == 0)
4919 return true;
4920 unsigned OpCount = 0;
4921 for (AMDGPU::OpName OpName : {AMDGPU::OpName::src0, AMDGPU::OpName::src1,
4922 AMDGPU::OpName::src2, AMDGPU::OpName::vdst}) {
4923 int OpIdx = AMDGPU::getNamedOperandIdx(Inst.getOpcode(), OpName);
4924 if (OpIdx == -1)
4925 continue;
4926 const MCOperand &Op = Inst.getOperand(OpIdx);
4927 if (Op.isReg() &&
4928 MRI->getRegClass(AMDGPU::VGPR_16RegClassID).contains(Op.getReg())) {
4929 bool VGPRSuffixIsHi = AMDGPU::isHi16Reg(Op.getReg(), *MRI);
4930 bool OpSelOpIsHi = ((OpSelOpValue & (1 << OpCount)) != 0);
4931 if (OpSelOpIsHi != VGPRSuffixIsHi)
4932 return false;
4933 }
4934 ++OpCount;
4935 }
4936
4937 return true;
4938}
4939
4940bool AMDGPUAsmParser::validateNeg(const MCInst &Inst, AMDGPU::OpName OpName) {
4941 assert(OpName == AMDGPU::OpName::neg_lo || OpName == AMDGPU::OpName::neg_hi);
4942
4943 const unsigned Opc = Inst.getOpcode();
4944
4945 // v_dot4 fp8/bf8 neg_lo/neg_hi not allowed on src0 and src1 (allowed on src2)
4946 // v_wmma iu4/iu8 neg_lo not allowed on src2 (allowed on src0, src1)
4947 // v_swmmac f16/bf16 neg_lo/neg_hi not allowed on src2 (allowed on src0, src1)
4948 // other wmma/swmmac instructions don't have neg_lo/neg_hi operand.
4949 if (!SIInstrFlags::isDOT(MII, Inst) && !SIInstrFlags::isWMMA(MII, Inst) &&
4950 !SIInstrFlags::isSWMMAC(MII, Inst))
4951 return true;
4952
4953 int NegIdx = AMDGPU::getNamedOperandIdx(Opc, OpName);
4954 if (NegIdx == -1)
4955 return true;
4956
4957 unsigned Neg = Inst.getOperand(NegIdx).getImm();
4958
4959 // Instructions that have neg_lo or neg_hi operand but neg modifier is allowed
4960 // on some src operands but not allowed on other.
4961 // It is convenient that such instructions don't have src_modifiers operand
4962 // for src operands that don't allow neg because they also don't allow opsel.
4963
4964 const AMDGPU::OpName SrcMods[3] = {AMDGPU::OpName::src0_modifiers,
4965 AMDGPU::OpName::src1_modifiers,
4966 AMDGPU::OpName::src2_modifiers};
4967
4968 for (unsigned i = 0; i < 3; ++i) {
4969 if (!AMDGPU::hasNamedOperand(Opc, SrcMods[i])) {
4970 if (Neg & (1 << i))
4971 return false;
4972 }
4973 }
4974
4975 return true;
4976}
4977
4978bool AMDGPUAsmParser::validateDPP(const MCInst &Inst,
4979 const OperandVector &Operands) {
4980 const unsigned Opc = Inst.getOpcode();
4981 int DppCtrlIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::dpp_ctrl);
4982 if (DppCtrlIdx >= 0) {
4983 unsigned DppCtrl = Inst.getOperand(DppCtrlIdx).getImm();
4984
4985 if (!AMDGPU::isLegalDPALU_DPPControl(getSTI(), DppCtrl) &&
4986 getSTI().hasFeature(AMDGPU::FeatureDPALU_DPP) &&
4987 AMDGPU::isDPALU_DPP(MII.get(Opc), MII, getSTI())) {
4988 // DP ALU DPP is supported for row_newbcast only on GFX9* and row_share
4989 // only on GFX12.
4990 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyDppCtrl, Operands);
4991 Error(S, isGFX12() ? "DP ALU dpp only supports row_share"
4992 : "DP ALU dpp only supports row_newbcast");
4993 return false;
4994 }
4995 }
4996
4997 int Dpp8Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::dpp8);
4998 bool IsDPP = DppCtrlIdx >= 0 || Dpp8Idx >= 0;
4999
5000 if (IsDPP && !hasDPPSrc1SGPR(getSTI())) {
5001 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
5002 if (Src1Idx >= 0) {
5003 const MCOperand &Src1 = Inst.getOperand(Src1Idx);
5004 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
5005 if (Src1.isReg() && isSGPR(mc2PseudoReg(Src1.getReg()), TRI)) {
5006 Error(getOperandLoc(Operands, Src1Idx),
5007 "invalid operand for instruction");
5008 return false;
5009 }
5010 if (Src1.isImm()) {
5011 Error(getInstLoc(Operands),
5012 "src1 immediate operand invalid for instruction");
5013 return false;
5014 }
5015 }
5016 }
5017
5018 return true;
5019}
5020
5021// Check if VCC register matches wavefront size
5022bool AMDGPUAsmParser::validateVccOperand(MCRegister Reg) const {
5023 return (Reg == AMDGPU::VCC && isWave64()) ||
5024 (Reg == AMDGPU::VCC_LO && isWave32());
5025}
5026
5027// One unique literal can be used. VOP3 literal is only allowed in GFX10+
5028bool AMDGPUAsmParser::validateVOPLiteral(const MCInst &Inst,
5029 const OperandVector &Operands) {
5030 unsigned Opcode = Inst.getOpcode();
5031 const MCInstrDesc &Desc = MII.get(Opcode);
5032 bool HasMandatoryLiteral = getNamedOperandIdx(Opcode, OpName::imm) != -1;
5033 if (!SIInstrFlags::isVOP3Like(Desc) && !HasMandatoryLiteral &&
5034 !isVOPD(Opcode))
5035 return true;
5036
5037 OperandIndices OpIndices = getSrcOperandIndices(Opcode, HasMandatoryLiteral);
5038
5039 std::optional<unsigned> LiteralOpIdx;
5040 std::optional<uint64_t> LiteralValue;
5041
5042 for (int OpIdx : OpIndices) {
5043 if (OpIdx == -1)
5044 continue;
5045
5046 const MCOperand &MO = Inst.getOperand(OpIdx);
5047 if (!MO.isImm() && !MO.isExpr())
5048 continue;
5049 if (!isSISrcOperand(Desc, OpIdx))
5050 continue;
5051
5052 std::optional<int64_t> Imm;
5053 if (MO.isImm())
5054 Imm = MO.getImm();
5055 else if (MO.isExpr() && isLitExpr(MO.getExpr()))
5056 Imm = getLitValue(MO.getExpr());
5057
5058 bool IsAnotherLiteral = false;
5059 bool IsForcedLit = findMCOperand(Operands, OpIdx).isForcedLit();
5060 bool IsForcedLit64 = findMCOperand(Operands, OpIdx).isForcedLit64();
5061 if (!Imm.has_value()) {
5062 // Literal value not known, so we conservately assume it's different.
5063 IsAnotherLiteral = true;
5064 } else if (IsForcedLit || IsForcedLit64 || !isInlineConstant(Inst, OpIdx)) {
5065 uint64_t Value = *Imm;
5066 bool IsForcedFP64 =
5067 Desc.operands()[OpIdx].OperandType == AMDGPU::OPERAND_KIMM64 ||
5068 (Desc.operands()[OpIdx].OperandType == AMDGPU::OPERAND_REG_IMM_FP64 &&
5069 HasMandatoryLiteral);
5070 AMDGPU::OperandType OpTy =
5071 static_cast<AMDGPU::OperandType>(Desc.operands()[OpIdx].OperandType);
5072 bool IsFP64 =
5073 (IsForcedFP64 || (AMDGPU::isSISrcFPOperand(Desc, OpIdx) &&
5075 AMDGPU::getOperandSize(Desc.operands()[OpIdx]) == 8;
5076 bool IsValid32Op =
5077 IsForcedLit || AMDGPU::isValid32BitLiteral(Value, IsFP64);
5078
5079 if (((!IsValid32Op && !isInt<32>(Value) && !isUInt<32>(Value) &&
5080 !IsForcedFP64) ||
5081 (IsForcedLit64 && !HasMandatoryLiteral)) &&
5082 (!has64BitLiterals() || Desc.getSize() != 4)) {
5083 Error(getOperandLoc(Operands, OpIdx),
5084 "invalid operand for instruction");
5085 return false;
5086 }
5087
5088 // Only src0 can use lit64 in VOP* encoding.
5089 if (!IsForcedFP64 && (IsForcedLit64 || !IsValid32Op) &&
5090 OpIdx != getNamedOperandIdx(Opcode, OpName::src0)) {
5091 Error(getOperandLoc(Operands, OpIdx),
5092 "invalid operand for instruction");
5093 return false;
5094 }
5095
5096 // Compare values using the word encoded by a 32-bit literal.
5097 if (IsValid32Op && !IsForcedFP64 && !IsForcedLit64) {
5098 Value = static_cast<uint32_t>(
5099 AMDGPU::encode32BitLiteral(Value, OpTy, IsForcedLit));
5100 }
5101
5102 IsAnotherLiteral = !LiteralValue || *LiteralValue != Value;
5104 }
5105
5106 if (IsAnotherLiteral && !HasMandatoryLiteral &&
5107 !getFeatureBits()[FeatureVOP3Literal]) {
5108 Error(getOperandLoc(Operands, OpIdx),
5109 "literal operands are not supported");
5110 return false;
5111 }
5112
5113 if (LiteralOpIdx && IsAnotherLiteral) {
5114 Error(getLaterLoc(getOperandLoc(Operands, OpIdx),
5115 getOperandLoc(Operands, *LiteralOpIdx)),
5116 "only one unique literal operand is allowed");
5117 return false;
5118 }
5119
5120 if (IsAnotherLiteral)
5121 LiteralOpIdx = OpIdx;
5122 }
5123
5124 return true;
5125}
5126
5127// Returns -1 if not a register, 0 if VGPR and 1 if AGPR.
5128static int IsAGPROperand(const MCInst &Inst, AMDGPU::OpName Name,
5129 const MCRegisterInfo *MRI) {
5130 int OpIdx = AMDGPU::getNamedOperandIdx(Inst.getOpcode(), Name);
5131 if (OpIdx < 0)
5132 return -1;
5133
5134 const MCOperand &Op = Inst.getOperand(OpIdx);
5135 if (!Op.isReg())
5136 return -1;
5137
5138 MCRegister Sub = MRI->getSubReg(Op.getReg(), AMDGPU::sub0);
5139 auto Reg = Sub ? Sub : Op.getReg();
5140 const MCRegisterClass &AGPR32 = MRI->getRegClass(AMDGPU::AGPR_32RegClassID);
5141 return AGPR32.contains(Reg) ? 1 : 0;
5142}
5143
5144bool AMDGPUAsmParser::validateAGPRLdSt(const MCInst &Inst) const {
5145 if (!SIInstrFlags::isFLAT(MII, Inst) && !SIInstrFlags::isBuffer(MII, Inst) &&
5146 !SIInstrFlags::isMIMG(MII, Inst) && !SIInstrFlags::isDS(MII, Inst))
5147 return true;
5148
5149 AMDGPU::OpName DataName = SIInstrFlags::isDS(MII, Inst)
5150 ? AMDGPU::OpName::data0
5151 : AMDGPU::OpName::vdata;
5152
5153 const MCRegisterInfo *MRI = getMRI();
5154 int DstAreg = IsAGPROperand(Inst, AMDGPU::OpName::vdst, MRI);
5155 int DataAreg = IsAGPROperand(Inst, DataName, MRI);
5156
5157 if (SIInstrFlags::isDS(MII, Inst) && DataAreg >= 0) {
5158 int Data2Areg = IsAGPROperand(Inst, AMDGPU::OpName::data1, MRI);
5159 if (Data2Areg >= 0 && Data2Areg != DataAreg)
5160 return false;
5161 }
5162
5163 auto FB = getFeatureBits();
5164 if (FB[AMDGPU::FeatureGFX90AInsts]) {
5165 if (DataAreg < 0 || DstAreg < 0)
5166 return true;
5167 return DstAreg == DataAreg;
5168 }
5169
5170 return DstAreg < 1 && DataAreg < 1;
5171}
5172
5173bool AMDGPUAsmParser::validateVGPRAlign(const MCInst &Inst) const {
5174 auto FB = getFeatureBits();
5175 if (!FB[AMDGPU::FeatureRequiresAlignedVGPRs])
5176 return true;
5177
5178 unsigned Opc = Inst.getOpcode();
5179 const MCRegisterInfo *MRI = getMRI();
5180 // DS_READ_B96_TR_B6 is the only DS instruction in GFX950, that allows
5181 // unaligned VGPR. All others only allow even aligned VGPRs.
5182 if (FB[AMDGPU::FeatureGFX90AInsts] && Opc == AMDGPU::DS_READ_B96_TR_B6_vi)
5183 return true;
5184
5185 if (FB[AMDGPU::FeatureGFX1250Insts]) {
5186 switch (Opc) {
5187 default:
5188 break;
5189 case AMDGPU::DS_LOAD_TR6_B96:
5190 case AMDGPU::DS_LOAD_TR6_B96_gfx12:
5191 // DS_LOAD_TR6_B96 is the only DS instruction in GFX1250, that
5192 // allows unaligned VGPR. All others only allow even aligned VGPRs.
5193 return true;
5194 case AMDGPU::GLOBAL_LOAD_TR6_B96:
5195 case AMDGPU::GLOBAL_LOAD_TR6_B96_gfx1250: {
5196 // GLOBAL_LOAD_TR6_B96 is the only GLOBAL instruction in GFX1250, that
5197 // allows unaligned VGPR for vdst, but other operands still only allow
5198 // even aligned VGPRs.
5199 int VAddrIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
5200 if (VAddrIdx != -1) {
5201 const MCOperand &Op = Inst.getOperand(VAddrIdx);
5202 MCRegister Sub = MRI->getSubReg(Op.getReg(), AMDGPU::sub0);
5203 if ((Sub - AMDGPU::VGPR0) & 1)
5204 return false;
5205 }
5206 return true;
5207 }
5208 case AMDGPU::GLOBAL_LOAD_TR6_B96_SADDR:
5209 case AMDGPU::GLOBAL_LOAD_TR6_B96_SADDR_gfx1250:
5210 return true;
5211 }
5212 }
5213
5214 const MCRegisterClass &VGPR32 = MRI->getRegClass(AMDGPU::VGPR_32RegClassID);
5215 const MCRegisterClass &AGPR32 = MRI->getRegClass(AMDGPU::AGPR_32RegClassID);
5216 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
5217 const MCOperand &Op = Inst.getOperand(I);
5218 if (!Op.isReg())
5219 continue;
5220
5221 MCRegister Sub = MRI->getSubReg(Op.getReg(), AMDGPU::sub0);
5222 if (!Sub)
5223 continue;
5224
5225 if (VGPR32.contains(Sub) && ((Sub - AMDGPU::VGPR0) & 1))
5226 return false;
5227 if (AGPR32.contains(Sub) && ((Sub - AMDGPU::AGPR0) & 1))
5228 return false;
5229 }
5230
5231 return true;
5232}
5233
5234SMLoc AMDGPUAsmParser::getBLGPLoc(const OperandVector &Operands) const {
5235 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
5236 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
5237 if (Op.isBLGP())
5238 return Op.getStartLoc();
5239 }
5240 return SMLoc();
5241}
5242
5243bool AMDGPUAsmParser::validateBLGP(const MCInst &Inst,
5244 const OperandVector &Operands) {
5245 unsigned Opc = Inst.getOpcode();
5246 int BlgpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::blgp);
5247 if (BlgpIdx == -1)
5248 return true;
5249 SMLoc BLGPLoc = getBLGPLoc(Operands);
5250 if (!BLGPLoc.isValid())
5251 return true;
5252 bool IsNeg = StringRef(BLGPLoc.getPointer()).starts_with("neg:");
5253 auto FB = getFeatureBits();
5254 bool UsesNeg = false;
5255 if (FB[AMDGPU::FeatureGFX940Insts]) {
5256 switch (Opc) {
5257 case AMDGPU::V_MFMA_F64_16X16X4F64_gfx940_acd:
5258 case AMDGPU::V_MFMA_F64_16X16X4F64_gfx940_vcd:
5259 case AMDGPU::V_MFMA_F64_4X4X4F64_gfx940_acd:
5260 case AMDGPU::V_MFMA_F64_4X4X4F64_gfx940_vcd:
5261 UsesNeg = true;
5262 }
5263 }
5264
5265 if (IsNeg == UsesNeg)
5266 return true;
5267
5268 Error(BLGPLoc, UsesNeg ? "invalid modifier: blgp is not supported"
5269 : "invalid modifier: neg is not supported");
5270
5271 return false;
5272}
5273
5274bool AMDGPUAsmParser::validateWaitCnt(const MCInst &Inst,
5275 const OperandVector &Operands) {
5276 if (!isGFX11Plus())
5277 return true;
5278
5279 unsigned Opc = Inst.getOpcode();
5280 if (Opc != AMDGPU::S_WAITCNT_EXPCNT_gfx11 &&
5281 Opc != AMDGPU::S_WAITCNT_LGKMCNT_gfx11 &&
5282 Opc != AMDGPU::S_WAITCNT_VMCNT_gfx11 &&
5283 Opc != AMDGPU::S_WAITCNT_VSCNT_gfx11)
5284 return true;
5285
5286 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::sdst);
5287 assert(Src0Idx >= 0 && Inst.getOperand(Src0Idx).isReg());
5288 auto Reg = mc2PseudoReg(Inst.getOperand(Src0Idx).getReg());
5289 if (Reg == AMDGPU::SGPR_NULL)
5290 return true;
5291
5292 Error(getOperandLoc(Operands, Src0Idx), "src0 must be null");
5293 return false;
5294}
5295
5296bool AMDGPUAsmParser::validateDS(const MCInst &Inst,
5297 const OperandVector &Operands) {
5298 if (!SIInstrFlags::isDS(MII, Inst))
5299 return true;
5300 if (SIInstrFlags::isGWS(MII, Inst))
5301 return validateGWS(Inst, Operands);
5302 // Only validate GDS for non-GWS instructions.
5303 if (hasGDS())
5304 return true;
5305 int GDSIdx =
5306 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::gds);
5307 if (GDSIdx < 0)
5308 return true;
5309 unsigned GDS = Inst.getOperand(GDSIdx).getImm();
5310 if (GDS) {
5311 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyGDS, Operands);
5312 Error(S, "gds modifier is not supported on this GPU");
5313 return false;
5314 }
5315 return true;
5316}
5317
5318// gfx90a has an undocumented limitation:
5319// DS_GWS opcodes must use even aligned registers.
5320bool AMDGPUAsmParser::validateGWS(const MCInst &Inst,
5321 const OperandVector &Operands) {
5322 if (!getFeatureBits()[AMDGPU::FeatureGFX90AInsts])
5323 return true;
5324
5325 int Opc = Inst.getOpcode();
5326 if (Opc != AMDGPU::DS_GWS_INIT_vi && Opc != AMDGPU::DS_GWS_BARRIER_vi &&
5327 Opc != AMDGPU::DS_GWS_SEMA_BR_vi)
5328 return true;
5329
5330 const MCRegisterInfo *MRI = getMRI();
5331 const MCRegisterClass &VGPR32 = MRI->getRegClass(AMDGPU::VGPR_32RegClassID);
5332 int Data0Pos =
5333 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data0);
5334 assert(Data0Pos != -1);
5335 auto Reg = Inst.getOperand(Data0Pos).getReg();
5336 auto RegIdx = Reg - (VGPR32.contains(Reg) ? AMDGPU::VGPR0 : AMDGPU::AGPR0);
5337 if (RegIdx & 1) {
5338 Error(getOperandLoc(Operands, Data0Pos), "vgpr must be even aligned");
5339 return false;
5340 }
5341
5342 return true;
5343}
5344
5345bool AMDGPUAsmParser::validateCoherencyBits(const MCInst &Inst,
5346 const OperandVector &Operands,
5347 SMLoc IDLoc) {
5348 int CPolPos =
5349 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::cpol);
5350 if (CPolPos == -1)
5351 return true;
5352
5353 unsigned CPol = Inst.getOperand(CPolPos).getImm();
5354
5355 if (CPol & CPol::CFS) {
5356 if (!hasCacheFillSize()) {
5357 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5358 StringRef CStr(S.getPointer());
5359 S = SMLoc::getFromPointer(&CStr.data()[CStr.find("cfs")]);
5360 Error(S, "Cache fill size is not supported on this GPU");
5361 } else if (!validateCFSBits(Inst, Operands)) {
5362 return false;
5363 }
5364 }
5365
5366 if (!hasScaleOffset() && (CPol & CPol::SCAL)) {
5367 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5368 StringRef CStr(S.getPointer());
5369 S = SMLoc::getFromPointer(&CStr.data()[CStr.find("scale_offset")]);
5370 Error(S, "scale_offset is not supported on this GPU");
5371 }
5372
5373 if (!isGFX1250Plus() && (CPol & CPol::NV)) {
5374 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5375 StringRef CStr(S.getPointer());
5376 S = SMLoc::getFromPointer(&CStr.data()[CStr.find("nv")]);
5377 Error(S, "nv is not supported on this GPU");
5378 }
5379
5380 if ((CPol & CPol::SCAL) && !supportsScaleOffset(MII, Inst.getOpcode())) {
5381 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5382 StringRef CStr(S.getPointer());
5383 S = SMLoc::getFromPointer(&CStr.data()[CStr.find("scale_offset")]);
5384 Error(S, "scale_offset is not supported for this instruction");
5385 }
5386
5387 if (isGFX12Plus())
5388 return validateTHAndScopeBits(Inst, Operands, CPol);
5389
5390 if (SIInstrFlags::isSMRD(MII, Inst)) {
5391 if (CPol && (isSI() || isCI())) {
5392 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5393 Error(S, "cache policy is not supported for SMRD instructions");
5394 return false;
5395 }
5396 if (CPol & ~(AMDGPU::CPol::GLC | AMDGPU::CPol::DLC)) {
5397 Error(IDLoc, "invalid cache policy for SMEM instruction");
5398 return false;
5399 }
5400 }
5401
5402 if (isGFX90A() && !isGFX940() && (CPol & CPol::SCC)) {
5403 if (!SIInstrFlags::isVMEM(MII, Inst)) {
5404 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5405 StringRef CStr(S.getPointer());
5406 S = SMLoc::getFromPointer(&CStr.data()[CStr.find("scc")]);
5407 Error(S,
5408 "scc modifier is not supported for this instruction on this GPU");
5409 return false;
5410 }
5411 }
5412
5413 if (!SIInstrFlags::isAtomic(MII, Inst))
5414 return true;
5415
5416 if (SIInstrFlags::isAtomicRet(MII, Inst)) {
5417 if (!SIInstrFlags::isMIMG(MII, Inst) && !(CPol & CPol::GLC)) {
5418 Error(IDLoc, isGFX940() ? "instruction must use sc0"
5419 : "instruction must use glc");
5420 return false;
5421 }
5422 } else {
5423 if (CPol & CPol::GLC) {
5424 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5425 StringRef CStr(S.getPointer());
5427 &CStr.data()[CStr.find(isGFX940() ? "sc0" : "glc")]);
5428 Error(S, isGFX940() ? "instruction must not use sc0"
5429 : "instruction must not use glc");
5430 return false;
5431 }
5432 }
5433
5434 return true;
5435}
5436
5437bool AMDGPUAsmParser::validateTHAndScopeBits(const MCInst &Inst,
5438 const OperandVector &Operands,
5439 const unsigned CPol) {
5440 const unsigned TH = CPol & AMDGPU::CPol::TH;
5441 const unsigned Scope = CPol & AMDGPU::CPol::SCOPE;
5442
5443 auto PrintError = [&](StringRef Msg) {
5444 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5445 Error(S, Msg);
5446 return false;
5447 };
5448
5449 if ((TH & AMDGPU::CPol::TH_ATOMIC_RETURN) &&
5450 SIInstrFlags::isAtomicNoRet(MII, Inst))
5451 return PrintError("th:TH_ATOMIC_RETURN requires a destination operand");
5452
5453 if (SIInstrFlags::isAtomicRet(MII, Inst) &&
5454 (SIInstrFlags::isFLAT(MII, Inst) || SIInstrFlags::isMUBUF(MII, Inst)) &&
5456 return PrintError("instruction must use th:TH_ATOMIC_RETURN");
5457
5458 if (TH == 0)
5459 return true;
5460
5461 if (SIInstrFlags::isSMRD(MII, Inst) &&
5462 ((TH == AMDGPU::CPol::TH_NT_RT) || (TH == AMDGPU::CPol::TH_RT_NT) ||
5463 (TH == AMDGPU::CPol::TH_NT_HT)))
5464 return PrintError("invalid th value for SMEM instruction");
5465
5466 if (TH == AMDGPU::CPol::TH_BYPASS) {
5467 if ((Scope != AMDGPU::CPol::SCOPE_SYS &&
5469 (Scope == AMDGPU::CPol::SCOPE_SYS &&
5471 return PrintError("scope and th combination is not valid");
5472 }
5473
5474 unsigned THType = AMDGPU::getTemporalHintType(MII.get(Inst.getOpcode()));
5475 if (THType == AMDGPU::CPol::TH_TYPE_ATOMIC) {
5476 if (!(CPol & AMDGPU::CPol::TH_TYPE_ATOMIC))
5477 return PrintError("invalid th value for atomic instructions");
5478 } else if (THType == AMDGPU::CPol::TH_TYPE_STORE) {
5479 if (!(CPol & AMDGPU::CPol::TH_TYPE_STORE))
5480 return PrintError("invalid th value for store instructions");
5481 } else {
5482 if (!(CPol & AMDGPU::CPol::TH_TYPE_LOAD))
5483 return PrintError("invalid th value for load instructions");
5484 }
5485
5486 return true;
5487}
5488
5489bool AMDGPUAsmParser::validateCFSBits(const MCInst &Inst,
5490 const OperandVector &Operands) {
5491 const unsigned Opcode = Inst.getOpcode();
5492 const MCInstrDesc &Desc = MII.get(Opcode);
5493
5494 auto PrintError = [&](StringRef Msg) {
5495 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5496 Error(S, Msg);
5497 return false;
5498 };
5499
5501 return true;
5502
5503 return PrintError("Cache fill size is only supported for VC operations");
5504}
5505
5506bool AMDGPUAsmParser::validateTFE(const MCInst &Inst,
5507 const OperandVector &Operands) {
5508 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
5509 if (Desc.mayStore() && SIInstrFlags::isBuffer(Desc)) {
5510 SMLoc Loc = getImmLoc(AMDGPUOperand::ImmTyTFE, Operands);
5511 if (Loc != getInstLoc(Operands)) {
5512 Error(Loc, "TFE modifier has no meaning for store instructions");
5513 return false;
5514 }
5515 }
5516
5517 return true;
5518}
5519
5520bool AMDGPUAsmParser::validateWMMA(const MCInst &Inst,
5521 const OperandVector &Operands) {
5522 unsigned Opc = Inst.getOpcode();
5523 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
5524 const MCInstrDesc &Desc = MII.get(Opc);
5525
5526 int AFmtIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_a_fmt);
5527 if (AFmtIdx == -1)
5528 return true;
5529 unsigned AFmt = Inst.getOperand(AFmtIdx).getImm();
5530 int BFmtIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_b_fmt);
5531 unsigned BFmt = Inst.getOperand(BFmtIdx).getImm();
5532
5533 auto validateFmt = [&](unsigned Fmt, AMDGPU::OpName SrcOp) -> bool {
5534 int SrcIdx = AMDGPU::getNamedOperandIdx(Opc, SrcOp);
5535 unsigned RegSize =
5536 TRI->getRegClass(MII.getOpRegClassID(Desc.operands()[SrcIdx], HwMode))
5537 .getSizeInBits();
5538
5540 return true;
5541
5542 Error(getOperandLoc(Operands, SrcIdx),
5543 "wrong register tuple size for " +
5544 Twine(WMMAMods::ModMatrixFmt[Fmt]));
5545 return false;
5546 };
5547
5548 if (!validateFmt(AFmt, AMDGPU::OpName::src0) ||
5549 !validateFmt(BFmt, AMDGPU::OpName::src1))
5550 return false;
5551
5552 int AScaleIdx =
5553 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_a_scale_fmt);
5554 if (AScaleIdx == -1)
5555 return true;
5556 unsigned AScale = Inst.getOperand(AScaleIdx).getImm();
5557 int BScaleIdx =
5558 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_b_scale_fmt);
5559 unsigned BScale = Inst.getOperand(BScaleIdx).getImm();
5560 if (!isValidWMMAScaleFmtCombination(AFmt, AScale, BFmt, BScale)) {
5561 Error(getImmLoc(AMDGPUOperand::ImmTyMatrixAFMT, Operands),
5562 "invalid matrix and scale format combination");
5563 return false;
5564 }
5565
5566 return true;
5567}
5568
5569bool AMDGPUAsmParser::validateMonitorSleep(const MCInst &Inst,
5570 const OperandVector &Operands) {
5571 unsigned Opc = Inst.getOpcode();
5572 if (Opc != AMDGPU::S_MONITOR_SLEEP_gfx12 ||
5573 !getSTI().hasFeature(AMDGPU::FeatureNoSleepForever))
5574 return true;
5575
5576 int ImmIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::simm16);
5577 if (Inst.getOperand(ImmIdx).getImm() & 0x8000) {
5578 Error(getOperandLoc(Operands, ImmIdx),
5579 "sleep forever is unsupported on the target");
5580 return false;
5581 }
5582
5583 return true;
5584}
5585
5586bool AMDGPUAsmParser::validateClusterBarrierIsFirst(
5587 const MCInst &Inst, const OperandVector &Operands) {
5588 unsigned Opc = Inst.getOpcode();
5589 if (Opc != AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM_gfx12 &&
5590 Opc != AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM_gfx13)
5591 return true;
5592
5593 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
5594 int BarrierID = Inst.getOperand(Src0Idx).getImm();
5595 if (BarrierID != AMDGPU::Barrier::CLUSTER)
5596 return true;
5597
5598 Error(
5599 getOperandLoc(Operands, Src0Idx),
5600 "s_barrier_signal_isfirst does not support user_cluster_barrier_id (-3)");
5601 return false;
5602}
5603
5604bool AMDGPUAsmParser::validateScaleSel(const MCInst &Inst,
5605 const OperandVector &Operands) {
5606 unsigned Opc = Inst.getOpcode();
5607 int ScaleSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::scale_sel);
5608 if (ScaleSelIdx == -1)
5609 return true;
5610 int MaxSel = 0;
5611 switch (Opc) {
5612 case AMDGPU::V_CVT_SCALE_PK16_F16_FP6_e64_gfx1250:
5613 case AMDGPU::V_CVT_SCALE_PK16_BF16_FP6_e64_gfx1250:
5614 case AMDGPU::V_CVT_SCALE_PK16_F16_BF6_e64_gfx1250:
5615 case AMDGPU::V_CVT_SCALE_PK16_BF16_BF6_e64_gfx1250:
5616 case AMDGPU::V_CVT_SCALE_PK16_F32_FP6_e64_gfx1250:
5617 case AMDGPU::V_CVT_SCALE_PK16_F32_BF6_e64_gfx1250:
5618 case AMDGPU::V_CVT_SCALE_PK8_F16_FP4_e64_gfx1250:
5619 case AMDGPU::V_CVT_SCALE_PK8_BF16_FP4_e64_gfx1250:
5620 case AMDGPU::V_CVT_SCALE_PK8_F32_FP4_e64_gfx1250:
5621 MaxSel = 4;
5622 break;
5623 case AMDGPU::V_CVT_SCALE_PK8_F16_FP8_e64_gfx1250:
5624 case AMDGPU::V_CVT_SCALE_PK8_BF16_FP8_e64_gfx1250:
5625 case AMDGPU::V_CVT_SCALE_PK8_F16_BF8_e64_gfx1250:
5626 case AMDGPU::V_CVT_SCALE_PK8_BF16_BF8_e64_gfx1250:
5627 case AMDGPU::V_CVT_SCALE_PK8_F32_FP8_e64_gfx1250:
5628 case AMDGPU::V_CVT_SCALE_PK8_F32_BF8_e64_gfx1250:
5629 MaxSel = 8;
5630 break;
5631 default:
5632 return true;
5633 }
5634
5635 if (getSTI().hasFeature(AMDGPU::FeatureBlock16ConversionScaleInsts))
5636 MaxSel *= 2;
5637
5638 int ScaleSel = Inst.getOperand(ScaleSelIdx).getImm();
5639 if (ScaleSel < MaxSel)
5640 return true;
5641
5642 Error(getOperandLoc(Operands, ScaleSelIdx),
5643 "scale_sel maximum supported value is " + Twine(MaxSel - 1));
5644 return false;
5645}
5646
5647bool AMDGPUAsmParser::validateInstruction(const MCInst &Inst, SMLoc IDLoc,
5648 const OperandVector &Operands) {
5649 if (!validateLdsDirect(Inst, Operands))
5650 return false;
5651 if (!validateTrue16OpSel(Inst)) {
5652 Error(getImmLoc(AMDGPUOperand::ImmTyOpSel, Operands),
5653 "op_sel operand conflicts with 16-bit operand suffix");
5654 return false;
5655 }
5656 if (!validateSOPLiteral(Inst, Operands))
5657 return false;
5658 if (!validateVOPLiteral(Inst, Operands)) {
5659 return false;
5660 }
5661 if (!validateConstantBusLimitations(Inst, Operands)) {
5662 return false;
5663 }
5664 if (!validateVOPD(Inst, Operands)) {
5665 return false;
5666 }
5667 if (!validateIntClampSupported(Inst)) {
5668 Error(getImmLoc(AMDGPUOperand::ImmTyClamp, Operands),
5669 "integer clamping is not supported on this GPU");
5670 return false;
5671 }
5672 if (!validateOpSel(Inst)) {
5673 Error(getImmLoc(AMDGPUOperand::ImmTyOpSel, Operands),
5674 "invalid op_sel operand");
5675 return false;
5676 }
5677 if (!validateNeg(Inst, AMDGPU::OpName::neg_lo)) {
5678 Error(getImmLoc(AMDGPUOperand::ImmTyNegLo, Operands),
5679 "invalid neg_lo operand");
5680 return false;
5681 }
5682 if (!validateNeg(Inst, AMDGPU::OpName::neg_hi)) {
5683 Error(getImmLoc(AMDGPUOperand::ImmTyNegHi, Operands),
5684 "invalid neg_hi operand");
5685 return false;
5686 }
5687 if (!validateDPP(Inst, Operands)) {
5688 return false;
5689 }
5690 // For MUBUF/MTBUF d16 is a part of opcode, so there is nothing to validate.
5691 if (!validateMIMGD16(Inst)) {
5692 Error(getImmLoc(AMDGPUOperand::ImmTyD16, Operands),
5693 "d16 modifier is not supported on this GPU");
5694 return false;
5695 }
5696 if (!validateMIMGDim(Inst, Operands)) {
5697 Error(IDLoc, "missing dim operand");
5698 return false;
5699 }
5700 if (!validateTensorR128(Inst)) {
5701 Error(getImmLoc(AMDGPUOperand::ImmTyD16, Operands),
5702 "instruction must set modifier r128=0");
5703 return false;
5704 }
5705 if (!validateMIMGMSAA(Inst)) {
5706 Error(getImmLoc(AMDGPUOperand::ImmTyDim, Operands),
5707 "invalid dim; must be MSAA type");
5708 return false;
5709 }
5710 if (!validateMIMGDataSize(Inst, IDLoc)) {
5711 return false;
5712 }
5713 if (!validateMIMGAddrSize(Inst, IDLoc))
5714 return false;
5715 if (!validateMIMGAtomicDMask(Inst)) {
5716 Error(getImmLoc(AMDGPUOperand::ImmTyDMask, Operands),
5717 "invalid atomic image dmask");
5718 return false;
5719 }
5720 if (!validateMIMGGatherDMask(Inst)) {
5721 Error(getImmLoc(AMDGPUOperand::ImmTyDMask, Operands),
5722 "invalid image_gather dmask: only one bit must be set");
5723 return false;
5724 }
5725 if (!validateMovrels(Inst, Operands)) {
5726 return false;
5727 }
5728 if (!validateOffset(Inst, Operands)) {
5729 return false;
5730 }
5731 if (!validateSMEMSData(Inst, Operands))
5732 return false;
5733 if (!validateBF16InlineConst(Inst, Operands)) {
5734 return false;
5735 }
5736 if (!validateMAIAccWrite(Inst, Operands)) {
5737 return false;
5738 }
5739 if (!validateMAISrc2(Inst, Operands)) {
5740 return false;
5741 }
5742 if (!validateMFMA(Inst, Operands)) {
5743 return false;
5744 }
5745 if (!validateCoherencyBits(Inst, Operands, IDLoc)) {
5746 return false;
5747 }
5748
5749 if (!validateAGPRLdSt(Inst)) {
5750 Error(
5751 IDLoc,
5752 getFeatureBits()[AMDGPU::FeatureGFX90AInsts]
5753 ? "invalid register class: data and dst should be all VGPR or AGPR"
5754 : "invalid register class: agpr loads and stores not supported on "
5755 "this GPU");
5756 return false;
5757 }
5758 if (!validateVGPRAlign(Inst)) {
5759 Error(IDLoc, "invalid register class: vgpr tuples must be 64 bit aligned");
5760 return false;
5761 }
5762 if (!validateDS(Inst, Operands)) {
5763 return false;
5764 }
5765
5766 if (!validateBLGP(Inst, Operands)) {
5767 return false;
5768 }
5769
5770 if (!validateDivScale(Inst)) {
5771 Error(IDLoc, "ABS not allowed in VOP3B instructions");
5772 return false;
5773 }
5774 if (!validateWaitCnt(Inst, Operands)) {
5775 return false;
5776 }
5777 if (!validateTFE(Inst, Operands)) {
5778 return false;
5779 }
5780 if (!validateWMMA(Inst, Operands)) {
5781 return false;
5782 }
5783 if (!validateMonitorSleep(Inst, Operands)) {
5784 return false;
5785 }
5786 if (!validateClusterBarrierIsFirst(Inst, Operands)) {
5787 return false;
5788 }
5789 if (!validateScaleSel(Inst, Operands)) {
5790 return false;
5791 }
5792
5793 return true;
5794}
5795
5797 const FeatureBitset &FBS,
5798 unsigned VariantID = 0);
5799
5800static bool AMDGPUCheckMnemonic(StringRef Mnemonic,
5801 const FeatureBitset &AvailableFeatures,
5802 unsigned VariantID);
5803
5804bool AMDGPUAsmParser::isSupportedMnemo(StringRef Mnemo,
5805 const FeatureBitset &FBS) {
5806 return isSupportedMnemo(Mnemo, FBS, getAllVariants());
5807}
5808
5809bool AMDGPUAsmParser::isSupportedMnemo(StringRef Mnemo,
5810 const FeatureBitset &FBS,
5811 ArrayRef<unsigned> Variants) {
5812 for (auto Variant : Variants) {
5813 if (AMDGPUCheckMnemonic(Mnemo, FBS, Variant))
5814 return true;
5815 }
5816
5817 return false;
5818}
5819
5820bool AMDGPUAsmParser::checkUnsupportedInstruction(StringRef Mnemo,
5821 SMLoc IDLoc) {
5822 FeatureBitset FBS = ComputeAvailableFeatures(getFeatureBits());
5823
5824 // Check if requested instruction variant is supported.
5825 if (isSupportedMnemo(Mnemo, FBS, getMatchedVariants()))
5826 return false;
5827
5828 // This instruction is not supported.
5829 // Clear any other pending errors because they are no longer relevant.
5830 getParser().clearPendingErrors();
5831
5832 // Requested instruction variant is not supported.
5833 // Check if any other variants are supported.
5834 StringRef VariantName = getMatchedVariantName();
5835 if (!VariantName.empty() && isSupportedMnemo(Mnemo, FBS)) {
5836 return Error(IDLoc, Twine(VariantName,
5837 " variant of this instruction is not supported"));
5838 }
5839
5840 // Check if this instruction may be used with a different wavesize.
5841 if (isGFX10Plus() && getFeatureBits()[AMDGPU::FeatureWavefrontSize64] &&
5842 !getFeatureBits()[AMDGPU::FeatureWavefrontSize32]) {
5843 // FIXME: Use getAvailableFeatures, and do not manually recompute
5844 FeatureBitset FeaturesWS32 = getFeatureBits();
5845 FeaturesWS32.flip(AMDGPU::FeatureWavefrontSize64)
5846 .flip(AMDGPU::FeatureWavefrontSize32);
5847 FeatureBitset AvailableFeaturesWS32 =
5848 ComputeAvailableFeatures(FeaturesWS32);
5849
5850 if (isSupportedMnemo(Mnemo, AvailableFeaturesWS32, getMatchedVariants()))
5851 return Error(IDLoc, "instruction requires wavesize=32");
5852 }
5853
5854 // Finally check if this instruction is supported on any other GPU.
5855 if (isSupportedMnemo(Mnemo, FeatureBitset().set())) {
5856 return Error(IDLoc, "instruction not supported on this GPU (" +
5857 getSTI().getCPU() + ")" + ": " + Mnemo);
5858 }
5859
5860 // Instruction not supported on any GPU. Probably a typo.
5861 std::string Suggestion = AMDGPUMnemonicSpellCheck(Mnemo, FBS);
5862 return Error(IDLoc, "invalid instruction" + Suggestion);
5863}
5864
5866 uint64_t InvalidOprIdx) {
5867 assert(InvalidOprIdx < Operands.size());
5868 const auto &Op = ((AMDGPUOperand &)*Operands[InvalidOprIdx]);
5869 if (Op.isToken() && InvalidOprIdx > 1) {
5870 const auto &PrevOp = ((AMDGPUOperand &)*Operands[InvalidOprIdx - 1]);
5871 return PrevOp.isToken() && PrevOp.getToken() == "::";
5872 }
5873 return false;
5874}
5875
5876bool AMDGPUAsmParser::matchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
5878 MCStreamer &Out,
5879 uint64_t &ErrorInfo,
5880 bool MatchingInlineAsm) {
5881 MCInst Inst;
5882 Inst.setLoc(IDLoc);
5883 unsigned Result = Match_Success;
5884
5885 // Order match statuses from least to most specific and keep the most
5886 // specific one:
5887 // Match_MnemonicFail < Match_InvalidOperand < Match_MissingFeature
5888 auto atLeastAsSpecific = [](unsigned New, unsigned Cur) {
5889 auto rank = [](unsigned M) {
5890 return M == Match_MnemonicFail ? 1
5891 : M == Match_InvalidOperand ? 2
5892 : M == Match_MissingFeature ? 3
5893 : 0; // Match_Success sentinel
5894 };
5895 return rank(New) >= rank(Cur);
5896 };
5897
5898 for (auto Variant : getMatchedVariants()) {
5899 uint64_t EI;
5900 auto R =
5901 MatchInstructionImpl(Operands, Inst, EI, MatchingInlineAsm, Variant);
5902 if (R == Match_Success || atLeastAsSpecific(R, Result)) {
5903 Result = R;
5904 ErrorInfo = EI;
5905 }
5906 if (R == Match_Success)
5907 break;
5908 }
5909
5910 if (Result == Match_Success) {
5911 if (!validateInstruction(Inst, IDLoc, Operands)) {
5912 return true;
5913 }
5914 emitTargetDirective();
5915 Out.emitInstruction(Inst, getSTI());
5916 // Record for kernel prologue checking.
5917 OpcodeStream.push_back(Inst.getOpcode());
5918 return false;
5919 }
5920
5921 StringRef Mnemo = ((AMDGPUOperand &)*Operands[0]).getToken();
5922 if (checkUnsupportedInstruction(Mnemo, IDLoc)) {
5923 return true;
5924 }
5925
5926 switch (Result) {
5927 default:
5928 break;
5929 case Match_MissingFeature:
5930 // It has been verified that the specified instruction
5931 // mnemonic is valid. A match was found but it requires
5932 // features which are not supported on this GPU.
5933 return Error(IDLoc, "operands are not valid for this GPU or mode");
5934
5935 case Match_InvalidOperand: {
5936 SMLoc ErrorLoc = IDLoc;
5937 if (ErrorInfo != ~0ULL) {
5938 if (ErrorInfo >= Operands.size()) {
5939 return Error(IDLoc, "too few operands for instruction");
5940 }
5941 AMDGPUOperand &ErrorOp = (AMDGPUOperand &)*Operands[ErrorInfo];
5942 ErrorLoc = ErrorOp.getStartLoc();
5943 if (ErrorLoc == SMLoc())
5944 ErrorLoc = IDLoc;
5945
5946 if (isInvalidVOPDY(Operands, ErrorInfo))
5947 return Error(ErrorLoc, "invalid VOPDY instruction");
5948 }
5949 return Error(ErrorLoc, "invalid operand for instruction");
5950 }
5951
5952 case Match_MnemonicFail:
5953 llvm_unreachable("Invalid instructions should have been handled already");
5954 }
5955 llvm_unreachable("Implement any new match types added!");
5956}
5957
5958bool AMDGPUAsmParser::ParseAsAbsoluteExpression(uint32_t &Ret) {
5959 int64_t Tmp = -1;
5960 if (!isToken(AsmToken::Integer) && !isToken(AsmToken::Identifier)) {
5961 return true;
5962 }
5963 if (getParser().parseAbsoluteExpression(Tmp)) {
5964 return true;
5965 }
5966 Ret = static_cast<uint32_t>(Tmp);
5967 return false;
5968}
5969
5970bool AMDGPUAsmParser::ParseDirectiveAMDGCNTarget() {
5971 if (!getSTI().getTargetTriple().isAMDGCN())
5972 return TokError("directive only supported for amdgcn architecture");
5973
5974 std::string TargetIDDirective;
5975 SMLoc TargetStart = getTok().getLoc();
5976 if (getParser().parseEscapedString(TargetIDDirective))
5977 return true;
5978
5979 std::optional<AMDGPU::TargetID> MaybeParsed =
5980 AMDGPU::TargetID::parseTargetIDString(TargetIDDirective);
5981 if (!MaybeParsed)
5982 return getParser().Error(TargetStart,
5983 "malformed target id '" + TargetIDDirective + "'");
5984
5985 const AMDGPU::TargetID &ParsedTargetID = *MaybeParsed;
5986 const Triple &TT = getSTI().getTargetTriple();
5987
5988 // The processor named in the target id must be covered by the triple's
5989 // subarch.
5990 if (!AMDGPU::isCPUValidForSubArch(TT.getSubArch(),
5991 ParsedTargetID.getGPUKind())) {
5992 return getParser().Error(
5993 TargetStart, "target id '" + TargetIDDirective +
5994 "' specifies a processor that is not valid for "
5995 "subarch '" +
5996 TT.getArchName() + "'");
5997 }
5998
5999 const std::optional<AMDGPU::TargetID> &CurrentTargetID =
6000 getTargetStreamer().getTargetID();
6001
6002 Triple DirectiveTriple(ParsedTargetID.getTargetTripleString());
6003 const Triple &STITriple = getSTI().getTargetTriple();
6004 if (!DirectiveTriple.isCompatibleWith(STITriple)) {
6005 return getParser().Error(
6006 TargetStart, ".amdgcn_target " + Twine(ParsedTargetID.toString()) +
6007 " is incompatible with " +
6008 Twine(CurrentTargetID->toString()));
6009 }
6010
6011 // Error if the ISA version doesn't match
6012 StringRef DirectiveProcessor =
6013 AMDGPU::getArchNameAMDGCN(ParsedTargetID.getGPUKind());
6014 AMDGPU::IsaVersion DirectiveISA = AMDGPU::getIsaVersion(DirectiveProcessor);
6015 if (DirectiveISA != ISA) {
6016 return getParser().Error(TargetStart,
6017 ".amdgcn_target directive processor " +
6018 Twine(DirectiveProcessor) +
6019 " does not match the specified processor " +
6020 Twine(getSTI().getCPU()));
6021 }
6022
6023 // Warn if sramecc or xnack mismatch. These do not change the encoding.
6025 ParsedTargetID.getXnackSetting(),
6026 CurrentTargetID->getXnackSetting())) {
6027 Warning(TargetStart,
6028 ".amdgcn_target directive has conflicting xnack settings");
6029 }
6031 ParsedTargetID.getSramEccSetting(),
6032 CurrentTargetID->getSramEccSetting())) {
6033 Warning(TargetStart,
6034 ".amdgcn_target directive has conflicting sramecc settings");
6035 }
6036
6037 // Update the target streamer's TargetID with settings from the directive.
6038 // We don't update the MCSubtargetInfo because we've already validated
6039 // that the directive matches the command-line CPU.
6040 getTargetStreamer().getTargetID()->setXnackSetting(
6041 ParsedTargetID.getXnackSetting());
6042 getTargetStreamer().getTargetID()->setSramEccSetting(
6043 ParsedTargetID.getSramEccSetting());
6044
6045 return false;
6046}
6047
6048bool AMDGPUAsmParser::OutOfRangeError(SMRange Range) {
6049 return Error(Range.Start, "value out of range", Range);
6050}
6051
6052bool AMDGPUAsmParser::calculateGPRBlocks(
6053 const FeatureBitset &Features, const MCExpr *VCCUsed,
6054 const MCExpr *FlatScrUsed, bool XNACKUsed,
6055 std::optional<bool> EnableWavefrontSize32, const MCExpr *NextFreeVGPR,
6056 SMRange VGPRRange, const MCExpr *NextFreeSGPR, SMRange SGPRRange,
6057 const MCExpr *&VGPRBlocks, const MCExpr *&SGPRBlocks) {
6058 // TODO(scott.linder): These calculations are duplicated from
6059 // AMDGPUAsmPrinter::getSIProgramInfo and could be unified.
6060 MCContext &Ctx = getContext();
6061
6062 const MCExpr *NumSGPRs = NextFreeSGPR;
6063 int64_t EvaluatedSGPRs;
6064
6065 if (ISA.Major >= 10)
6067 else {
6068 unsigned MaxAddressableNumSGPRs = AMDGPU::getAddressableNumSGPRs(Gfx);
6069
6070 if (NumSGPRs->evaluateAsAbsolute(EvaluatedSGPRs) && ISA.Major >= 8 &&
6071 !Features.test(FeatureSGPRInitBug) &&
6072 static_cast<uint64_t>(EvaluatedSGPRs) > MaxAddressableNumSGPRs)
6073 return OutOfRangeError(SGPRRange);
6074
6075 const MCExpr *ExtraSGPRs =
6076 AMDGPUMCExpr::createExtraSGPRs(VCCUsed, FlatScrUsed, XNACKUsed, Ctx);
6077 NumSGPRs = MCBinaryExpr::createAdd(NumSGPRs, ExtraSGPRs, Ctx);
6078
6079 if (NumSGPRs->evaluateAsAbsolute(EvaluatedSGPRs) &&
6080 (ISA.Major <= 7 || Features.test(FeatureSGPRInitBug)) &&
6081 static_cast<uint64_t>(EvaluatedSGPRs) > MaxAddressableNumSGPRs)
6082 return OutOfRangeError(SGPRRange);
6083
6084 if (Features.test(FeatureSGPRInitBug))
6085 NumSGPRs =
6087 }
6088
6089 // The MCExpr equivalent of getNumSGPRBlocks/getNumVGPRBlocks:
6090 // (alignTo(max(1u, NumGPR), GPREncodingGranule) / GPREncodingGranule) - 1
6091 auto GetNumGPRBlocks = [&Ctx](const MCExpr *NumGPR,
6092 unsigned Granule) -> const MCExpr * {
6093 const MCExpr *OneConst = MCConstantExpr::create(1ul, Ctx);
6094 const MCExpr *GranuleConst = MCConstantExpr::create(Granule, Ctx);
6095 const MCExpr *MaxNumGPR = AMDGPUMCExpr::createMax({NumGPR, OneConst}, Ctx);
6096 const MCExpr *AlignToGPR =
6097 AMDGPUMCExpr::createAlignTo(MaxNumGPR, GranuleConst, Ctx);
6098 const MCExpr *DivGPR =
6099 MCBinaryExpr::createDiv(AlignToGPR, GranuleConst, Ctx);
6100 const MCExpr *SubGPR = MCBinaryExpr::createSub(DivGPR, OneConst, Ctx);
6101 return SubGPR;
6102 };
6103
6104 VGPRBlocks = GetNumGPRBlocks(
6105 NextFreeVGPR,
6106 IsaInfo::getVGPREncodingGranule(getSTI(), EnableWavefrontSize32));
6107 SGPRBlocks =
6108 GetNumGPRBlocks(NumSGPRs, IsaInfo::getSGPREncodingGranule(getSTI()));
6109
6110 return false;
6111}
6112
6113bool AMDGPUAsmParser::ParseDirectiveAMDHSAKernel() {
6114 if (!getSTI().getTargetTriple().isAMDGCN())
6115 return TokError("directive only supported for amdgcn architecture");
6116
6117 if (!isHsaAbi(getSTI()))
6118 return TokError("directive only supported for amdhsa OS");
6119
6120 StringRef KernelName;
6121 if (getParser().parseIdentifier(KernelName))
6122 return true;
6123
6124 // Remember the kernel name so its prologue can be checked at end of file.
6125 // The matching label may have been parsed already or may follow later.
6126 AMDHSAKernelSymbols.insert(getContext().getOrCreateSymbol(KernelName));
6127
6128 AMDGPU::MCKernelDescriptor KD =
6130 &getSTI(), getContext());
6131
6132 StringSet<> Seen;
6133
6134 const MCExpr *ZeroExpr = MCConstantExpr::create(0, getContext());
6135 const MCExpr *OneExpr = MCConstantExpr::create(1, getContext());
6136
6137 SMRange VGPRRange;
6138 const MCExpr *NextFreeVGPR = ZeroExpr;
6139 const MCExpr *AccumOffset = MCConstantExpr::create(0, getContext());
6140 const MCExpr *NamedBarCnt = ZeroExpr;
6141 uint64_t SharedVGPRCount = 0;
6142 uint64_t PreloadLength = 0;
6143 uint64_t PreloadOffset = 0;
6144 SMRange SGPRRange;
6145 const MCExpr *NextFreeSGPR = ZeroExpr;
6146
6147 // Count the number of user SGPRs implied from the enabled feature bits.
6148 unsigned ImpliedUserSGPRCount = 0;
6149
6150 // Track if the asm explicitly contains the directive for the user SGPR
6151 // count.
6152 std::optional<unsigned> ExplicitUserSGPRCount;
6153 const MCExpr *ReserveVCC = OneExpr;
6154 const MCExpr *ReserveFlatScr = OneExpr;
6155 std::optional<bool> EnableWavefrontSize32;
6156
6157 while (true) {
6158 while (trySkipToken(AsmToken::EndOfStatement))
6159 ;
6160
6161 StringRef ID;
6162 SMRange IDRange = getTok().getLocRange();
6163 if (!parseId(ID, "expected .amdhsa_ directive or .end_amdhsa_kernel"))
6164 return true;
6165
6166 if (ID == ".end_amdhsa_kernel")
6167 break;
6168
6169 if (!Seen.insert(ID).second)
6170 return TokError(".amdhsa_ directives cannot be repeated");
6171
6172 SMLoc ValStart = getLoc();
6173 const MCExpr *ExprVal;
6174 if (getParser().parseExpression(ExprVal))
6175 return true;
6176 SMLoc ValEnd = getLoc();
6177 SMRange ValRange = SMRange(ValStart, ValEnd);
6178
6179 int64_t IVal = 0;
6180 uint64_t Val = IVal;
6181 bool EvaluatableExpr;
6182 if ((EvaluatableExpr = ExprVal->evaluateAsAbsolute(IVal))) {
6183 if (IVal < 0)
6184 return OutOfRangeError(ValRange);
6185 Val = IVal;
6186 }
6187
6188#define PARSE_BITS_ENTRY(FIELD, ENTRY, VALUE, RANGE) \
6189 if (!isUInt<ENTRY##_WIDTH>(Val)) \
6190 return OutOfRangeError(RANGE); \
6191 AMDGPU::MCKernelDescriptor::bits_set(FIELD, VALUE, ENTRY##_SHIFT, ENTRY, \
6192 getContext());
6193
6194// Some fields use the parsed value immediately which requires the expression to
6195// be solvable.
6196#define EXPR_RESOLVE_OR_ERROR(RESOLVED) \
6197 if (!(RESOLVED)) \
6198 return Error(IDRange.Start, "directive should have resolvable expression", \
6199 IDRange);
6200
6201 if (ID == ".amdhsa_group_segment_fixed_size") {
6203 CHAR_BIT>(Val))
6204 return OutOfRangeError(ValRange);
6205 KD.group_segment_fixed_size = ExprVal;
6206 } else if (ID == ".amdhsa_private_segment_fixed_size") {
6208 CHAR_BIT>(Val))
6209 return OutOfRangeError(ValRange);
6210 KD.private_segment_fixed_size = ExprVal;
6211 } else if (ID == ".amdhsa_kernarg_size") {
6212 if (!isUInt<sizeof(kernel_descriptor_t::kernarg_size) * CHAR_BIT>(Val))
6213 return OutOfRangeError(ValRange);
6214 KD.kernarg_size = ExprVal;
6215 } else if (ID == ".amdhsa_user_sgpr_count") {
6216 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6217 ExplicitUserSGPRCount = Val;
6218 } else if (ID == ".amdhsa_user_sgpr_private_segment_buffer") {
6219 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6221 return Error(IDRange.Start,
6222 "directive is not supported with architected flat scratch",
6223 IDRange);
6225 KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER,
6226 ExprVal, ValRange);
6227 if (Val)
6228 ImpliedUserSGPRCount += 4;
6229 } else if (ID == ".amdhsa_user_sgpr_kernarg_preload_length") {
6230 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6231 if (!hasKernargPreload())
6232 return Error(IDRange.Start, "directive requires gfx90a+", IDRange);
6233
6234 if (Val > getMaxNumUserSGPRs())
6235 return OutOfRangeError(ValRange);
6236 PARSE_BITS_ENTRY(KD.kernarg_preload, KERNARG_PRELOAD_SPEC_LENGTH, ExprVal,
6237 ValRange);
6238 if (Val) {
6239 ImpliedUserSGPRCount += Val;
6240 PreloadLength = Val;
6241 }
6242 } else if (ID == ".amdhsa_user_sgpr_kernarg_preload_offset") {
6243 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6244 if (!hasKernargPreload())
6245 return Error(IDRange.Start, "directive requires gfx90a+", IDRange);
6246
6247 if (Val >= 1024)
6248 return OutOfRangeError(ValRange);
6249 PARSE_BITS_ENTRY(KD.kernarg_preload, KERNARG_PRELOAD_SPEC_OFFSET, ExprVal,
6250 ValRange);
6251 if (Val)
6252 PreloadOffset = Val;
6253 } else if (ID == ".amdhsa_user_sgpr_dispatch_ptr") {
6254 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6256 KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR, ExprVal,
6257 ValRange);
6258 if (Val)
6259 ImpliedUserSGPRCount += 2;
6260 } else if (ID == ".amdhsa_user_sgpr_queue_ptr") {
6261 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6263 KERNEL_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR, ExprVal,
6264 ValRange);
6265 if (Val)
6266 ImpliedUserSGPRCount += 2;
6267 } else if (ID == ".amdhsa_user_sgpr_kernarg_segment_ptr") {
6268 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6270 KERNEL_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR,
6271 ExprVal, ValRange);
6272 if (Val)
6273 ImpliedUserSGPRCount += 2;
6274 } else if (ID == ".amdhsa_user_sgpr_dispatch_id") {
6275 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6277 KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID, ExprVal,
6278 ValRange);
6279 if (Val)
6280 ImpliedUserSGPRCount += 2;
6281 } else if (ID == ".amdhsa_user_sgpr_flat_scratch_init") {
6283 return Error(IDRange.Start,
6284 "directive is not supported with architected flat scratch",
6285 IDRange);
6286 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6288 KERNEL_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT,
6289 ExprVal, ValRange);
6290 if (Val)
6291 ImpliedUserSGPRCount += 2;
6292 } else if (ID == ".amdhsa_user_sgpr_private_segment_size") {
6293 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6295 KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_SIZE,
6296 ExprVal, ValRange);
6297 if (Val)
6298 ImpliedUserSGPRCount += 1;
6299 } else if (ID == ".amdhsa_wavefront_size32") {
6300 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6301 if (ISA.Major < 10)
6302 return Error(IDRange.Start, "directive requires gfx10+", IDRange);
6303 EnableWavefrontSize32 = Val;
6305 KERNEL_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32, ExprVal,
6306 ValRange);
6307 } else if (ID == ".amdhsa_uses_dynamic_stack") {
6309 KERNEL_CODE_PROPERTY_USES_DYNAMIC_STACK, ExprVal,
6310 ValRange);
6311 } else if (ID == ".amdhsa_system_sgpr_private_segment_wavefront_offset") {
6313 return Error(IDRange.Start,
6314 "directive is not supported with architected flat scratch",
6315 IDRange);
6317 COMPUTE_PGM_RSRC2_ENABLE_PRIVATE_SEGMENT, ExprVal,
6318 ValRange);
6319 } else if (ID == ".amdhsa_enable_private_segment") {
6321 return Error(
6322 IDRange.Start,
6323 "directive is not supported without architected flat scratch",
6324 IDRange);
6326 COMPUTE_PGM_RSRC2_ENABLE_PRIVATE_SEGMENT, ExprVal,
6327 ValRange);
6328 } else if (ID == ".amdhsa_system_sgpr_workgroup_id_x") {
6330 COMPUTE_PGM_RSRC2_ENABLE_SGPR_WORKGROUP_ID_X, ExprVal,
6331 ValRange);
6332 } else if (ID == ".amdhsa_system_sgpr_workgroup_id_y") {
6334 COMPUTE_PGM_RSRC2_ENABLE_SGPR_WORKGROUP_ID_Y, ExprVal,
6335 ValRange);
6336 } else if (ID == ".amdhsa_system_sgpr_workgroup_id_z") {
6338 COMPUTE_PGM_RSRC2_ENABLE_SGPR_WORKGROUP_ID_Z, ExprVal,
6339 ValRange);
6340 } else if (ID == ".amdhsa_system_sgpr_workgroup_info") {
6342 COMPUTE_PGM_RSRC2_ENABLE_SGPR_WORKGROUP_INFO, ExprVal,
6343 ValRange);
6344 } else if (ID == ".amdhsa_system_vgpr_workitem_id") {
6346 COMPUTE_PGM_RSRC2_ENABLE_VGPR_WORKITEM_ID, ExprVal,
6347 ValRange);
6348 } else if (ID == ".amdhsa_next_free_vgpr") {
6349 VGPRRange = ValRange;
6350 NextFreeVGPR = ExprVal;
6351 } else if (ID == ".amdhsa_next_free_sgpr") {
6352 SGPRRange = ValRange;
6353 NextFreeSGPR = ExprVal;
6354 } else if (ID == ".amdhsa_accum_offset") {
6355 if (!isGFX90A())
6356 return Error(IDRange.Start, "directive requires gfx90a+", IDRange);
6357 AccumOffset = ExprVal;
6358 } else if (ID == ".amdhsa_named_barrier_count") {
6359 if (!isGFX1250Plus())
6360 return Error(IDRange.Start, "directive requires gfx1250+", IDRange);
6361 NamedBarCnt = ExprVal;
6362 } else if (ID == ".amdhsa_reserve_vcc") {
6363 if (EvaluatableExpr && !isUInt<1>(Val))
6364 return OutOfRangeError(ValRange);
6365 ReserveVCC = ExprVal;
6366 } else if (ID == ".amdhsa_reserve_flat_scratch") {
6367 if (ISA.Major < 7)
6368 return Error(IDRange.Start, "directive requires gfx7+", IDRange);
6370 return Error(IDRange.Start,
6371 "directive is not supported with architected flat scratch",
6372 IDRange);
6373 if (EvaluatableExpr && !isUInt<1>(Val))
6374 return OutOfRangeError(ValRange);
6375 ReserveFlatScr = ExprVal;
6376 } else if (ID == ".amdhsa_reserve_xnack_mask") {
6377 if (ISA.Major < 8)
6378 return Error(IDRange.Start, "directive requires gfx8+", IDRange);
6379 if (!isUInt<1>(Val))
6380 return OutOfRangeError(ValRange);
6381 bool XnackOn = getTargetStreamer().getTargetID()->isXnackOnOrAny();
6382 if (Val != XnackOn) {
6383 return getParser().Error(
6384 IDRange.Start,
6385 ".amdhsa_reserve_xnack_mask does not match target id", IDRange);
6386 }
6387 } else if (ID == ".amdhsa_float_round_mode_32") {
6389 COMPUTE_PGM_RSRC1_FLOAT_ROUND_MODE_32, ExprVal,
6390 ValRange);
6391 } else if (ID == ".amdhsa_float_round_mode_16_64") {
6393 COMPUTE_PGM_RSRC1_FLOAT_ROUND_MODE_16_64, ExprVal,
6394 ValRange);
6395 } else if (ID == ".amdhsa_float_denorm_mode_32") {
6397 COMPUTE_PGM_RSRC1_FLOAT_DENORM_MODE_32, ExprVal,
6398 ValRange);
6399 } else if (ID == ".amdhsa_float_denorm_mode_16_64") {
6401 COMPUTE_PGM_RSRC1_FLOAT_DENORM_MODE_16_64, ExprVal,
6402 ValRange);
6403 } else if (ID == ".amdhsa_dx10_clamp") {
6404 if (!getSTI().hasFeature(AMDGPU::FeatureDX10ClampAndIEEEMode))
6405 return Error(IDRange.Start, "directive unsupported on gfx1170+",
6406 IDRange);
6408 COMPUTE_PGM_RSRC1_GFX6_GFX11_ENABLE_DX10_CLAMP, ExprVal,
6409 ValRange);
6410 } else if (ID == ".amdhsa_ieee_mode") {
6411 if (!getSTI().hasFeature(AMDGPU::FeatureDX10ClampAndIEEEMode))
6412 return Error(IDRange.Start, "directive unsupported on gfx1170+",
6413 IDRange);
6415 COMPUTE_PGM_RSRC1_GFX6_GFX11_ENABLE_IEEE_MODE, ExprVal,
6416 ValRange);
6417 } else if (ID == ".amdhsa_fp16_overflow") {
6418 if (ISA.Major < 9)
6419 return Error(IDRange.Start, "directive requires gfx9+", IDRange);
6421 COMPUTE_PGM_RSRC1_GFX9_PLUS_FP16_OVFL, ExprVal,
6422 ValRange);
6423 } else if (ID == ".amdhsa_tg_split") {
6424 if (!isGFX90A())
6425 return Error(IDRange.Start, "directive requires gfx90a+", IDRange);
6426 PARSE_BITS_ENTRY(KD.compute_pgm_rsrc3, COMPUTE_PGM_RSRC3_GFX90A_TG_SPLIT,
6427 ExprVal, ValRange);
6428 } else if (ID == ".amdhsa_workgroup_processor_mode") {
6429 if (!supportsWGP(getSTI()))
6430 return Error(IDRange.Start,
6431 "directive unsupported on " + getSTI().getCPU(), IDRange);
6433 COMPUTE_PGM_RSRC1_GFX10_PLUS_WGP_MODE, ExprVal,
6434 ValRange);
6435 } else if (ID == ".amdhsa_memory_ordered") {
6436 if (ISA.Major < 10)
6437 return Error(IDRange.Start, "directive requires gfx10+", IDRange);
6439 COMPUTE_PGM_RSRC1_GFX10_PLUS_MEM_ORDERED, ExprVal,
6440 ValRange);
6441 } else if (ID == ".amdhsa_forward_progress") {
6442 if (ISA.Major < 10)
6443 return Error(IDRange.Start, "directive requires gfx10+", IDRange);
6445 COMPUTE_PGM_RSRC1_GFX10_PLUS_FWD_PROGRESS, ExprVal,
6446 ValRange);
6447 } else if (ID == ".amdhsa_shared_vgpr_count") {
6448 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6449 if (ISA.Major < 10 || ISA.Major >= 12)
6450 return Error(IDRange.Start, "directive requires gfx10 or gfx11",
6451 IDRange);
6452 SharedVGPRCount = Val;
6454 COMPUTE_PGM_RSRC3_GFX10_GFX11_SHARED_VGPR_COUNT, ExprVal,
6455 ValRange);
6456 } else if (ID == ".amdhsa_inst_pref_size") {
6457 if (ISA.Major < 11)
6458 return Error(IDRange.Start, "directive requires gfx11+", IDRange);
6459 if (ISA.Major == 11) {
6461 COMPUTE_PGM_RSRC3_GFX11_INST_PREF_SIZE, ExprVal,
6462 ValRange);
6463 } else {
6465 COMPUTE_PGM_RSRC3_GFX12_PLUS_INST_PREF_SIZE, ExprVal,
6466 ValRange);
6467 }
6468 } else if (ID == ".amdhsa_exception_fp_ieee_invalid_op") {
6471 COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_INVALID_OPERATION,
6472 ExprVal, ValRange);
6473 } else if (ID == ".amdhsa_exception_fp_denorm_src") {
6475 COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_FP_DENORMAL_SOURCE,
6476 ExprVal, ValRange);
6477 } else if (ID == ".amdhsa_exception_fp_ieee_div_zero") {
6480 COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_DIVISION_BY_ZERO,
6481 ExprVal, ValRange);
6482 } else if (ID == ".amdhsa_exception_fp_ieee_overflow") {
6484 COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_OVERFLOW,
6485 ExprVal, ValRange);
6486 } else if (ID == ".amdhsa_exception_fp_ieee_underflow") {
6488 COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_UNDERFLOW,
6489 ExprVal, ValRange);
6490 } else if (ID == ".amdhsa_exception_fp_ieee_inexact") {
6492 COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_INEXACT,
6493 ExprVal, ValRange);
6494 } else if (ID == ".amdhsa_exception_int_div_zero") {
6496 COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_INT_DIVIDE_BY_ZERO,
6497 ExprVal, ValRange);
6498 } else if (ID == ".amdhsa_round_robin_scheduling") {
6499 if (ISA.Major < 12)
6500 return Error(IDRange.Start, "directive requires gfx12+", IDRange);
6502 COMPUTE_PGM_RSRC1_GFX12_PLUS_ENABLE_WG_RR_EN, ExprVal,
6503 ValRange);
6504 } else {
6505 return Error(IDRange.Start, "unknown .amdhsa_kernel directive", IDRange);
6506 }
6507
6508#undef PARSE_BITS_ENTRY
6509 }
6510
6511 if (!Seen.contains(".amdhsa_next_free_vgpr"))
6512 return TokError(".amdhsa_next_free_vgpr directive is required");
6513
6514 if (!Seen.contains(".amdhsa_next_free_sgpr"))
6515 return TokError(".amdhsa_next_free_sgpr directive is required");
6516
6517 unsigned UserSGPRCount = ExplicitUserSGPRCount.value_or(ImpliedUserSGPRCount);
6518 if (UserSGPRCount > getMaxNumUserSGPRs())
6519 return TokError("too many user SGPRs enabled, found " +
6520 Twine(UserSGPRCount) + ", but only " +
6521 Twine(getMaxNumUserSGPRs()) + " are supported.");
6522
6523 // Consider the case where the total number of UserSGPRs with trailing
6524 // allocated preload SGPRs, is greater than the number of explicitly
6525 // referenced SGPRs.
6526 if (PreloadLength) {
6527 MCContext &Ctx = getContext();
6528 NextFreeSGPR = AMDGPUMCExpr::createMax(
6529 {NextFreeSGPR, MCConstantExpr::create(UserSGPRCount, Ctx)}, Ctx);
6530 }
6531
6532 const MCExpr *VGPRBlocks;
6533 const MCExpr *SGPRBlocks;
6534 if (calculateGPRBlocks(getFeatureBits(), ReserveVCC, ReserveFlatScr,
6535 getTargetStreamer().getTargetID()->isXnackOnOrAny(),
6536 EnableWavefrontSize32, NextFreeVGPR, VGPRRange,
6537 NextFreeSGPR, SGPRRange, VGPRBlocks, SGPRBlocks))
6538 return true;
6539
6540 int64_t EvaluatedVGPRBlocks;
6541 bool VGPRBlocksEvaluatable =
6542 VGPRBlocks->evaluateAsAbsolute(EvaluatedVGPRBlocks);
6543 if (VGPRBlocksEvaluatable &&
6545 static_cast<uint64_t>(EvaluatedVGPRBlocks))) {
6546 return OutOfRangeError(VGPRRange);
6547 }
6549 KD.compute_pgm_rsrc1, VGPRBlocks,
6550 COMPUTE_PGM_RSRC1_GRANULATED_WORKITEM_VGPR_COUNT_SHIFT,
6551 COMPUTE_PGM_RSRC1_GRANULATED_WORKITEM_VGPR_COUNT, getContext());
6552
6553 int64_t EvaluatedSGPRBlocks;
6554 if (SGPRBlocks->evaluateAsAbsolute(EvaluatedSGPRBlocks) &&
6556 static_cast<uint64_t>(EvaluatedSGPRBlocks)))
6557 return OutOfRangeError(SGPRRange);
6559 KD.compute_pgm_rsrc1, SGPRBlocks,
6560 COMPUTE_PGM_RSRC1_GRANULATED_WAVEFRONT_SGPR_COUNT_SHIFT,
6561 COMPUTE_PGM_RSRC1_GRANULATED_WAVEFRONT_SGPR_COUNT, getContext());
6562
6563 if (ExplicitUserSGPRCount && ImpliedUserSGPRCount > *ExplicitUserSGPRCount)
6564 return TokError("amdgpu_user_sgpr_count smaller than implied by "
6565 "enabled user SGPRs");
6566
6567 if (isGFX1250Plus()) {
6570 MCConstantExpr::create(UserSGPRCount, getContext()),
6571 COMPUTE_PGM_RSRC2_GFX125_USER_SGPR_COUNT_SHIFT,
6572 COMPUTE_PGM_RSRC2_GFX125_USER_SGPR_COUNT, getContext());
6573 } else {
6576 MCConstantExpr::create(UserSGPRCount, getContext()),
6577 COMPUTE_PGM_RSRC2_GFX6_GFX120_USER_SGPR_COUNT_SHIFT,
6578 COMPUTE_PGM_RSRC2_GFX6_GFX120_USER_SGPR_COUNT, getContext());
6579 }
6580
6581 int64_t IVal = 0;
6582 if (!KD.kernarg_size->evaluateAsAbsolute(IVal))
6583 return TokError("Kernarg size should be resolvable");
6584 uint64_t kernarg_size = IVal;
6585 if (PreloadLength && kernarg_size &&
6586 (PreloadLength * 4 + PreloadOffset * 4 > kernarg_size))
6587 return TokError("Kernarg preload length + offset is larger than the "
6588 "kernarg segment size");
6589
6590 if (isGFX90A()) {
6591 if (!Seen.contains(".amdhsa_accum_offset"))
6592 return TokError(".amdhsa_accum_offset directive is required");
6593 int64_t EvaluatedAccum;
6594 bool AccumEvaluatable = AccumOffset->evaluateAsAbsolute(EvaluatedAccum);
6595 uint64_t UEvaluatedAccum = EvaluatedAccum;
6596 if (AccumEvaluatable &&
6597 (UEvaluatedAccum < 4 || UEvaluatedAccum > 256 || (UEvaluatedAccum & 3)))
6598 return TokError("accum_offset should be in range [4..256] in "
6599 "increments of 4");
6600
6601 int64_t EvaluatedNumVGPR;
6602 if (NextFreeVGPR->evaluateAsAbsolute(EvaluatedNumVGPR) &&
6603 AccumEvaluatable &&
6604 UEvaluatedAccum >
6605 alignTo(std::max((uint64_t)1, (uint64_t)EvaluatedNumVGPR), 4))
6606 return TokError("accum_offset exceeds total VGPR allocation");
6607 const MCExpr *AdjustedAccum = MCBinaryExpr::createSub(
6609 AccumOffset, MCConstantExpr::create(4, getContext()), getContext()),
6612 COMPUTE_PGM_RSRC3_GFX90A_ACCUM_OFFSET_SHIFT,
6613 COMPUTE_PGM_RSRC3_GFX90A_ACCUM_OFFSET,
6614 getContext());
6615 }
6616
6617 if (isGFX1250Plus())
6619 COMPUTE_PGM_RSRC3_GFX125_NAMED_BAR_CNT_SHIFT,
6620 COMPUTE_PGM_RSRC3_GFX125_NAMED_BAR_CNT,
6621 getContext());
6622
6623 if (ISA.Major >= 10 && ISA.Major < 12) {
6624 // SharedVGPRCount < 16 checked by PARSE_ENTRY_BITS
6625 if (SharedVGPRCount && EnableWavefrontSize32 && *EnableWavefrontSize32) {
6626 return TokError("shared_vgpr_count directive not valid on "
6627 "wavefront size 32");
6628 }
6629
6630 if (VGPRBlocksEvaluatable &&
6631 (SharedVGPRCount * 2 + static_cast<uint64_t>(EvaluatedVGPRBlocks) >
6632 63)) {
6633 return TokError("shared_vgpr_count*2 + "
6634 "compute_pgm_rsrc1.GRANULATED_WORKITEM_VGPR_COUNT cannot "
6635 "exceed 63\n");
6636 }
6637 }
6638
6639 emitTargetDirective();
6640 getTargetStreamer().EmitAmdhsaKernelDescriptor(getSTI(), KernelName, KD,
6641 NextFreeVGPR, NextFreeSGPR,
6642 ReserveVCC, ReserveFlatScr);
6643 return false;
6644}
6645
6646bool AMDGPUAsmParser::ParseDirectiveAMDHSACodeObjectVersion() {
6647 uint32_t Version;
6648 if (ParseAsAbsoluteExpression(Version))
6649 return true;
6650
6651 getTargetStreamer().EmitDirectiveAMDHSACodeObjectVersion(Version);
6652 emitTargetDirective();
6653 return false;
6654}
6655
6656bool AMDGPUAsmParser::ParseAMDKernelCodeTValue(StringRef ID,
6657 AMDGPUMCKernelCodeT &C) {
6658 // max_scratch_backing_memory_byte_size is deprecated. Ignore it while parsing
6659 // assembly for backwards compatibility.
6660 if (ID == "max_scratch_backing_memory_byte_size") {
6661 Parser.eatToEndOfStatement();
6662 return false;
6663 }
6664
6665 SmallString<40> ErrStr;
6666 raw_svector_ostream Err(ErrStr);
6667 if (!C.ParseKernelCodeT(ID, getParser(), Err)) {
6668 return TokError(Err.str());
6669 }
6670 Lex();
6671
6672 if (ID == "enable_wavefront_size32") {
6673 if (C.code_properties & AMD_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32) {
6674 if (!isGFX10Plus())
6675 return TokError("enable_wavefront_size32=1 is only allowed on GFX10+");
6676 if (!isWave32())
6677 return TokError("enable_wavefront_size32=1 requires +WavefrontSize32");
6678 } else {
6679 if (!isWave64())
6680 return TokError("enable_wavefront_size32=0 requires +WavefrontSize64");
6681 }
6682 }
6683
6684 if (ID == "wavefront_size") {
6685 if (C.wavefront_size == 5) {
6686 if (!isGFX10Plus())
6687 return TokError("wavefront_size=5 is only allowed on GFX10+");
6688 if (!isWave32())
6689 return TokError("wavefront_size=5 requires +WavefrontSize32");
6690 } else if (C.wavefront_size == 6) {
6691 if (!isWave64())
6692 return TokError("wavefront_size=6 requires +WavefrontSize64");
6693 }
6694 }
6695
6696 return false;
6697}
6698
6699bool AMDGPUAsmParser::ParseDirectiveAMDKernelCodeT() {
6700 AMDGPUMCKernelCodeT KernelCode;
6701 KernelCode.initDefault(getSTI(), getContext());
6702
6703 while (true) {
6704 // Lex EndOfStatement. This is in a while loop, because lexing a comment
6705 // will set the current token to EndOfStatement.
6706 while (trySkipToken(AsmToken::EndOfStatement))
6707 ;
6708
6709 StringRef ID;
6710 if (!parseId(ID, "expected value identifier or .end_amd_kernel_code_t"))
6711 return true;
6712
6713 if (ID == ".end_amd_kernel_code_t")
6714 break;
6715
6716 if (ParseAMDKernelCodeTValue(ID, KernelCode))
6717 return true;
6718 }
6719
6720 KernelCode.validate(&getSTI(), getContext());
6721 getTargetStreamer().EmitAMDKernelCodeT(KernelCode);
6722
6723 return false;
6724}
6725
6726bool AMDGPUAsmParser::ParseDirectiveAMDGPUHsaKernel() {
6727 StringRef KernelName;
6728 if (!parseId(KernelName, "expected symbol name"))
6729 return true;
6730
6731 getTargetStreamer().EmitAMDGPUSymbolType(KernelName,
6733
6734 KernelScope.initialize(getContext());
6735 return false;
6736}
6737
6738bool AMDGPUAsmParser::ParseDirectiveISAVersion() {
6739 if (!getSTI().getTargetTriple().isAMDGCN()) {
6740 return Error(getLoc(),
6741 ".amd_amdgpu_isa directive is not available on non-amdgcn "
6742 "architectures");
6743 }
6744
6745 StringRef TargetIDDirective = getLexer().getTok().getStringContents();
6746
6747 std::optional<AMDGPU::TargetID> MaybeParsed =
6748 AMDGPU::TargetID::parseTargetIDString(TargetIDDirective);
6749 if (!MaybeParsed)
6750 return Error(getParser().getTok().getLoc(),
6751 "malformed target id '" + TargetIDDirective + "'");
6752
6753 const AMDGPU::TargetID &ParsedTargetID = *MaybeParsed;
6754 const Triple &TT = getSTI().getTargetTriple();
6755
6756 // The processor named in the target id must be covered by the triple's
6757 // subarch.
6758 if (!AMDGPU::isCPUValidForSubArch(TT.getSubArch(),
6759 ParsedTargetID.getGPUKind())) {
6760 return Error(getParser().getTok().getLoc(),
6761 "target id '" + TargetIDDirective +
6762 "' specifies a processor that is not valid for subarch '" +
6763 TT.getArchName() + "'");
6764 }
6765
6766 const std::optional<AMDGPU::TargetID> &CurrentTargetID =
6767 getTargetStreamer().getTargetID();
6768
6769 Triple DirectiveTriple(ParsedTargetID.getTargetTripleString());
6770 const Triple &STITriple = getSTI().getTargetTriple();
6771 if (!DirectiveTriple.isCompatibleWith(STITriple)) {
6772 return Error(getParser().getTok().getLoc(),
6773 ".amd_amdgpu_isa " + Twine(ParsedTargetID.toString()) +
6774 " is incompatible with " +
6775 Twine(CurrentTargetID->toString()));
6776 }
6777
6778 // Error if the ISA version doesn't match
6779 StringRef DirectiveProcessor =
6780 AMDGPU::getArchNameAMDGCN(ParsedTargetID.getGPUKind());
6781 AMDGPU::IsaVersion DirectiveISA = AMDGPU::getIsaVersion(DirectiveProcessor);
6782 if (DirectiveISA != ISA) {
6783 return Error(getParser().getTok().getLoc(),
6784 ".amd_amdgpu_isa directive processor " +
6785 Twine(DirectiveProcessor) +
6786 " does not match the specified processor " +
6787 Twine(getSTI().getCPU()));
6788 }
6789
6790 getTargetStreamer().EmitISAVersion();
6791 Lex();
6792
6793 return false;
6794}
6795
6796bool AMDGPUAsmParser::ParseDirectiveHSAMetadata() {
6797 assert(isHsaAbi(getSTI()));
6798
6799 std::string HSAMetadataString;
6800 if (ParseToEndDirective(HSAMD::V3::AssemblerDirectiveBegin,
6801 HSAMD::V3::AssemblerDirectiveEnd, HSAMetadataString))
6802 return true;
6803
6804 if (!getTargetStreamer().EmitHSAMetadataV3(HSAMetadataString))
6805 return Error(getLoc(), "invalid HSA metadata");
6806
6807 return false;
6808}
6809
6810/// Common code to parse out a block of text (typically YAML) between start and
6811/// end directives.
6812bool AMDGPUAsmParser::ParseToEndDirective(const char *AssemblerDirectiveBegin,
6813 const char *AssemblerDirectiveEnd,
6814 std::string &CollectString) {
6815
6816 raw_string_ostream CollectStream(CollectString);
6817
6818 getLexer().setSkipSpace(false);
6819
6820 bool FoundEnd = false;
6821 while (!isToken(AsmToken::Eof)) {
6822 while (isToken(AsmToken::Space)) {
6823 CollectStream << getTokenStr();
6824 Lex();
6825 }
6826
6827 if (trySkipId(AssemblerDirectiveEnd)) {
6828 FoundEnd = true;
6829 break;
6830 }
6831
6832 CollectStream << Parser.parseStringToEndOfStatement()
6833 << getContext().getAsmInfo().getSeparatorString();
6834
6835 Parser.eatToEndOfStatement();
6836 }
6837
6838 getLexer().setSkipSpace(true);
6839
6840 if (isToken(AsmToken::Eof) && !FoundEnd) {
6841 return TokError(Twine("expected directive ") +
6842 Twine(AssemblerDirectiveEnd) + Twine(" not found"));
6843 }
6844
6845 return false;
6846}
6847
6848/// Parse the assembler directive for new MsgPack-format PAL metadata.
6849bool AMDGPUAsmParser::ParseDirectivePALMetadataBegin() {
6850 std::string String;
6851 if (ParseToEndDirective(AMDGPU::PALMD::AssemblerDirectiveBegin,
6853 return true;
6854
6855 auto *PALMetadata = getTargetStreamer().getPALMetadata();
6856 if (!PALMetadata->setFromString(String))
6857 return Error(getLoc(), "invalid PAL metadata");
6858 return false;
6859}
6860
6861/// Parse the assembler directive for old linear-format PAL metadata.
6862bool AMDGPUAsmParser::ParseDirectivePALMetadata() {
6863 if (getSTI().getTargetTriple().getOS() != Triple::AMDPAL) {
6864 return Error(getLoc(), (Twine(PALMD::AssemblerDirective) +
6865 Twine(" directive is "
6866 "not available on non-amdpal OSes"))
6867 .str());
6868 }
6869
6870 auto *PALMetadata = getTargetStreamer().getPALMetadata();
6871 PALMetadata->setLegacy();
6872 for (;;) {
6873 uint32_t Key, Value;
6874 if (ParseAsAbsoluteExpression(Key)) {
6875 return TokError(Twine("invalid value in ") +
6877 }
6878 if (!trySkipToken(AsmToken::Comma)) {
6879 return TokError(Twine("expected an even number of values in ") +
6881 }
6882 if (ParseAsAbsoluteExpression(Value)) {
6883 return TokError(Twine("invalid value in ") +
6885 }
6886 PALMetadata->setRegister(Key, Value);
6887 if (!trySkipToken(AsmToken::Comma))
6888 break;
6889 }
6890 return false;
6891}
6892
6893/// ParseDirectiveAMDGPULDS
6894/// ::= .amdgpu_lds identifier ',' size_expression [',' align_expression]
6895bool AMDGPUAsmParser::ParseDirectiveAMDGPULDS() {
6896 if (getParser().checkForValidSection())
6897 return true;
6898
6899 StringRef Name;
6900 SMLoc NameLoc = getLoc();
6901 if (getParser().parseIdentifier(Name))
6902 return TokError("expected identifier in directive");
6903
6904 MCSymbol *Symbol = getContext().getOrCreateSymbol(Name);
6905 if (getParser().parseComma())
6906 return true;
6907
6908 unsigned LocalMemorySize = AMDGPU::IsaInfo::getLocalMemorySize(getSTI());
6909
6910 int64_t Size;
6911 SMLoc SizeLoc = getLoc();
6912 if (getParser().parseAbsoluteExpression(Size))
6913 return true;
6914 if (Size < 0)
6915 return Error(SizeLoc, "size must be non-negative");
6916 if (Size > LocalMemorySize)
6917 return Error(SizeLoc, "size is too large");
6918
6919 int64_t Alignment = 4;
6920 if (trySkipToken(AsmToken::Comma)) {
6921 SMLoc AlignLoc = getLoc();
6922 if (getParser().parseAbsoluteExpression(Alignment))
6923 return true;
6924 if (Alignment < 0 || !isPowerOf2_64(Alignment))
6925 return Error(AlignLoc, "alignment must be a power of two");
6926
6927 // Alignment larger than the size of LDS is possible in theory, as long
6928 // as the linker manages to place to symbol at address 0, but we do want
6929 // to make sure the alignment fits nicely into a 32-bit integer.
6930 if (Alignment >= 1u << 31)
6931 return Error(AlignLoc, "alignment is too large");
6932 }
6933
6934 if (parseEOL())
6935 return true;
6936
6937 Symbol->redefineIfPossible();
6938 if (!Symbol->isUndefined())
6939 return Error(NameLoc, "invalid symbol redefinition");
6940
6941 getTargetStreamer().emitAMDGPULDS(Symbol, Size, Align(Alignment));
6942 return false;
6943}
6944
6945bool AMDGPUAsmParser::ParseDirectiveAMDGPUInfo() {
6946 if (getParser().checkForValidSection())
6947 return true;
6948
6949 StringRef FuncName;
6950 if (getParser().parseIdentifier(FuncName))
6951 return TokError("expected symbol name after .amdgpu_info");
6952
6953 MCSymbol *FuncSym = getContext().getOrCreateSymbol(FuncName);
6954 AMDGPU::InfoSectionData ParsedInfoData;
6955 AMDGPU::FuncInfo FI;
6956 FI.Sym = FuncSym;
6957 bool HasScalarAttrs = false;
6958
6959 while (true) {
6960 while (trySkipToken(AsmToken::EndOfStatement))
6961 ;
6962
6963 StringRef ID;
6964 SMLoc IDLoc = getLoc();
6965 if (!parseId(ID, "expected directive or .end_amdgpu_info"))
6966 return true;
6967
6968 if (ID == ".end_amdgpu_info")
6969 break;
6970
6971 // Every per-entry directive shares the `.amdgpu_` namespace prefix; strip
6972 // it once and dispatch on the distinguishing suffix below. The unstripped
6973 // ID is preserved for diagnostics.
6974 StringRef Dir = ID;
6975 if (!Dir.consume_front(".amdgpu_"))
6976 return Error(IDLoc, "unknown .amdgpu_info directive '" + ID + "'");
6977
6978 if (Dir == "flags") {
6979 int64_t Val;
6980 if (getParser().parseAbsoluteExpression(Val))
6981 return true;
6982 auto Flags = static_cast<AMDGPU::FuncInfoFlags>(Val);
6983 FI.UsesVCC = !!(Flags & AMDGPU::FuncInfoFlags::FUNC_USES_VCC);
6984 FI.UsesFlatScratch =
6985 !!(Flags & AMDGPU::FuncInfoFlags::FUNC_USES_FLAT_SCRATCH);
6986 FI.HasDynStack = !!(Flags & AMDGPU::FuncInfoFlags::FUNC_HAS_DYN_STACK);
6987 HasScalarAttrs = true;
6988 } else if (Dir == "num_sgpr") {
6989 int64_t Val;
6990 if (getParser().parseAbsoluteExpression(Val))
6991 return true;
6992 FI.NumSGPR = static_cast<uint32_t>(Val);
6993 HasScalarAttrs = true;
6994 } else if (Dir == "num_vgpr") {
6995 int64_t Val;
6996 if (getParser().parseAbsoluteExpression(Val))
6997 return true;
6998 FI.NumArchVGPR = static_cast<uint32_t>(Val);
6999 HasScalarAttrs = true;
7000 } else if (Dir == "num_agpr") {
7001 int64_t Val;
7002 if (getParser().parseAbsoluteExpression(Val))
7003 return true;
7004 FI.NumAccVGPR = static_cast<uint32_t>(Val);
7005 HasScalarAttrs = true;
7006 } else if (Dir == "private_segment_size") {
7007 int64_t Val;
7008 if (getParser().parseAbsoluteExpression(Val))
7009 return true;
7010 FI.PrivateSegmentSize = static_cast<uint32_t>(Val);
7011 HasScalarAttrs = true;
7012 } else if (Dir == "use") {
7013 StringRef ResName;
7014 if (getParser().parseIdentifier(ResName))
7015 return TokError("expected resource symbol for .amdgpu_use");
7016 ParsedInfoData.Uses.push_back(
7017 {FuncSym, getContext().getOrCreateSymbol(ResName)});
7018 } else if (Dir == "call") {
7019 StringRef DstName;
7020 if (getParser().parseIdentifier(DstName))
7021 return TokError("expected callee symbol for .amdgpu_call");
7022 ParsedInfoData.Calls.push_back(
7023 {FuncSym, getContext().getOrCreateSymbol(DstName)});
7024 } else if (Dir == "indirect_call") {
7025 std::string TypeId;
7026 if (getParser().parseEscapedString(TypeId))
7027 return TokError("expected type ID string for .amdgpu_indirect_call");
7028 ParsedInfoData.IndirectCalls.push_back({FuncSym, std::move(TypeId)});
7029 } else if (Dir == "typeid") {
7030 std::string TypeId;
7031 if (getParser().parseEscapedString(TypeId))
7032 return TokError("expected type ID string for .amdgpu_typeid");
7033 ParsedInfoData.TypeIds.push_back({FuncSym, std::move(TypeId)});
7034 } else {
7035 return Error(IDLoc, "unknown .amdgpu_info directive '" + ID + "'");
7036 }
7037 }
7038
7039 if (HasScalarAttrs)
7040 ParsedInfoData.Funcs.push_back(std::move(FI));
7041
7042 AMDGPU::InfoSectionData &Data = InfoData ? *InfoData : InfoData.emplace();
7043 for (AMDGPU::FuncInfo &Func : ParsedInfoData.Funcs)
7044 Data.Funcs.push_back(std::move(Func));
7045 for (std::pair<MCSymbol *, MCSymbol *> &Use : ParsedInfoData.Uses)
7046 Data.Uses.push_back(Use);
7047 for (std::pair<MCSymbol *, MCSymbol *> &Call : ParsedInfoData.Calls)
7048 Data.Calls.push_back(Call);
7049 for (std::pair<MCSymbol *, std::string> &IndirectCall :
7050 ParsedInfoData.IndirectCalls)
7051 Data.IndirectCalls.push_back(std::move(IndirectCall));
7052 for (std::pair<MCSymbol *, std::string> &TypeId : ParsedInfoData.TypeIds)
7053 Data.TypeIds.push_back(std::move(TypeId));
7054
7055 return false;
7056}
7057
7058void AMDGPUAsmParser::doBeforeLabelEmit(MCSymbol *Symbol, SMLoc IDLoc) {
7059 // Record every parsed label in the timeline so that, at end of file, the
7060 // instructions following a kernel's label can be located regardless of
7061 // whether the .amdhsa_kernel directive came before or after the label.
7062 OpcodeStreamSymbols.emplace_back(Symbol, IDLoc, OpcodeStream.size());
7063}
7064
7065void AMDGPUAsmParser::checkKernelPrologues() {
7066 if (getFeatureBits()[AMDGPU::FeatureRequiresInitialUnclausedVmem]) {
7067 static const unsigned Required[] = {S_MOV_B64_gfx12, V_NOP_e32_gfx12,
7068 GLOBAL_PREFETCH_B8_SADDR_gfx1250};
7069 for (auto [Sym, Loc, Offset] : OpcodeStreamSymbols) {
7070 if (!AMDHSAKernelSymbols.contains(Sym))
7071 continue;
7072 ArrayRef<unsigned> Prologue = ArrayRef(OpcodeStream).drop_front(Offset);
7073 if (!Prologue.empty() && Prologue.front() == S_SETREG_IMM32_B32_gfx12)
7074 Prologue = Prologue.drop_front();
7075 if (Prologue.take_front(std::size(Required)) != ArrayRef(Required)) {
7076 Warning(Loc, "kernel '" + Sym->getName() +
7077 "' does not begin with the required prologue "
7078 "sequence: s_mov_b64 followed by v_nop and "
7079 "global_prefetch_b8");
7080 }
7081 }
7082 }
7083 OpcodeStream.clear();
7084 OpcodeStreamSymbols.clear();
7085 AMDHSAKernelSymbols.clear();
7086}
7087
7088void AMDGPUAsmParser::onEndOfFile() {
7089 emitTargetDirective();
7090 checkKernelPrologues();
7091 if (InfoData)
7092 getTargetStreamer().emitAMDGPUInfo(*InfoData);
7093}
7094
7095bool AMDGPUAsmParser::ParseDirective(AsmToken DirectiveID) {
7096 StringRef IDVal = DirectiveID.getString();
7097
7098 if (isHsaAbi(getSTI())) {
7099 if (IDVal == ".amdhsa_kernel")
7100 return ParseDirectiveAMDHSAKernel();
7101
7102 if (IDVal == ".amdhsa_code_object_version")
7103 return ParseDirectiveAMDHSACodeObjectVersion();
7104
7105 // TODO: Restructure/combine with PAL metadata directive.
7107 return ParseDirectiveHSAMetadata();
7108 } else {
7109 if (IDVal == ".amd_kernel_code_t")
7110 return ParseDirectiveAMDKernelCodeT();
7111
7112 if (IDVal == ".amdgpu_hsa_kernel")
7113 return ParseDirectiveAMDGPUHsaKernel();
7114
7115 if (IDVal == ".amd_amdgpu_isa")
7116 return ParseDirectiveISAVersion();
7117
7119 return Error(getLoc(), (Twine(HSAMD::AssemblerDirectiveBegin) +
7120 Twine(" directive is "
7121 "not available on non-amdhsa OSes"))
7122 .str());
7123 }
7124 }
7125
7126 if (IDVal == ".amdgcn_target")
7127 return ParseDirectiveAMDGCNTarget();
7128
7129 if (IDVal == ".amdgpu_lds")
7130 return ParseDirectiveAMDGPULDS();
7131
7132 if (IDVal == ".amdgpu_info")
7133 return ParseDirectiveAMDGPUInfo();
7134
7135 if (IDVal == PALMD::AssemblerDirectiveBegin)
7136 return ParseDirectivePALMetadataBegin();
7137
7138 if (IDVal == PALMD::AssemblerDirective)
7139 return ParseDirectivePALMetadata();
7140
7141 return true;
7142}
7143
7144bool AMDGPUAsmParser::subtargetHasRegister(const MCRegisterInfo &MRI,
7145 MCRegister Reg) {
7146 if (MRI.regsOverlap(TTMP12_TTMP13_TTMP14_TTMP15, Reg))
7147 return isGFX9Plus();
7148
7149 // GFX10+ has 2 more SGPRs 104 and 105.
7150 if (MRI.regsOverlap(SGPR104_SGPR105, Reg))
7151 return hasSGPR104_SGPR105();
7152
7153 switch (Reg.id()) {
7154 case SRC_SHARED_BASE_LO:
7155 case SRC_SHARED_BASE:
7156 case SRC_SHARED_LIMIT_LO:
7157 case SRC_SHARED_LIMIT:
7158 return isGFX9Plus();
7159 case SRC_PRIVATE_BASE_LO:
7160 case SRC_PRIVATE_BASE:
7161 case SRC_PRIVATE_LIMIT_LO:
7162 case SRC_PRIVATE_LIMIT:
7163 return AMDGPU::hasPrivateApertureRegs(getSTI());
7164 case SRC_FLAT_SCRATCH_BASE_LO:
7165 case SRC_FLAT_SCRATCH_BASE_HI:
7166 return hasGloballyAddressableScratch();
7167 case SRC_POPS_EXITING_WAVE_ID:
7168 return hasPopsExitingWaveID(getSTI());
7169 case TBA:
7170 case TBA_LO:
7171 case TBA_HI:
7172 case TMA:
7173 case TMA_LO:
7174 case TMA_HI:
7175 return !isGFX9Plus();
7176 case XNACK_MASK:
7177 case XNACK_MASK_LO:
7178 case XNACK_MASK_HI:
7179 return (isVI() || isGFX9()) &&
7180 getTargetStreamer().getTargetID()->isXnackSupported();
7181 case SGPR_NULL:
7182 return isGFX10Plus();
7183 case SRC_EXECZ:
7184 case SRC_VCCZ:
7185 return !isGFX11Plus();
7186 default:
7187 break;
7188 }
7189
7190 if (isCI())
7191 return true;
7192
7193 if (isSI() || isGFX10Plus()) {
7194 // No flat_scr on SI.
7195 // On GFX10Plus flat scratch is not a valid register operand and can only be
7196 // accessed with s_setreg/s_getreg.
7197 switch (Reg.id()) {
7198 case FLAT_SCR:
7199 case FLAT_SCR_LO:
7200 case FLAT_SCR_HI:
7201 return false;
7202 default:
7203 return true;
7204 }
7205 }
7206
7207 // VI only has 102 SGPRs, so make sure we aren't trying to use the 2 more that
7208 // SI/CI have.
7209 if (MRI.regsOverlap(SGPR102_SGPR103, Reg))
7210 return hasSGPR102_SGPR103();
7211
7212 return true;
7213}
7214
7215ParseStatus AMDGPUAsmParser::parseOperand(OperandVector &Operands,
7216 StringRef Mnemonic,
7217 OperandMode Mode) {
7218 ParseStatus Res = parseVOPD(Operands);
7219 if (Res.isSuccess() || Res.isFailure() || isToken(AsmToken::EndOfStatement))
7220 return Res;
7221
7222 // Try to parse with a custom parser
7223 Res = MatchOperandParserImpl(Operands, Mnemonic);
7224
7225 // If we successfully parsed the operand or if there as an error parsing,
7226 // we are done.
7227 //
7228 // If we are parsing after we reach EndOfStatement then this means we
7229 // are appending default values to the Operands list. This is only done
7230 // by custom parser, so we shouldn't continue on to the generic parsing.
7231 if (Res.isSuccess() || Res.isFailure() || isToken(AsmToken::EndOfStatement))
7232 return Res;
7233
7234 SMLoc RBraceLoc;
7235 SMLoc LBraceLoc = getLoc();
7236 if (Mode == OperandMode_NSA && trySkipToken(AsmToken::LBrac)) {
7237 unsigned Prefix = Operands.size();
7238
7239 for (;;) {
7240 auto Loc = getLoc();
7241 Res = parseReg(Operands);
7242 if (Res.isNoMatch())
7243 Error(Loc, "expected a register");
7244 if (!Res.isSuccess())
7245 return ParseStatus::Failure;
7246
7247 RBraceLoc = getLoc();
7248 if (trySkipToken(AsmToken::RBrac))
7249 break;
7250
7251 if (!skipToken(AsmToken::Comma,
7252 "expected a comma or a closing square bracket"))
7253 return ParseStatus::Failure;
7254 }
7255
7256 if (Operands.size() - Prefix > 1) {
7257 Operands.insert(Operands.begin() + Prefix,
7258 AMDGPUOperand::CreateToken(this, "[", LBraceLoc));
7259 Operands.push_back(AMDGPUOperand::CreateToken(this, "]", RBraceLoc));
7260 }
7261
7262 return ParseStatus::Success;
7263 }
7264
7265 return parseRegOrImm(Operands);
7266}
7267
7268StringRef AMDGPUAsmParser::parseMnemonicSuffix(StringRef Name) {
7269 // Clear any forced encodings from the previous instruction.
7270 setForcedEncodingSize(0);
7271 setForcedDPP(false);
7272 setForcedSDWA(false);
7273
7274 if (Name.consume_back("_e64_dpp")) {
7275 setForcedDPP(true);
7276 setForcedEncodingSize(64);
7277 return Name;
7278 }
7279 if (Name.consume_back("_e64")) {
7280 setForcedEncodingSize(64);
7281 return Name;
7282 }
7283 if (Name.consume_back("_e32")) {
7284 setForcedEncodingSize(32);
7285 return Name;
7286 }
7287 if (Name.consume_back("_dpp")) {
7288 setForcedDPP(true);
7289 return Name;
7290 }
7291 if (Name.consume_back("_sdwa")) {
7292 setForcedSDWA(true);
7293 return Name;
7294 }
7295 return Name;
7296}
7297
7298static void applyMnemonicAliases(StringRef &Mnemonic,
7299 const FeatureBitset &Features,
7300 unsigned VariantID);
7301
7302bool AMDGPUAsmParser::parseInstruction(ParseInstructionInfo &Info,
7303 StringRef Name, SMLoc NameLoc,
7305 // Add the instruction mnemonic
7306 Name = parseMnemonicSuffix(Name);
7307
7308 // If the target architecture uses MnemonicAlias, call it here to parse
7309 // operands correctly.
7310 applyMnemonicAliases(Name, getAvailableFeatures(), 0);
7311
7312 Operands.push_back(AMDGPUOperand::CreateToken(this, Name, NameLoc));
7313
7314 bool IsMIMG = Name.starts_with("image_");
7315
7316 while (!trySkipToken(AsmToken::EndOfStatement)) {
7317 OperandMode Mode = OperandMode_Default;
7318 if (IsMIMG && isGFX10Plus() && Operands.size() == 2)
7319 Mode = OperandMode_NSA;
7320 ParseStatus Res = parseOperand(Operands, Name, Mode);
7321
7322 if (!Res.isSuccess()) {
7323 checkUnsupportedInstruction(Name, NameLoc);
7324 if (!Parser.hasPendingError()) {
7325 // FIXME: use real operand location rather than the current location.
7326 StringRef Msg = Res.isFailure() ? "failed parsing operand."
7327 : "not a valid operand.";
7328 Error(getLoc(), Msg);
7329 }
7330 while (!trySkipToken(AsmToken::EndOfStatement)) {
7331 lex();
7332 }
7333 return true;
7334 }
7335
7336 // Eat the comma or space if there is one.
7337 trySkipToken(AsmToken::Comma);
7338 }
7339
7340 return false;
7341}
7342
7343//===----------------------------------------------------------------------===//
7344// Utility functions
7345//===----------------------------------------------------------------------===//
7346
7347ParseStatus AMDGPUAsmParser::parseTokenOp(StringRef Name,
7349 SMLoc S = getLoc();
7350 if (!trySkipId(Name))
7351 return ParseStatus::NoMatch;
7352
7353 Operands.push_back(AMDGPUOperand::CreateToken(this, Name, S));
7354 return ParseStatus::Success;
7355}
7356
7357ParseStatus AMDGPUAsmParser::parseIntWithPrefix(const char *Prefix,
7358 int64_t &IntVal) {
7359
7360 if (!trySkipId(Prefix, AsmToken::Colon))
7361 return ParseStatus::NoMatch;
7362
7364}
7365
7366ParseStatus AMDGPUAsmParser::parseIntWithPrefix(
7367 const char *Prefix, OperandVector &Operands, AMDGPUOperand::ImmTy ImmTy,
7368 std::function<bool(int64_t &)> ConvertResult) {
7369 SMLoc S = getLoc();
7370 int64_t Value = 0;
7371
7372 ParseStatus Res = parseIntWithPrefix(Prefix, Value);
7373 if (!Res.isSuccess())
7374 return Res;
7375
7376 if (ConvertResult && !ConvertResult(Value)) {
7377 Error(S, "invalid " + StringRef(Prefix) + " value.");
7378 }
7379
7380 Operands.push_back(AMDGPUOperand::CreateImm(this, Value, S, ImmTy));
7381 return ParseStatus::Success;
7382}
7383
7384ParseStatus AMDGPUAsmParser::parseOperandArrayWithPrefix(
7385 const char *Prefix, OperandVector &Operands, AMDGPUOperand::ImmTy ImmTy,
7386 bool (*ConvertResult)(int64_t &)) {
7387 SMLoc S = getLoc();
7388 if (!trySkipId(Prefix, AsmToken::Colon))
7389 return ParseStatus::NoMatch;
7390
7391 if (!skipToken(AsmToken::LBrac, "expected a left square bracket"))
7392 return ParseStatus::Failure;
7393
7394 unsigned Val = 0;
7395 const unsigned MaxSize = 4;
7396
7397 // FIXME: How to verify the number of elements matches the number of src
7398 // operands?
7399 for (int I = 0;; ++I) {
7400 int64_t Op;
7401 SMLoc Loc = getLoc();
7402 if (!parseExpr(Op))
7403 return ParseStatus::Failure;
7404
7405 if (Op != 0 && Op != 1)
7406 return Error(Loc, "invalid " + StringRef(Prefix) + " value.");
7407
7408 Val |= (Op << I);
7409
7410 if (trySkipToken(AsmToken::RBrac))
7411 break;
7412
7413 if (I + 1 == MaxSize)
7414 return Error(getLoc(), "expected a closing square bracket");
7415
7416 if (!skipToken(AsmToken::Comma, "expected a comma"))
7417 return ParseStatus::Failure;
7418 }
7419
7420 Operands.push_back(AMDGPUOperand::CreateImm(this, Val, S, ImmTy));
7421 return ParseStatus::Success;
7422}
7423
7424ParseStatus AMDGPUAsmParser::parseNamedBit(StringRef Name,
7426 AMDGPUOperand::ImmTy ImmTy,
7427 bool IgnoreNegative) {
7428 int64_t Bit;
7429 SMLoc S = getLoc();
7430
7431 if (trySkipId(Name)) {
7432 Bit = 1;
7433 } else if (trySkipId("no", Name)) {
7434 if (IgnoreNegative)
7435 return ParseStatus::Success;
7436 Bit = 0;
7437 } else {
7438 return ParseStatus::NoMatch;
7439 }
7440
7441 if (Name == "r128" && !hasMIMG_R128())
7442 return Error(S, "r128 modifier is not supported on this GPU");
7443 if (Name == "a16" && !hasA16())
7444 return Error(S, "a16 modifier is not supported on this GPU");
7445
7446 if (Bit == 0 && Name == "gds") {
7447 StringRef Mnemo = ((AMDGPUOperand &)*Operands[0]).getToken();
7448 if (Mnemo.starts_with("ds_gws"))
7449 return Error(S, "nogds is not allowed");
7450 }
7451
7452 if (isGFX9() && ImmTy == AMDGPUOperand::ImmTyA16)
7453 ImmTy = AMDGPUOperand::ImmTyR128A16;
7454
7455 Operands.push_back(AMDGPUOperand::CreateImm(this, Bit, S, ImmTy));
7456 return ParseStatus::Success;
7457}
7458
7459unsigned AMDGPUAsmParser::getCPolKind(StringRef Id, StringRef Mnemo,
7460 bool &Disabling) const {
7461 Disabling = Id.consume_front("no");
7462
7463 if (isGFX940() && !Mnemo.starts_with("s_")) {
7464 return StringSwitch<unsigned>(Id)
7465 .Case("nt", AMDGPU::CPol::NT)
7466 .Case("sc0", AMDGPU::CPol::SC0)
7467 .Case("sc1", AMDGPU::CPol::SC1)
7468 .Default(0);
7469 }
7470
7471 return StringSwitch<unsigned>(Id)
7472 .Case("dlc", AMDGPU::CPol::DLC)
7473 .Case("glc", AMDGPU::CPol::GLC)
7474 .Case("scc", AMDGPU::CPol::SCC)
7475 .Case("slc", AMDGPU::CPol::SLC)
7476 .Default(0);
7477}
7478
7479ParseStatus AMDGPUAsmParser::parseCPol(OperandVector &Operands) {
7480 if (isGFX12Plus()) {
7481 SMLoc StringLoc = getLoc();
7482
7483 int64_t CPolVal = 0;
7484 ParseStatus ResTH = ParseStatus::NoMatch;
7485 ParseStatus ResScope = ParseStatus::NoMatch;
7486 ParseStatus ResNV = ParseStatus::NoMatch;
7487 ParseStatus ResScal = ParseStatus::NoMatch;
7488 ParseStatus ResCFS = ParseStatus::NoMatch;
7489
7490 for (;;) {
7491 if (ResTH.isNoMatch()) {
7492 int64_t TH;
7493 ResTH = parseTH(Operands, TH);
7494 if (ResTH.isFailure())
7495 return ResTH;
7496 if (ResTH.isSuccess()) {
7497 CPolVal |= TH;
7498 continue;
7499 }
7500 }
7501
7502 if (ResScope.isNoMatch()) {
7503 int64_t Scope;
7504 ResScope = parseScope(Operands, Scope);
7505 if (ResScope.isFailure())
7506 return ResScope;
7507 if (ResScope.isSuccess()) {
7508 CPolVal |= Scope;
7509 continue;
7510 }
7511 }
7512
7513 // NV bit exists on GFX12+, but does something starting from GFX1250.
7514 // Allow parsing on all GFX12 and fail on validation for better
7515 // diagnostics.
7516 if (ResNV.isNoMatch()) {
7517 if (trySkipId("nv")) {
7518 ResNV = ParseStatus::Success;
7519 CPolVal |= CPol::NV;
7520 continue;
7521 } else if (trySkipId("no", "nv")) {
7522 ResNV = ParseStatus::Success;
7523 continue;
7524 }
7525 }
7526
7527 if (ResScal.isNoMatch()) {
7528 if (trySkipId("scale_offset")) {
7529 ResScal = ParseStatus::Success;
7530 CPolVal |= CPol::SCAL;
7531 continue;
7532 } else if (trySkipId("no", "scale_offset")) {
7533 ResScal = ParseStatus::Success;
7534 continue;
7535 }
7536 }
7537
7538 if (ResCFS.isNoMatch()) {
7539 int64_t CFS;
7540 ResCFS = parseCFS(Operands, CFS);
7541 if (ResCFS.isFailure())
7542 return ResCFS;
7543 if (ResCFS.isSuccess()) {
7544 CPolVal |= CFS;
7545 continue;
7546 }
7547 }
7548
7549 break;
7550 }
7551
7552 if (ResTH.isNoMatch() && ResScope.isNoMatch() && ResNV.isNoMatch() &&
7553 ResScal.isNoMatch() && ResCFS.isNoMatch())
7554 return ParseStatus::NoMatch;
7555
7556 Operands.push_back(AMDGPUOperand::CreateImm(this, CPolVal, StringLoc,
7557 AMDGPUOperand::ImmTyCPol));
7558 return ParseStatus::Success;
7559 }
7560
7561 StringRef Mnemo = ((AMDGPUOperand &)*Operands[0]).getToken();
7562 SMLoc OpLoc = getLoc();
7563 unsigned Enabled = 0, Seen = 0;
7564 for (;;) {
7565 SMLoc S = getLoc();
7566 bool Disabling;
7567 unsigned CPol = getCPolKind(getId(), Mnemo, Disabling);
7568 if (!CPol)
7569 break;
7570
7571 lex();
7572
7573 if (!isGFX10Plus() && CPol == AMDGPU::CPol::DLC)
7574 return Error(S, "dlc modifier is not supported on this GPU");
7575
7576 if (!isGFX90A() && CPol == AMDGPU::CPol::SCC)
7577 return Error(S, "scc modifier is not supported on this GPU");
7578
7579 if (Seen & CPol)
7580 return Error(S, "duplicate cache policy modifier");
7581
7582 if (!Disabling)
7583 Enabled |= CPol;
7584
7585 Seen |= CPol;
7586 }
7587
7588 if (!Seen)
7589 return ParseStatus::NoMatch;
7590
7591 Operands.push_back(
7592 AMDGPUOperand::CreateImm(this, Enabled, OpLoc, AMDGPUOperand::ImmTyCPol));
7593 return ParseStatus::Success;
7594}
7595
7596ParseStatus AMDGPUAsmParser::parseScope(OperandVector &Operands,
7597 int64_t &Scope) {
7598 static const unsigned Scopes[] = {CPol::SCOPE_CU, CPol::SCOPE_SE,
7600
7601 ParseStatus Res = parseStringOrIntWithPrefix(
7602 Operands, "scope", {"SCOPE_CU", "SCOPE_SE", "SCOPE_DEV", "SCOPE_SYS"},
7603 Scope);
7604
7605 if (Res.isSuccess())
7606 Scope = Scopes[Scope];
7607
7608 return Res;
7609}
7610
7611ParseStatus AMDGPUAsmParser::parseTH(OperandVector &Operands, int64_t &TH) {
7612 TH = AMDGPU::CPol::TH_RT; // default
7613
7614 StringRef Value;
7615 SMLoc StringLoc;
7616 ParseStatus Res = parseStringWithPrefix("th", Value, StringLoc);
7617 if (!Res.isSuccess())
7618 return Res;
7619
7620 if (Value == "TH_DEFAULT")
7622 else if (Value == "TH_STORE_LU" || Value == "TH_LOAD_WB" ||
7623 Value == "TH_LOAD_NT_WB") {
7624 return Error(StringLoc, "invalid th value");
7625 } else if (Value.consume_front("TH_ATOMIC_")) {
7627 } else if (Value.consume_front("TH_LOAD_")) {
7629 } else if (Value.consume_front("TH_STORE_")) {
7631 } else {
7632 return Error(StringLoc, "invalid th value");
7633 }
7634
7635 if (Value == "BYPASS")
7637
7638 if (TH != 0) {
7640 TH |= StringSwitch<int64_t>(Value)
7641 .Case("RETURN", AMDGPU::CPol::TH_ATOMIC_RETURN)
7642 .Case("RT", AMDGPU::CPol::TH_RT)
7643 .Case("RT_RETURN", AMDGPU::CPol::TH_ATOMIC_RETURN)
7644 .Case("NT", AMDGPU::CPol::TH_ATOMIC_NT)
7645 .Case("NT_RETURN", AMDGPU::CPol::TH_ATOMIC_NT |
7647 .Case("CASCADE_RT", AMDGPU::CPol::TH_ATOMIC_CASCADE)
7648 .Case("CASCADE_NT", AMDGPU::CPol::TH_ATOMIC_CASCADE |
7650 .Default(0xffffffff);
7651 else
7652 TH |= StringSwitch<int64_t>(Value)
7653 .Case("RT", AMDGPU::CPol::TH_RT)
7654 .Case("NT", AMDGPU::CPol::TH_NT)
7655 .Case("HT", AMDGPU::CPol::TH_HT)
7656 .Case("LU", AMDGPU::CPol::TH_LU)
7657 .Case("WB", AMDGPU::CPol::TH_WB)
7658 .Case("NT_RT", AMDGPU::CPol::TH_NT_RT)
7659 .Case("RT_NT", AMDGPU::CPol::TH_RT_NT)
7660 .Case("NT_HT", AMDGPU::CPol::TH_NT_HT)
7661 .Case("NT_WB", AMDGPU::CPol::TH_NT_WB)
7662 .Case("BYPASS", AMDGPU::CPol::TH_BYPASS)
7663 .Default(0xffffffff);
7664 }
7665
7666 if (TH == 0xffffffff)
7667 return Error(StringLoc, "invalid th value");
7668
7669 return ParseStatus::Success;
7670}
7671
7672ParseStatus AMDGPUAsmParser::parseCFS(OperandVector &Operands, int64_t &CFS) {
7673 static const unsigned CFSVals[] = {CPol::CFS_256B, CPol::CFS_128B,
7675
7676 ParseStatus Res = parseStringOrIntWithPrefix(
7677 Operands, "cfs", {"CFS_256B", "CFS_128B", "CFS_64B", "CFS_32B"}, CFS);
7678
7679 if (Res.isSuccess())
7680 CFS = CFSVals[CFS];
7681
7682 return Res;
7683}
7684
7685static void
7687 AMDGPUAsmParser::OptionalImmIndexMap &OptionalIdx,
7688 AMDGPUOperand::ImmTy ImmT, int64_t Default = 0,
7689 std::optional<unsigned> InsertAt = std::nullopt) {
7690 auto i = OptionalIdx.find(ImmT);
7691 if (i != OptionalIdx.end()) {
7692 unsigned Idx = i->second;
7693 const AMDGPUOperand &Op =
7694 static_cast<const AMDGPUOperand &>(*Operands[Idx]);
7695 if (InsertAt)
7696 Inst.insert(Inst.begin() + *InsertAt, MCOperand::createImm(Op.getImm()));
7697 else
7698 Op.addImmOperands(Inst, 1);
7699 } else {
7700 if (InsertAt.has_value())
7701 Inst.insert(Inst.begin() + *InsertAt, MCOperand::createImm(Default));
7702 else
7704 }
7705}
7706
7707ParseStatus AMDGPUAsmParser::parseStringWithPrefix(StringRef Prefix,
7708 StringRef &Value,
7709 SMLoc &StringLoc) {
7710 if (!trySkipId(Prefix, AsmToken::Colon))
7711 return ParseStatus::NoMatch;
7712
7713 StringLoc = getLoc();
7714 return parseId(Value, "expected an identifier") ? ParseStatus::Success
7716}
7717
7718ParseStatus AMDGPUAsmParser::parseStringOrIntWithPrefix(
7719 OperandVector &Operands, StringRef Name, ArrayRef<const char *> Ids,
7720 int64_t &IntVal) {
7721 if (!trySkipId(Name, AsmToken::Colon))
7722 return ParseStatus::NoMatch;
7723
7724 SMLoc StringLoc = getLoc();
7725
7726 StringRef Value;
7727 if (isToken(AsmToken::Identifier)) {
7728 Value = getTokenStr();
7729 lex();
7730
7731 for (IntVal = 0; IntVal < (int64_t)Ids.size(); ++IntVal)
7732 if (Value == Ids[IntVal])
7733 break;
7734 } else if (!parseExpr(IntVal))
7735 return ParseStatus::Failure;
7736
7737 if (IntVal < 0 || IntVal >= (int64_t)Ids.size())
7738 return Error(StringLoc, "invalid " + Twine(Name) + " value");
7739
7740 return ParseStatus::Success;
7741}
7742
7743ParseStatus AMDGPUAsmParser::parseStringOrIntWithPrefix(
7744 OperandVector &Operands, StringRef Name, ArrayRef<const char *> Ids,
7745 AMDGPUOperand::ImmTy Type) {
7746 SMLoc S = getLoc();
7747 int64_t IntVal;
7748
7749 ParseStatus Res = parseStringOrIntWithPrefix(Operands, Name, Ids, IntVal);
7750 if (Res.isSuccess())
7751 Operands.push_back(AMDGPUOperand::CreateImm(this, IntVal, S, Type));
7752
7753 return Res;
7754}
7755
7756//===----------------------------------------------------------------------===//
7757// MTBUF format
7758//===----------------------------------------------------------------------===//
7759
7760ParseStatus AMDGPUAsmParser::tryParseFmt(const char *Pref, int64_t MaxVal,
7761 int64_t &Fmt) {
7762 int64_t Val;
7763 SMLoc Loc = getLoc();
7764
7765 ParseStatus Res = parseIntWithPrefix(Pref, Val);
7766 if (!Res.isSuccess())
7767 return Res;
7768
7769 if (Val < 0 || Val > MaxVal)
7770 return Error(Loc, Twine("out of range ", StringRef(Pref)));
7771
7772 Fmt = Val;
7773 return ParseStatus::Success;
7774}
7775
7776ParseStatus AMDGPUAsmParser::tryParseIndexKey(OperandVector &Operands,
7777 AMDGPUOperand::ImmTy ImmTy) {
7778 const char *Pref = "index_key";
7779 int64_t ImmVal = 0;
7780 SMLoc Loc = getLoc();
7781 auto Res = parseIntWithPrefix(Pref, ImmVal);
7782 if (!Res.isSuccess())
7783 return Res;
7784
7785 if ((ImmTy == AMDGPUOperand::ImmTyIndexKey16bit ||
7786 ImmTy == AMDGPUOperand::ImmTyIndexKey32bit) &&
7787 (ImmVal < 0 || ImmVal > 1))
7788 return Error(Loc, Twine("out of range ", StringRef(Pref)));
7789
7790 if (ImmTy == AMDGPUOperand::ImmTyIndexKey8bit && (ImmVal < 0 || ImmVal > 3))
7791 return Error(Loc, Twine("out of range ", StringRef(Pref)));
7792
7793 Operands.push_back(AMDGPUOperand::CreateImm(this, ImmVal, Loc, ImmTy));
7794 return ParseStatus::Success;
7795}
7796
7797ParseStatus AMDGPUAsmParser::parseIndexKey8bit(OperandVector &Operands) {
7798 return tryParseIndexKey(Operands, AMDGPUOperand::ImmTyIndexKey8bit);
7799}
7800
7801ParseStatus AMDGPUAsmParser::parseIndexKey16bit(OperandVector &Operands) {
7802 return tryParseIndexKey(Operands, AMDGPUOperand::ImmTyIndexKey16bit);
7803}
7804
7805ParseStatus AMDGPUAsmParser::parseIndexKey32bit(OperandVector &Operands) {
7806 return tryParseIndexKey(Operands, AMDGPUOperand::ImmTyIndexKey32bit);
7807}
7808
7809ParseStatus AMDGPUAsmParser::tryParseMatrixFMT(OperandVector &Operands,
7810 StringRef Name,
7811 AMDGPUOperand::ImmTy Type) {
7812 return parseStringOrIntWithPrefix(Operands, Name, WMMAMods::ModMatrixFmt,
7813 Type);
7814}
7815
7816ParseStatus AMDGPUAsmParser::parseMatrixAFMT(OperandVector &Operands) {
7817 return tryParseMatrixFMT(Operands, "matrix_a_fmt",
7818 AMDGPUOperand::ImmTyMatrixAFMT);
7819}
7820
7821ParseStatus AMDGPUAsmParser::parseMatrixBFMT(OperandVector &Operands) {
7822 return tryParseMatrixFMT(Operands, "matrix_b_fmt",
7823 AMDGPUOperand::ImmTyMatrixBFMT);
7824}
7825
7826ParseStatus AMDGPUAsmParser::tryParseMatrixScale(OperandVector &Operands,
7827 StringRef Name,
7828 AMDGPUOperand::ImmTy Type) {
7829 return parseStringOrIntWithPrefix(Operands, Name, WMMAMods::ModMatrixScale,
7830 Type);
7831}
7832
7833ParseStatus AMDGPUAsmParser::parseMatrixAScale(OperandVector &Operands) {
7834 return tryParseMatrixScale(Operands, "matrix_a_scale",
7835 AMDGPUOperand::ImmTyMatrixAScale);
7836}
7837
7838ParseStatus AMDGPUAsmParser::parseMatrixBScale(OperandVector &Operands) {
7839 return tryParseMatrixScale(Operands, "matrix_b_scale",
7840 AMDGPUOperand::ImmTyMatrixBScale);
7841}
7842
7843ParseStatus AMDGPUAsmParser::tryParseMatrixScaleFmt(OperandVector &Operands,
7844 StringRef Name,
7845 AMDGPUOperand::ImmTy Type) {
7846 return parseStringOrIntWithPrefix(Operands, Name, WMMAMods::ModMatrixScaleFmt,
7847 Type);
7848}
7849
7850ParseStatus AMDGPUAsmParser::parseMatrixAScaleFmt(OperandVector &Operands) {
7851 return tryParseMatrixScaleFmt(Operands, "matrix_a_scale_fmt",
7852 AMDGPUOperand::ImmTyMatrixAScaleFmt);
7853}
7854
7855ParseStatus AMDGPUAsmParser::parseMatrixBScaleFmt(OperandVector &Operands) {
7856 return tryParseMatrixScaleFmt(Operands, "matrix_b_scale_fmt",
7857 AMDGPUOperand::ImmTyMatrixBScaleFmt);
7858}
7859
7860// dfmt and nfmt (in a tbuffer instruction) are parsed as one to allow their
7861// values to live in a joint format operand in the MCInst encoding.
7862ParseStatus AMDGPUAsmParser::parseDfmtNfmt(int64_t &Format) {
7863 using namespace llvm::AMDGPU::MTBUFFormat;
7864
7865 int64_t Dfmt = DFMT_DEFAULT;
7866 int64_t Nfmt = NFMT_DEFAULT;
7867
7868 auto TryAfterComma = [&](const char *Pref, int64_t MaxVal,
7869 int64_t &Fmt) -> ParseStatus {
7870 if (isId(Pref) && peekToken().is(AsmToken::Colon))
7871 return Error(getLoc(), "expected a comma");
7872 AsmToken NextTokens[2];
7873 peekTokens(NextTokens);
7874 if (!isToken(AsmToken::Comma) || !isId(NextTokens[0], Pref) ||
7875 !NextTokens[1].is(AsmToken::Colon))
7876 return ParseStatus::Success;
7877 lex();
7878 return tryParseFmt(Pref, MaxVal, Fmt);
7879 };
7880
7881 // dfmt and nfmt can appear in either order, and each is optional. If both
7882 // are present, they are separated by a comma.
7883 ParseStatus Res = tryParseFmt("dfmt", DFMT_MAX, Dfmt);
7884 if (Res.isSuccess()) {
7885 Res = TryAfterComma("nfmt", NFMT_MAX, Nfmt);
7886 } else if (Res.isNoMatch()) {
7887 Res = tryParseFmt("nfmt", NFMT_MAX, Nfmt);
7888 if (Res.isSuccess())
7889 Res = TryAfterComma("dfmt", DFMT_MAX, Dfmt);
7890 }
7891 if (!Res.isSuccess())
7892 return Res;
7893
7894 Format = encodeDfmtNfmt(Dfmt, Nfmt);
7895 return ParseStatus::Success;
7896}
7897
7898ParseStatus AMDGPUAsmParser::parseUfmt(int64_t &Format) {
7899 return tryParseFmt("format", MTBUFFormat::UFMT_MAX, Format);
7900}
7901
7902bool AMDGPUAsmParser::matchDfmtNfmt(int64_t &Dfmt, int64_t &Nfmt,
7903 StringRef FormatStr, SMLoc Loc) {
7904 using namespace llvm::AMDGPU::MTBUFFormat;
7905 int64_t Format;
7906
7907 Format = getDfmt(FormatStr);
7908 if (Format != DFMT_UNDEF) {
7909 Dfmt = Format;
7910 return true;
7911 }
7912
7913 Format = getNfmt(FormatStr, getSTI());
7914 if (Format != NFMT_UNDEF) {
7915 Nfmt = Format;
7916 return true;
7917 }
7918
7919 Error(Loc, "unsupported format");
7920 return false;
7921}
7922
7923ParseStatus AMDGPUAsmParser::parseSymbolicSplitFormat(StringRef FormatStr,
7924 SMLoc FormatLoc,
7925 int64_t &Format) {
7926 using namespace llvm::AMDGPU::MTBUFFormat;
7927
7928 int64_t Dfmt = DFMT_UNDEF;
7929 int64_t Nfmt = NFMT_UNDEF;
7930 if (!matchDfmtNfmt(Dfmt, Nfmt, FormatStr, FormatLoc))
7931 return ParseStatus::Failure;
7932
7933 if (trySkipToken(AsmToken::Comma)) {
7934 StringRef Str;
7935 SMLoc Loc = getLoc();
7936 if (!parseId(Str, "expected a format string") ||
7937 !matchDfmtNfmt(Dfmt, Nfmt, Str, Loc))
7938 return ParseStatus::Failure;
7939 if (Dfmt == DFMT_UNDEF)
7940 return Error(Loc, "duplicate numeric format");
7941 if (Nfmt == NFMT_UNDEF)
7942 return Error(Loc, "duplicate data format");
7943 }
7944
7945 Dfmt = (Dfmt == DFMT_UNDEF) ? DFMT_DEFAULT : Dfmt;
7946 Nfmt = (Nfmt == NFMT_UNDEF) ? NFMT_DEFAULT : Nfmt;
7947
7948 if (isGFX10Plus()) {
7949 auto Ufmt = convertDfmtNfmt2Ufmt(Dfmt, Nfmt, getSTI());
7950 if (Ufmt == UFMT_UNDEF)
7951 return Error(FormatLoc, "unsupported format");
7952 Format = Ufmt;
7953 } else {
7954 Format = encodeDfmtNfmt(Dfmt, Nfmt);
7955 }
7956
7957 return ParseStatus::Success;
7958}
7959
7960ParseStatus AMDGPUAsmParser::parseSymbolicUnifiedFormat(StringRef FormatStr,
7961 SMLoc Loc,
7962 int64_t &Format) {
7963 using namespace llvm::AMDGPU::MTBUFFormat;
7964
7965 auto Id = getUnifiedFormat(FormatStr, getSTI());
7966 if (Id == UFMT_UNDEF)
7967 return ParseStatus::NoMatch;
7968
7969 if (!isGFX10Plus())
7970 return Error(Loc, "unified format is not supported on this GPU");
7971
7972 Format = Id;
7973 return ParseStatus::Success;
7974}
7975
7976ParseStatus AMDGPUAsmParser::parseNumericFormat(int64_t &Format) {
7977 using namespace llvm::AMDGPU::MTBUFFormat;
7978 SMLoc Loc = getLoc();
7979
7980 if (!parseExpr(Format))
7981 return ParseStatus::Failure;
7982 if (!isValidFormatEncoding(Format, getSTI()))
7983 return Error(Loc, "out of range format");
7984
7985 return ParseStatus::Success;
7986}
7987
7988ParseStatus AMDGPUAsmParser::parseSymbolicOrNumericFormat(int64_t &Format) {
7989 using namespace llvm::AMDGPU::MTBUFFormat;
7990
7991 if (!trySkipId("format", AsmToken::Colon))
7992 return ParseStatus::NoMatch;
7993
7994 if (trySkipToken(AsmToken::LBrac)) {
7995 StringRef FormatStr;
7996 SMLoc Loc = getLoc();
7997 if (!parseId(FormatStr, "expected a format string"))
7998 return ParseStatus::Failure;
7999
8000 auto Res = parseSymbolicUnifiedFormat(FormatStr, Loc, Format);
8001 if (Res.isNoMatch())
8002 Res = parseSymbolicSplitFormat(FormatStr, Loc, Format);
8003 if (!Res.isSuccess())
8004 return Res;
8005
8006 if (!skipToken(AsmToken::RBrac, "expected a closing square bracket"))
8007 return ParseStatus::Failure;
8008
8009 return ParseStatus::Success;
8010 }
8011
8012 return parseNumericFormat(Format);
8013}
8014
8015ParseStatus AMDGPUAsmParser::parseFormat(OperandVector &Operands) {
8016 SMLoc Loc = getLoc();
8017 int64_t Format;
8018 ParseStatus Res = parseSymbolicOrNumericFormat(Format);
8019 if (!Res.isSuccess())
8020 return Res;
8021
8022 Operands.push_back(
8023 AMDGPUOperand::CreateImm(this, Format, Loc, AMDGPUOperand::ImmTyFormat));
8024 return ParseStatus::Success;
8025}
8026
8027ParseStatus AMDGPUAsmParser::parseFormatOp(OperandVector &Operands) {
8028 SMLoc Loc = getLoc();
8029 int64_t Format;
8030 ParseStatus Res = isGFX10Plus() ? parseUfmt(Format) : parseDfmtNfmt(Format);
8031 if (!Res.isSuccess())
8032 return Res;
8033
8034 Operands.push_back(AMDGPUOperand::CreateImm(this, Format, Loc,
8035 AMDGPUOperand::ImmTyFormatOp));
8036 return ParseStatus::Success;
8037}
8038
8039ParseStatus AMDGPUAsmParser::parseFlatOffset(OperandVector &Operands) {
8040 ParseStatus Res =
8041 parseIntWithPrefix("offset", Operands, AMDGPUOperand::ImmTyOffset);
8042 if (Res.isNoMatch()) {
8043 Res = parseIntWithPrefix("inst_offset", Operands,
8044 AMDGPUOperand::ImmTyInstOffset);
8045 }
8046 return Res;
8047}
8048
8049ParseStatus AMDGPUAsmParser::parseR128A16(OperandVector &Operands) {
8050 ParseStatus Res =
8051 parseNamedBit("r128", Operands, AMDGPUOperand::ImmTyR128A16);
8052 if (Res.isNoMatch())
8053 Res = parseNamedBit("a16", Operands, AMDGPUOperand::ImmTyA16);
8054 return Res;
8055}
8056
8057ParseStatus AMDGPUAsmParser::parseBLGP(OperandVector &Operands) {
8058 ParseStatus Res =
8059 parseIntWithPrefix("blgp", Operands, AMDGPUOperand::ImmTyBLGP);
8060 if (Res.isNoMatch()) {
8061 Res =
8062 parseOperandArrayWithPrefix("neg", Operands, AMDGPUOperand::ImmTyBLGP);
8063 }
8064 return Res;
8065}
8066
8067//===----------------------------------------------------------------------===//
8068// Exp
8069//===----------------------------------------------------------------------===//
8070
8071void AMDGPUAsmParser::cvtExp(MCInst &Inst, const OperandVector &Operands) {
8072 OptionalImmIndexMap OptionalIdx;
8073
8074 unsigned OperandIdx[4];
8075 unsigned EnMask = 0;
8076 int SrcIdx = 0;
8077
8078 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
8079 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
8080
8081 // Add the register arguments
8082 if (Op.isReg()) {
8083 assert(SrcIdx < 4);
8084 OperandIdx[SrcIdx] = Inst.size();
8085 Op.addRegOperands(Inst, 1);
8086 ++SrcIdx;
8087 continue;
8088 }
8089
8090 if (Op.isOff()) {
8091 assert(SrcIdx < 4);
8092 OperandIdx[SrcIdx] = Inst.size();
8093 Inst.addOperand(MCOperand::createReg(MCRegister()));
8094 ++SrcIdx;
8095 continue;
8096 }
8097
8098 if (Op.isImm() && Op.getImmTy() == AMDGPUOperand::ImmTyExpTgt) {
8099 Op.addImmOperands(Inst, 1);
8100 continue;
8101 }
8102
8103 if (Op.isToken() && (Op.getToken() == "done" || Op.getToken() == "row_en"))
8104 continue;
8105
8106 // Handle optional arguments
8107 OptionalIdx[Op.getImmTy()] = i;
8108 }
8109
8110 assert(SrcIdx == 4);
8111
8112 bool Compr = false;
8113 if (OptionalIdx.find(AMDGPUOperand::ImmTyExpCompr) != OptionalIdx.end()) {
8114 Compr = true;
8115 Inst.getOperand(OperandIdx[1]) = Inst.getOperand(OperandIdx[2]);
8116 Inst.getOperand(OperandIdx[2]).setReg(MCRegister());
8117 Inst.getOperand(OperandIdx[3]).setReg(MCRegister());
8118 }
8119
8120 for (auto i = 0; i < SrcIdx; ++i) {
8121 if (Inst.getOperand(OperandIdx[i]).getReg()) {
8122 EnMask |= Compr ? (0x3 << i * 2) : (0x1 << i);
8123 }
8124 }
8125
8126 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyExpVM);
8127 addOptionalImmOperand(Inst, Operands, OptionalIdx,
8128 AMDGPUOperand::ImmTyExpCompr);
8129
8130 Inst.addOperand(MCOperand::createImm(EnMask));
8131}
8132
8133//===----------------------------------------------------------------------===//
8134// s_waitcnt
8135//===----------------------------------------------------------------------===//
8136
8137static bool encodeCnt(const AMDGPU::IsaVersion ISA, int64_t &IntVal,
8138 int64_t CntVal, bool Saturate,
8139 unsigned (*encode)(const IsaVersion &Version, unsigned,
8140 unsigned),
8141 unsigned (*decode)(const IsaVersion &Version, unsigned)) {
8142 bool Failed = false;
8143
8144 IntVal = encode(ISA, IntVal, CntVal);
8145 if (CntVal != decode(ISA, IntVal)) {
8146 if (Saturate) {
8147 IntVal = encode(ISA, IntVal, -1);
8148 } else {
8149 Failed = true;
8150 }
8151 }
8152 return Failed;
8153}
8154
8155bool AMDGPUAsmParser::parseCnt(int64_t &IntVal) {
8156
8157 SMLoc CntLoc = getLoc();
8158 StringRef CntName = getTokenStr();
8159
8160 if (!skipToken(AsmToken::Identifier, "expected a counter name") ||
8161 !skipToken(AsmToken::LParen, "expected a left parenthesis"))
8162 return false;
8163
8164 int64_t CntVal;
8165 SMLoc ValLoc = getLoc();
8166 if (!parseExpr(CntVal))
8167 return false;
8168
8169 bool Failed = true;
8170 bool Sat = CntName.ends_with("_sat");
8171
8172 if (CntName == "vmcnt" || CntName == "vmcnt_sat") {
8173 Failed = encodeCnt(ISA, IntVal, CntVal, Sat, encodeVmcnt, decodeVmcnt);
8174 } else if (CntName == "expcnt" || CntName == "expcnt_sat") {
8175 Failed = encodeCnt(ISA, IntVal, CntVal, Sat, encodeExpcnt, decodeExpcnt);
8176 } else if (CntName == "lgkmcnt" || CntName == "lgkmcnt_sat") {
8177 Failed = encodeCnt(ISA, IntVal, CntVal, Sat, encodeLgkmcnt, decodeLgkmcnt);
8178 } else {
8179 Error(CntLoc, "invalid counter name " + CntName);
8180 return false;
8181 }
8182
8183 if (Failed) {
8184 Error(ValLoc, "too large value for " + CntName);
8185 return false;
8186 }
8187
8188 if (!skipToken(AsmToken::RParen, "expected a closing parenthesis"))
8189 return false;
8190
8191 if (trySkipToken(AsmToken::Amp) || trySkipToken(AsmToken::Comma)) {
8192 if (isToken(AsmToken::EndOfStatement)) {
8193 Error(getLoc(), "expected a counter name");
8194 return false;
8195 }
8196 }
8197
8198 return true;
8199}
8200
8201ParseStatus AMDGPUAsmParser::parseSWaitCnt(OperandVector &Operands) {
8202 int64_t Waitcnt = getWaitcntBitMask(ISA);
8203 SMLoc S = getLoc();
8204
8205 if (isToken(AsmToken::Identifier) && peekToken().is(AsmToken::LParen)) {
8206 while (!isToken(AsmToken::EndOfStatement)) {
8207 if (!parseCnt(Waitcnt))
8208 return ParseStatus::Failure;
8209 }
8210 } else {
8211 if (!parseExpr(Waitcnt))
8212 return ParseStatus::Failure;
8213 }
8214
8215 Operands.push_back(AMDGPUOperand::CreateImm(this, Waitcnt, S));
8216 return ParseStatus::Success;
8217}
8218
8219bool AMDGPUAsmParser::parseDelay(int64_t &Delay) {
8220 SMLoc FieldLoc = getLoc();
8221 StringRef FieldName = getTokenStr();
8222 if (!skipToken(AsmToken::Identifier, "expected a field name") ||
8223 !skipToken(AsmToken::LParen, "expected a left parenthesis"))
8224 return false;
8225
8226 SMLoc ValueLoc = getLoc();
8227 StringRef ValueName = getTokenStr();
8228 if (!skipToken(AsmToken::Identifier, "expected a value name") ||
8229 !skipToken(AsmToken::RParen, "expected a right parenthesis"))
8230 return false;
8231
8232 unsigned Shift;
8233 if (FieldName == "instid0") {
8234 Shift = 0;
8235 } else if (FieldName == "instskip") {
8236 Shift = 4;
8237 } else if (FieldName == "instid1") {
8238 Shift = 7;
8239 } else {
8240 Error(FieldLoc, "invalid field name " + FieldName);
8241 return false;
8242 }
8243
8244 int Value;
8245 if (Shift == 4) {
8246 // Parse values for instskip.
8247 Value = StringSwitch<int>(ValueName)
8248 .Case("SAME", 0)
8249 .Case("NEXT", 1)
8250 .Case("SKIP_1", 2)
8251 .Case("SKIP_2", 3)
8252 .Case("SKIP_3", 4)
8253 .Case("SKIP_4", 5)
8254 .Default(-1);
8255 } else {
8256 // Parse values for instid0 and instid1.
8257 Value = StringSwitch<int>(ValueName)
8258 .Case("NO_DEP", 0)
8259 .Case("VALU_DEP_1", 1)
8260 .Case("VALU_DEP_2", 2)
8261 .Case("VALU_DEP_3", 3)
8262 .Case("VALU_DEP_4", 4)
8263 .Case("TRANS32_DEP_1", 5)
8264 .Case("TRANS32_DEP_2", 6)
8265 .Case("TRANS32_DEP_3", 7)
8266 .Case("FMA_ACCUM_CYCLE_1", 8)
8267 .Case("SALU_CYCLE_1", 9)
8268 .Case("SALU_CYCLE_2", 10)
8269 .Case("SALU_CYCLE_3", 11)
8270 .Default(-1);
8271 }
8272 if (Value < 0) {
8273 Error(ValueLoc, "invalid value name " + ValueName);
8274 return false;
8275 }
8276
8277 Delay |= Value << Shift;
8278 return true;
8279}
8280
8281ParseStatus AMDGPUAsmParser::parseSDelayALU(OperandVector &Operands) {
8282 int64_t Delay = 0;
8283 SMLoc S = getLoc();
8284
8285 if (isToken(AsmToken::Identifier) && peekToken().is(AsmToken::LParen)) {
8286 do {
8287 if (!parseDelay(Delay))
8288 return ParseStatus::Failure;
8289 } while (trySkipToken(AsmToken::Pipe));
8290 } else {
8291 if (!parseExpr(Delay))
8292 return ParseStatus::Failure;
8293 }
8294
8295 Operands.push_back(AMDGPUOperand::CreateImm(this, Delay, S));
8296 return ParseStatus::Success;
8297}
8298
8299bool AMDGPUOperand::isSWaitCnt() const { return isImm(); }
8300
8301bool AMDGPUOperand::isSDelayALU() const { return isImm(); }
8302
8303//===----------------------------------------------------------------------===//
8304// DepCtr
8305//===----------------------------------------------------------------------===//
8306
8307void AMDGPUAsmParser::depCtrError(SMLoc Loc, int ErrorId,
8308 StringRef DepCtrName) {
8309 switch (ErrorId) {
8310 case OPR_ID_UNKNOWN:
8311 Error(Loc, Twine("invalid counter name ", DepCtrName));
8312 return;
8313 case OPR_ID_UNSUPPORTED:
8314 Error(Loc, Twine(DepCtrName, " is not supported on this GPU"));
8315 return;
8316 case OPR_ID_DUPLICATE:
8317 Error(Loc, Twine("duplicate counter name ", DepCtrName));
8318 return;
8319 case OPR_VAL_INVALID:
8320 Error(Loc, Twine("invalid value for ", DepCtrName));
8321 return;
8322 default:
8323 assert(false);
8324 }
8325}
8326
8327bool AMDGPUAsmParser::parseDepCtr(int64_t &DepCtr, unsigned &UsedOprMask) {
8328
8329 using namespace llvm::AMDGPU::DepCtr;
8330
8331 SMLoc DepCtrLoc = getLoc();
8332 StringRef DepCtrName = getTokenStr();
8333
8334 if (!skipToken(AsmToken::Identifier, "expected a counter name") ||
8335 !skipToken(AsmToken::LParen, "expected a left parenthesis"))
8336 return false;
8337
8338 int64_t ExprVal;
8339 if (!parseExpr(ExprVal))
8340 return false;
8341
8342 unsigned PrevOprMask = UsedOprMask;
8343 int CntVal = encodeDepCtr(DepCtrName, ExprVal, UsedOprMask, getSTI());
8344
8345 if (CntVal < 0) {
8346 depCtrError(DepCtrLoc, CntVal, DepCtrName);
8347 return false;
8348 }
8349
8350 if (!skipToken(AsmToken::RParen, "expected a closing parenthesis"))
8351 return false;
8352
8353 if (trySkipToken(AsmToken::Amp) || trySkipToken(AsmToken::Comma)) {
8354 if (isToken(AsmToken::EndOfStatement)) {
8355 Error(getLoc(), "expected a counter name");
8356 return false;
8357 }
8358 }
8359
8360 int64_t CntValMask = PrevOprMask ^ UsedOprMask;
8361 DepCtr = (DepCtr & ~CntValMask) | CntVal;
8362 return true;
8363}
8364
8365ParseStatus AMDGPUAsmParser::parseDepCtr(OperandVector &Operands) {
8366 using namespace llvm::AMDGPU::DepCtr;
8367
8368 int64_t DepCtr = getDefaultDepCtrEncoding(getSTI());
8369 SMLoc Loc = getLoc();
8370
8371 if (isToken(AsmToken::Identifier) && peekToken().is(AsmToken::LParen)) {
8372 unsigned UsedOprMask = 0;
8373 while (!isToken(AsmToken::EndOfStatement)) {
8374 if (!parseDepCtr(DepCtr, UsedOprMask))
8375 return ParseStatus::Failure;
8376 }
8377 } else {
8378 if (!parseExpr(DepCtr))
8379 return ParseStatus::Failure;
8380 }
8381
8382 Operands.push_back(AMDGPUOperand::CreateImm(this, DepCtr, Loc));
8383 return ParseStatus::Success;
8384}
8385
8386bool AMDGPUOperand::isDepCtr() const { return isS16Imm(); }
8387
8388//===----------------------------------------------------------------------===//
8389// hwreg
8390//===----------------------------------------------------------------------===//
8391
8392ParseStatus AMDGPUAsmParser::parseHwregFunc(OperandInfoTy &HwReg,
8393 OperandInfoTy &Offset,
8394 OperandInfoTy &Width) {
8395 using namespace llvm::AMDGPU::Hwreg;
8396
8397 if (!trySkipId("hwreg", AsmToken::LParen))
8398 return ParseStatus::NoMatch;
8399
8400 // The register may be specified by name or using a numeric code
8401 HwReg.Loc = getLoc();
8402 if (isToken(AsmToken::Identifier) &&
8403 (HwReg.Val = getHwregId(getTokenStr(), getSTI())) != OPR_ID_UNKNOWN) {
8404 HwReg.IsSymbolic = true;
8405 lex(); // skip register name
8406 } else if (!parseExpr(HwReg.Val, "a register name")) {
8407 return ParseStatus::Failure;
8408 }
8409
8410 if (trySkipToken(AsmToken::RParen))
8411 return ParseStatus::Success;
8412
8413 // parse optional params
8414 if (!skipToken(AsmToken::Comma, "expected a comma or a closing parenthesis"))
8415 return ParseStatus::Failure;
8416
8417 Offset.Loc = getLoc();
8418 if (!parseExpr(Offset.Val))
8419 return ParseStatus::Failure;
8420
8421 if (!skipToken(AsmToken::Comma, "expected a comma"))
8422 return ParseStatus::Failure;
8423
8424 Width.Loc = getLoc();
8425 if (!parseExpr(Width.Val) ||
8426 !skipToken(AsmToken::RParen, "expected a closing parenthesis"))
8427 return ParseStatus::Failure;
8428
8429 return ParseStatus::Success;
8430}
8431
8432ParseStatus AMDGPUAsmParser::parseHwreg(OperandVector &Operands) {
8433 using namespace llvm::AMDGPU::Hwreg;
8434
8435 int64_t ImmVal = 0;
8436 SMLoc Loc = getLoc();
8437
8438 StructuredOpField HwReg("id", "hardware register", HwregId::Width,
8439 HwregId::Default);
8440 StructuredOpField Offset("offset", "bit offset", HwregOffset::Width,
8441 HwregOffset::Default);
8442 struct : StructuredOpField {
8443 using StructuredOpField::StructuredOpField;
8444 bool validate(AMDGPUAsmParser &Parser) const override {
8445 if (!isUIntN(Width, Val - 1))
8446 return Error(Parser, "only values from 1 to 32 are legal");
8447 return true;
8448 }
8449 } Width("size", "bitfield width", HwregSize::Width, HwregSize::Default);
8450 ParseStatus Res = parseStructuredOpFields({&HwReg, &Offset, &Width});
8451
8452 if (Res.isNoMatch())
8453 Res = parseHwregFunc(HwReg, Offset, Width);
8454
8455 if (Res.isSuccess()) {
8456 if (!validateStructuredOpFields({&HwReg, &Offset, &Width}))
8457 return ParseStatus::Failure;
8458 ImmVal = HwregEncoding::encode(HwReg.Val, Offset.Val, Width.Val);
8459 }
8460
8461 if (Res.isNoMatch() &&
8462 parseExpr(ImmVal, "a hwreg macro, structured immediate"))
8464
8465 if (!Res.isSuccess())
8466 return ParseStatus::Failure;
8467
8468 if (!isUInt<16>(ImmVal))
8469 return Error(Loc, "invalid immediate: only 16-bit values are legal");
8470 Operands.push_back(
8471 AMDGPUOperand::CreateImm(this, ImmVal, Loc, AMDGPUOperand::ImmTyHwreg));
8472 return ParseStatus::Success;
8473}
8474
8475bool AMDGPUOperand::isHwreg() const { return isImmTy(ImmTyHwreg); }
8476
8477//===----------------------------------------------------------------------===//
8478// sendmsg
8479//===----------------------------------------------------------------------===//
8480
8481bool AMDGPUAsmParser::parseSendMsgBody(OperandInfoTy &Msg, OperandInfoTy &Op,
8482 OperandInfoTy &Stream) {
8483 using namespace llvm::AMDGPU::SendMsg;
8484
8485 Msg.Loc = getLoc();
8486 if (isToken(AsmToken::Identifier) &&
8487 (Msg.Val = getMsgId(getTokenStr(), getSTI())) != OPR_ID_UNKNOWN) {
8488 Msg.IsSymbolic = true;
8489 lex(); // skip message name
8490 } else if (!parseExpr(Msg.Val, "a message name")) {
8491 return false;
8492 }
8493
8494 if (trySkipToken(AsmToken::Comma)) {
8495 Op.IsDefined = true;
8496 Op.Loc = getLoc();
8497 if (isToken(AsmToken::Identifier) &&
8498 (Op.Val = getMsgOpId(Msg.Val, getTokenStr(), getSTI())) !=
8500 lex(); // skip operation name
8501 } else if (!parseExpr(Op.Val, "an operation name")) {
8502 return false;
8503 }
8504
8505 if (trySkipToken(AsmToken::Comma)) {
8506 Stream.IsDefined = true;
8507 Stream.Loc = getLoc();
8508 if (!parseExpr(Stream.Val))
8509 return false;
8510 }
8511 }
8512
8513 return skipToken(AsmToken::RParen, "expected a closing parenthesis");
8514}
8515
8516bool AMDGPUAsmParser::validateSendMsg(const OperandInfoTy &Msg,
8517 const OperandInfoTy &Op,
8518 const OperandInfoTy &Stream) {
8519 using namespace llvm::AMDGPU::SendMsg;
8520
8521 // Validation strictness depends on whether message is specified
8522 // in a symbolic or in a numeric form. In the latter case
8523 // only encoding possibility is checked.
8524 bool Strict = Msg.IsSymbolic;
8525
8526 if (Strict) {
8527 if (Msg.Val == OPR_ID_UNSUPPORTED) {
8528 Error(Msg.Loc, "specified message id is not supported on this GPU");
8529 return false;
8530 }
8531 } else {
8532 if (!isValidMsgId(Msg.Val, getSTI())) {
8533 Error(Msg.Loc, "invalid message id");
8534 return false;
8535 }
8536 }
8537 if (Strict && (msgRequiresOp(Msg.Val, getSTI()) != Op.IsDefined)) {
8538 if (Op.IsDefined) {
8539 Error(Op.Loc, "message does not support operations");
8540 } else {
8541 Error(Msg.Loc, "missing message operation");
8542 }
8543 return false;
8544 }
8545 if (!isValidMsgOp(Msg.Val, Op.Val, getSTI(), Strict)) {
8546 if (Op.Val == OPR_ID_UNSUPPORTED)
8547 Error(Op.Loc, "specified operation id is not supported on this GPU");
8548 else
8549 Error(Op.Loc, "invalid operation id");
8550 return false;
8551 }
8552 if (Strict && !msgSupportsStream(Msg.Val, Op.Val, getSTI()) &&
8553 Stream.IsDefined) {
8554 Error(Stream.Loc, "message operation does not support streams");
8555 return false;
8556 }
8557 if (!isValidMsgStream(Msg.Val, Op.Val, Stream.Val, getSTI(), Strict)) {
8558 Error(Stream.Loc, "invalid message stream id");
8559 return false;
8560 }
8561 return true;
8562}
8563
8564ParseStatus AMDGPUAsmParser::parseSendMsg(OperandVector &Operands) {
8565 using namespace llvm::AMDGPU::SendMsg;
8566
8567 int64_t ImmVal = 0;
8568 SMLoc Loc = getLoc();
8569
8570 if (trySkipId("sendmsg", AsmToken::LParen)) {
8571 OperandInfoTy Msg(OPR_ID_UNKNOWN);
8572 OperandInfoTy Op(OP_NONE_);
8573 OperandInfoTy Stream(STREAM_ID_NONE_);
8574 if (parseSendMsgBody(Msg, Op, Stream) && validateSendMsg(Msg, Op, Stream)) {
8575 ImmVal = encodeMsg(Msg.Val, Op.Val, Stream.Val);
8576 } else {
8577 return ParseStatus::Failure;
8578 }
8579 } else if (parseExpr(ImmVal, "a sendmsg macro")) {
8580 if (ImmVal < 0 || !isUInt<16>(ImmVal))
8581 return Error(Loc, "invalid immediate: only 16-bit values are legal");
8582 } else {
8583 return ParseStatus::Failure;
8584 }
8585
8586 Operands.push_back(
8587 AMDGPUOperand::CreateImm(this, ImmVal, Loc, AMDGPUOperand::ImmTySendMsg));
8588 return ParseStatus::Success;
8589}
8590
8591bool AMDGPUOperand::isSendMsg() const { return isImmTy(ImmTySendMsg); }
8592
8593ParseStatus AMDGPUAsmParser::parseWaitEvent(OperandVector &Operands) {
8594 using namespace llvm::AMDGPU::WaitEvent;
8595
8596 SMLoc Loc = getLoc();
8597 int64_t ImmVal = 0;
8598
8599 StructuredOpField DontWaitExportReady("dont_wait_export_ready", "bit value",
8600 1, 0);
8601 StructuredOpField ExportReady("export_ready", "bit value", 1, 0);
8602
8603 StructuredOpField *TargetBitfield =
8604 isGFX11() ? &DontWaitExportReady : &ExportReady;
8605
8606 ParseStatus Res = parseStructuredOpFields({TargetBitfield});
8607 if (Res.isNoMatch() && parseExpr(ImmVal, "structured immediate"))
8609 else if (Res.isSuccess()) {
8610 if (!validateStructuredOpFields({TargetBitfield}))
8611 return ParseStatus::Failure;
8612 ImmVal = TargetBitfield->Val;
8613 }
8614
8615 if (!Res.isSuccess())
8616 return ParseStatus::Failure;
8617
8618 if (!isUInt<16>(ImmVal))
8619 return Error(Loc, "invalid immediate: only 16-bit values are legal");
8620
8621 Operands.push_back(AMDGPUOperand::CreateImm(this, ImmVal, Loc,
8622 AMDGPUOperand::ImmTyWaitEvent));
8623 return ParseStatus::Success;
8624}
8625
8626bool AMDGPUOperand::isWaitEvent() const { return isImmTy(ImmTyWaitEvent); }
8627
8628//===----------------------------------------------------------------------===//
8629// v_interp
8630//===----------------------------------------------------------------------===//
8631
8632ParseStatus AMDGPUAsmParser::parseInterpSlot(OperandVector &Operands) {
8633 StringRef Str;
8634 SMLoc S = getLoc();
8635
8636 if (!parseId(Str))
8637 return ParseStatus::NoMatch;
8638
8639 int Slot = StringSwitch<int>(Str)
8640 .Case("p10", 0)
8641 .Case("p20", 1)
8642 .Case("p0", 2)
8643 .Default(-1);
8644
8645 if (Slot == -1)
8646 return Error(S, "invalid interpolation slot");
8647
8648 Operands.push_back(
8649 AMDGPUOperand::CreateImm(this, Slot, S, AMDGPUOperand::ImmTyInterpSlot));
8650 return ParseStatus::Success;
8651}
8652
8653ParseStatus AMDGPUAsmParser::parseInterpAttr(OperandVector &Operands) {
8654 StringRef Str;
8655 SMLoc S = getLoc();
8656
8657 if (!parseId(Str))
8658 return ParseStatus::NoMatch;
8659
8660 if (!Str.starts_with("attr"))
8661 return Error(S, "invalid interpolation attribute");
8662
8663 StringRef Chan = Str.take_back(2);
8664 int AttrChan = StringSwitch<int>(Chan)
8665 .Case(".x", 0)
8666 .Case(".y", 1)
8667 .Case(".z", 2)
8668 .Case(".w", 3)
8669 .Default(-1);
8670 if (AttrChan == -1)
8671 return Error(S, "invalid or missing interpolation attribute channel");
8672
8673 Str = Str.drop_back(2).drop_front(4);
8674
8675 uint8_t Attr;
8676 if (Str.getAsInteger(10, Attr))
8677 return Error(S, "invalid or missing interpolation attribute number");
8678
8679 if (Attr > 32)
8680 return Error(S, "out of bounds interpolation attribute number");
8681
8682 SMLoc SChan = SMLoc::getFromPointer(Chan.data());
8683
8684 Operands.push_back(
8685 AMDGPUOperand::CreateImm(this, Attr, S, AMDGPUOperand::ImmTyInterpAttr));
8686 Operands.push_back(AMDGPUOperand::CreateImm(
8687 this, AttrChan, SChan, AMDGPUOperand::ImmTyInterpAttrChan));
8688 return ParseStatus::Success;
8689}
8690
8691//===----------------------------------------------------------------------===//
8692// exp
8693//===----------------------------------------------------------------------===//
8694
8695ParseStatus AMDGPUAsmParser::parseExpTgt(OperandVector &Operands) {
8696 using namespace llvm::AMDGPU::Exp;
8697
8698 StringRef Str;
8699 SMLoc S = getLoc();
8700
8701 if (!parseId(Str))
8702 return ParseStatus::NoMatch;
8703
8704 unsigned Id = getTgtId(Str);
8705 if (Id == ET_INVALID || !isSupportedTgtId(Id, getSTI()))
8706 return Error(S, (Id == ET_INVALID)
8707 ? "invalid exp target"
8708 : "exp target is not supported on this GPU");
8709
8710 Operands.push_back(
8711 AMDGPUOperand::CreateImm(this, Id, S, AMDGPUOperand::ImmTyExpTgt));
8712 return ParseStatus::Success;
8713}
8714
8715//===----------------------------------------------------------------------===//
8716// parser helpers
8717//===----------------------------------------------------------------------===//
8718
8719bool AMDGPUAsmParser::isId(const AsmToken &Token, const StringRef Id) const {
8720 return Token.is(AsmToken::Identifier) && Token.getString() == Id;
8721}
8722
8723bool AMDGPUAsmParser::isId(const StringRef Id) const {
8724 return isId(getToken(), Id);
8725}
8726
8727bool AMDGPUAsmParser::isToken(const AsmToken::TokenKind Kind) const {
8728 return getTokenKind() == Kind;
8729}
8730
8731StringRef AMDGPUAsmParser::getId() const {
8732 return isToken(AsmToken::Identifier) ? getTokenStr() : StringRef();
8733}
8734
8735bool AMDGPUAsmParser::trySkipId(const StringRef Id) {
8736 if (isId(Id)) {
8737 lex();
8738 return true;
8739 }
8740 return false;
8741}
8742
8743bool AMDGPUAsmParser::trySkipId(const StringRef Pref, const StringRef Id) {
8744 if (isToken(AsmToken::Identifier)) {
8745 StringRef Tok = getTokenStr();
8746 if (Tok.starts_with(Pref) && Tok.drop_front(Pref.size()) == Id) {
8747 lex();
8748 return true;
8749 }
8750 }
8751 return false;
8752}
8753
8754bool AMDGPUAsmParser::trySkipId(const StringRef Id,
8755 const AsmToken::TokenKind Kind) {
8756 if (isId(Id) && peekToken().is(Kind)) {
8757 lex();
8758 lex();
8759 return true;
8760 }
8761 return false;
8762}
8763
8764bool AMDGPUAsmParser::trySkipToken(const AsmToken::TokenKind Kind) {
8765 if (isToken(Kind)) {
8766 lex();
8767 return true;
8768 }
8769 return false;
8770}
8771
8772bool AMDGPUAsmParser::skipToken(const AsmToken::TokenKind Kind,
8773 const StringRef ErrMsg) {
8774 if (!trySkipToken(Kind)) {
8775 Error(getLoc(), ErrMsg);
8776 return false;
8777 }
8778 return true;
8779}
8780
8781bool AMDGPUAsmParser::parseExpr(int64_t &Imm, StringRef Expected) {
8782 SMLoc S = getLoc();
8783
8784 const MCExpr *Expr;
8785 if (Parser.parseExpression(Expr))
8786 return false;
8787
8788 if (Expr->evaluateAsAbsolute(Imm))
8789 return true;
8790
8791 if (Expected.empty()) {
8792 Error(S, "expected absolute expression");
8793 } else {
8794 Error(S,
8795 Twine("expected ", Expected) + Twine(" or an absolute expression"));
8796 }
8797 return false;
8798}
8799
8800bool AMDGPUAsmParser::parseExpr(OperandVector &Operands) {
8801 SMLoc S = getLoc();
8802
8803 const MCExpr *Expr;
8804 if (Parser.parseExpression(Expr))
8805 return false;
8806
8807 int64_t IntVal;
8808 if (Expr->evaluateAsAbsolute(IntVal)) {
8809 Operands.push_back(AMDGPUOperand::CreateImm(this, IntVal, S));
8810 } else {
8811 Operands.push_back(AMDGPUOperand::CreateExpr(this, Expr, S));
8812 }
8813 return true;
8814}
8815
8816bool AMDGPUAsmParser::parseString(StringRef &Val, const StringRef ErrMsg) {
8817 if (isToken(AsmToken::String)) {
8818 Val = getToken().getStringContents();
8819 lex();
8820 return true;
8821 }
8822 Error(getLoc(), ErrMsg);
8823 return false;
8824}
8825
8826bool AMDGPUAsmParser::parseId(StringRef &Val, const StringRef ErrMsg) {
8827 if (isToken(AsmToken::Identifier)) {
8828 Val = getTokenStr();
8829 lex();
8830 return true;
8831 }
8832 if (!ErrMsg.empty())
8833 Error(getLoc(), ErrMsg);
8834 return false;
8835}
8836
8837AsmToken AMDGPUAsmParser::getToken() const { return Parser.getTok(); }
8838
8839AsmToken AMDGPUAsmParser::peekToken(bool ShouldSkipSpace) {
8840 return isToken(AsmToken::EndOfStatement)
8841 ? getToken()
8842 : getLexer().peekTok(ShouldSkipSpace);
8843}
8844
8845void AMDGPUAsmParser::peekTokens(MutableArrayRef<AsmToken> Tokens) {
8846 auto TokCount = getLexer().peekTokens(Tokens);
8847
8848 for (auto Idx = TokCount; Idx < Tokens.size(); ++Idx)
8849 Tokens[Idx] = AsmToken(AsmToken::Error, "");
8850}
8851
8852AsmToken::TokenKind AMDGPUAsmParser::getTokenKind() const {
8853 return getLexer().getKind();
8854}
8855
8856SMLoc AMDGPUAsmParser::getLoc() const { return getToken().getLoc(); }
8857
8858StringRef AMDGPUAsmParser::getTokenStr() const {
8859 return getToken().getString();
8860}
8861
8862void AMDGPUAsmParser::lex() { Parser.Lex(); }
8863
8864const AMDGPUOperand &
8865AMDGPUAsmParser::findMCOperand(const OperandVector &Operands,
8866 int MCOpIdx) const {
8867 for (const auto &Op : Operands) {
8868 const AMDGPUOperand &TargetOp = static_cast<AMDGPUOperand &>(*Op);
8869 if (TargetOp.getMCOpIdx() == MCOpIdx)
8870 return TargetOp;
8871 }
8872 llvm_unreachable("no such MC operand!");
8873}
8874
8875SMLoc AMDGPUAsmParser::getInstLoc(const OperandVector &Operands) const {
8876 return ((AMDGPUOperand &)*Operands[0]).getStartLoc();
8877}
8878
8879// Returns one of the given locations that comes later in the source.
8880SMLoc AMDGPUAsmParser::getLaterLoc(SMLoc a, SMLoc b) {
8881 return a.getPointer() < b.getPointer() ? b : a;
8882}
8883
8884SMLoc AMDGPUAsmParser::getOperandLoc(const OperandVector &Operands,
8885 int MCOpIdx) const {
8886 return findMCOperand(Operands, MCOpIdx).getStartLoc();
8887}
8888
8889SMLoc AMDGPUAsmParser::getOperandLoc(
8890 std::function<bool(const AMDGPUOperand &)> Test,
8891 const OperandVector &Operands) const {
8892 for (unsigned i = Operands.size() - 1; i > 0; --i) {
8893 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
8894 if (Test(Op))
8895 return Op.getStartLoc();
8896 }
8897 return getInstLoc(Operands);
8898}
8899
8900SMLoc AMDGPUAsmParser::getImmLoc(AMDGPUOperand::ImmTy Type,
8901 const OperandVector &Operands) const {
8902 auto Test = [=](const AMDGPUOperand &Op) { return Op.isImmTy(Type); };
8903 return getOperandLoc(Test, Operands);
8904}
8905
8906ParseStatus
8907AMDGPUAsmParser::parseStructuredOpFields(ArrayRef<StructuredOpField *> Fields) {
8908 if (!trySkipToken(AsmToken::LCurly))
8909 return ParseStatus::NoMatch;
8910
8911 bool First = true;
8912 while (!trySkipToken(AsmToken::RCurly)) {
8913 if (!First &&
8914 !skipToken(AsmToken::Comma, "comma or closing brace expected"))
8915 return ParseStatus::Failure;
8916
8917 StringRef Id = getTokenStr();
8918 SMLoc IdLoc = getLoc();
8919 if (!skipToken(AsmToken::Identifier, "field name expected") ||
8920 !skipToken(AsmToken::Colon, "colon expected"))
8921 return ParseStatus::Failure;
8922
8923 const auto *I =
8924 find_if(Fields, [Id](StructuredOpField *F) { return F->Id == Id; });
8925 if (I == Fields.end())
8926 return Error(IdLoc, "unknown field");
8927 if ((*I)->IsDefined)
8928 return Error(IdLoc, "duplicate field");
8929
8930 // TODO: Support symbolic values.
8931 (*I)->Loc = getLoc();
8932 if (!parseExpr((*I)->Val))
8933 return ParseStatus::Failure;
8934 (*I)->IsDefined = true;
8935
8936 First = false;
8937 }
8938 return ParseStatus::Success;
8939}
8940
8941bool AMDGPUAsmParser::validateStructuredOpFields(
8943 return all_of(Fields, [this](const StructuredOpField *F) {
8944 return F->validate(*this);
8945 });
8946}
8947
8948//===----------------------------------------------------------------------===//
8949// swizzle
8950//===----------------------------------------------------------------------===//
8951
8953static unsigned encodeBitmaskPerm(const unsigned AndMask, const unsigned OrMask,
8954 const unsigned XorMask) {
8955 using namespace llvm::AMDGPU::Swizzle;
8956
8957 return BITMASK_PERM_ENC | (AndMask << BITMASK_AND_SHIFT) |
8958 (OrMask << BITMASK_OR_SHIFT) | (XorMask << BITMASK_XOR_SHIFT);
8959}
8960
8961bool AMDGPUAsmParser::parseSwizzleOperand(int64_t &Op, const unsigned MinVal,
8962 const unsigned MaxVal,
8963 const Twine &ErrMsg, SMLoc &Loc) {
8964 if (!skipToken(AsmToken::Comma, "expected a comma")) {
8965 return false;
8966 }
8967 Loc = getLoc();
8968 if (!parseExpr(Op)) {
8969 return false;
8970 }
8971 if (Op < MinVal || Op > MaxVal) {
8972 Error(Loc, ErrMsg);
8973 return false;
8974 }
8975
8976 return true;
8977}
8978
8979bool AMDGPUAsmParser::parseSwizzleOperands(const unsigned OpNum, int64_t *Op,
8980 const unsigned MinVal,
8981 const unsigned MaxVal,
8982 const StringRef ErrMsg) {
8983 SMLoc Loc;
8984 for (unsigned i = 0; i < OpNum; ++i) {
8985 if (!parseSwizzleOperand(Op[i], MinVal, MaxVal, ErrMsg, Loc))
8986 return false;
8987 }
8988
8989 return true;
8990}
8991
8992bool AMDGPUAsmParser::parseSwizzleQuadPerm(int64_t &Imm) {
8993 using namespace llvm::AMDGPU::Swizzle;
8994
8995 int64_t Lane[LANE_NUM];
8996 if (parseSwizzleOperands(LANE_NUM, Lane, 0, LANE_MAX,
8997 "expected a 2-bit lane id")) {
8999 for (unsigned I = 0; I < LANE_NUM; ++I) {
9000 Imm |= Lane[I] << (LANE_SHIFT * I);
9001 }
9002 return true;
9003 }
9004 return false;
9005}
9006
9007bool AMDGPUAsmParser::parseSwizzleBroadcast(int64_t &Imm) {
9008 using namespace llvm::AMDGPU::Swizzle;
9009
9010 SMLoc Loc;
9011 int64_t GroupSize;
9012 int64_t LaneIdx;
9013
9014 if (!parseSwizzleOperand(GroupSize, 2, 32,
9015 "group size must be in the interval [2,32]", Loc)) {
9016 return false;
9017 }
9018 if (!isPowerOf2_64(GroupSize)) {
9019 Error(Loc, "group size must be a power of two");
9020 return false;
9021 }
9022 if (parseSwizzleOperand(LaneIdx, 0, GroupSize - 1,
9023 "lane id must be in the interval [0,group size - 1]",
9024 Loc)) {
9025 Imm = encodeBitmaskPerm(BITMASK_MAX - GroupSize + 1, LaneIdx, 0);
9026 return true;
9027 }
9028 return false;
9029}
9030
9031bool AMDGPUAsmParser::parseSwizzleReverse(int64_t &Imm) {
9032 using namespace llvm::AMDGPU::Swizzle;
9033
9034 SMLoc Loc;
9035 int64_t GroupSize;
9036
9037 if (!parseSwizzleOperand(GroupSize, 2, 32,
9038 "group size must be in the interval [2,32]", Loc)) {
9039 return false;
9040 }
9041 if (!isPowerOf2_64(GroupSize)) {
9042 Error(Loc, "group size must be a power of two");
9043 return false;
9044 }
9045
9046 Imm = encodeBitmaskPerm(BITMASK_MAX, 0, GroupSize - 1);
9047 return true;
9048}
9049
9050bool AMDGPUAsmParser::parseSwizzleSwap(int64_t &Imm) {
9051 using namespace llvm::AMDGPU::Swizzle;
9052
9053 SMLoc Loc;
9054 int64_t GroupSize;
9055
9056 if (!parseSwizzleOperand(GroupSize, 1, 16,
9057 "group size must be in the interval [1,16]", Loc)) {
9058 return false;
9059 }
9060 if (!isPowerOf2_64(GroupSize)) {
9061 Error(Loc, "group size must be a power of two");
9062 return false;
9063 }
9064
9065 Imm = encodeBitmaskPerm(BITMASK_MAX, 0, GroupSize);
9066 return true;
9067}
9068
9069bool AMDGPUAsmParser::parseSwizzleBitmaskPerm(int64_t &Imm) {
9070 using namespace llvm::AMDGPU::Swizzle;
9071
9072 if (!skipToken(AsmToken::Comma, "expected a comma")) {
9073 return false;
9074 }
9075
9076 StringRef Ctl;
9077 SMLoc StrLoc = getLoc();
9078 if (!parseString(Ctl)) {
9079 return false;
9080 }
9081 if (Ctl.size() != BITMASK_WIDTH) {
9082 Error(StrLoc, "expected a 5-character mask");
9083 return false;
9084 }
9085
9086 unsigned AndMask = 0;
9087 unsigned OrMask = 0;
9088 unsigned XorMask = 0;
9089
9090 for (size_t i = 0; i < Ctl.size(); ++i) {
9091 unsigned Mask = 1 << (BITMASK_WIDTH - 1 - i);
9092 switch (Ctl[i]) {
9093 default:
9094 Error(StrLoc, "invalid mask");
9095 return false;
9096 case '0':
9097 break;
9098 case '1':
9099 OrMask |= Mask;
9100 break;
9101 case 'p':
9102 AndMask |= Mask;
9103 break;
9104 case 'i':
9105 AndMask |= Mask;
9106 XorMask |= Mask;
9107 break;
9108 }
9109 }
9110
9111 Imm = encodeBitmaskPerm(AndMask, OrMask, XorMask);
9112 return true;
9113}
9114
9115bool AMDGPUAsmParser::parseSwizzleFFT(int64_t &Imm) {
9116 using namespace llvm::AMDGPU::Swizzle;
9117
9118 if (!AMDGPU::isGFX9Plus(getSTI())) {
9119 Error(getLoc(), "FFT mode swizzle not supported on this GPU");
9120 return false;
9121 }
9122
9123 int64_t Swizzle;
9124 SMLoc Loc;
9125 if (!parseSwizzleOperand(Swizzle, 0, FFT_SWIZZLE_MAX,
9126 "FFT swizzle must be in the interval [0," +
9127 Twine(FFT_SWIZZLE_MAX) + Twine(']'),
9128 Loc))
9129 return false;
9130
9131 Imm = FFT_MODE_ENC | Swizzle;
9132 return true;
9133}
9134
9135bool AMDGPUAsmParser::parseSwizzleRotate(int64_t &Imm) {
9136 using namespace llvm::AMDGPU::Swizzle;
9137
9138 if (!AMDGPU::isGFX9Plus(getSTI())) {
9139 Error(getLoc(), "Rotate mode swizzle not supported on this GPU");
9140 return false;
9141 }
9142
9143 SMLoc Loc;
9144 int64_t Direction;
9145
9146 if (!parseSwizzleOperand(Direction, 0, 1,
9147 "direction must be 0 (left) or 1 (right)", Loc))
9148 return false;
9149
9150 int64_t RotateSize;
9151 if (!parseSwizzleOperand(
9152 RotateSize, 0, ROTATE_MAX_SIZE,
9153 "number of threads to rotate must be in the interval [0," +
9154 Twine(ROTATE_MAX_SIZE) + Twine(']'),
9155 Loc))
9156 return false;
9157
9159 (RotateSize << ROTATE_SIZE_SHIFT);
9160 return true;
9161}
9162
9163bool AMDGPUAsmParser::parseSwizzleOffset(int64_t &Imm) {
9164
9165 SMLoc OffsetLoc = getLoc();
9166
9167 if (!parseExpr(Imm, "a swizzle macro")) {
9168 return false;
9169 }
9170 if (!isUInt<16>(Imm)) {
9171 Error(OffsetLoc, "expected a 16-bit offset");
9172 return false;
9173 }
9174 return true;
9175}
9176
9177bool AMDGPUAsmParser::parseSwizzleMacro(int64_t &Imm) {
9178 using namespace llvm::AMDGPU::Swizzle;
9179
9180 if (skipToken(AsmToken::LParen, "expected a left parentheses")) {
9181
9182 SMLoc ModeLoc = getLoc();
9183 bool Ok = false;
9184
9185 if (trySkipId(IdSymbolic[ID_QUAD_PERM])) {
9186 Ok = parseSwizzleQuadPerm(Imm);
9187 } else if (trySkipId(IdSymbolic[ID_BITMASK_PERM])) {
9188 Ok = parseSwizzleBitmaskPerm(Imm);
9189 } else if (trySkipId(IdSymbolic[ID_BROADCAST])) {
9190 Ok = parseSwizzleBroadcast(Imm);
9191 } else if (trySkipId(IdSymbolic[ID_SWAP])) {
9192 Ok = parseSwizzleSwap(Imm);
9193 } else if (trySkipId(IdSymbolic[ID_REVERSE])) {
9194 Ok = parseSwizzleReverse(Imm);
9195 } else if (trySkipId(IdSymbolic[ID_FFT])) {
9196 Ok = parseSwizzleFFT(Imm);
9197 } else if (trySkipId(IdSymbolic[ID_ROTATE])) {
9198 Ok = parseSwizzleRotate(Imm);
9199 } else {
9200 Error(ModeLoc, "expected a swizzle mode");
9201 }
9202
9203 return Ok && skipToken(AsmToken::RParen, "expected a closing parentheses");
9204 }
9205
9206 return false;
9207}
9208
9209ParseStatus AMDGPUAsmParser::parseSwizzle(OperandVector &Operands) {
9210 SMLoc S = getLoc();
9211 int64_t Imm = 0;
9212
9213 if (trySkipId("offset")) {
9214
9215 bool Ok = false;
9216 if (skipToken(AsmToken::Colon, "expected a colon")) {
9217 if (trySkipId("swizzle")) {
9218 Ok = parseSwizzleMacro(Imm);
9219 } else {
9220 Ok = parseSwizzleOffset(Imm);
9221 }
9222 }
9223
9224 Operands.push_back(
9225 AMDGPUOperand::CreateImm(this, Imm, S, AMDGPUOperand::ImmTySwizzle));
9226
9228 }
9229 return ParseStatus::NoMatch;
9230}
9231
9232bool AMDGPUOperand::isSwizzle() const { return isImmTy(ImmTySwizzle); }
9233
9234//===----------------------------------------------------------------------===//
9235// VGPR Index Mode
9236//===----------------------------------------------------------------------===//
9237
9238int64_t AMDGPUAsmParser::parseGPRIdxMacro() {
9239
9240 using namespace llvm::AMDGPU::VGPRIndexMode;
9241
9242 if (trySkipToken(AsmToken::RParen)) {
9243 return OFF;
9244 }
9245
9246 int64_t Imm = 0;
9247
9248 while (true) {
9249 unsigned Mode = 0;
9250 SMLoc S = getLoc();
9251
9252 for (unsigned ModeId = ID_MIN; ModeId <= ID_MAX; ++ModeId) {
9253 if (trySkipId(IdSymbolic[ModeId])) {
9254 Mode = 1 << ModeId;
9255 break;
9256 }
9257 }
9258
9259 if (Mode == 0) {
9260 Error(S, (Imm == 0)
9261 ? "expected a VGPR index mode or a closing parenthesis"
9262 : "expected a VGPR index mode");
9263 return UNDEF;
9264 }
9265
9266 if (Imm & Mode) {
9267 Error(S, "duplicate VGPR index mode");
9268 return UNDEF;
9269 }
9270 Imm |= Mode;
9271
9272 if (trySkipToken(AsmToken::RParen))
9273 break;
9274 if (!skipToken(AsmToken::Comma,
9275 "expected a comma or a closing parenthesis"))
9276 return UNDEF;
9277 }
9278
9279 return Imm;
9280}
9281
9282ParseStatus AMDGPUAsmParser::parseGPRIdxMode(OperandVector &Operands) {
9283
9284 using namespace llvm::AMDGPU::VGPRIndexMode;
9285
9286 int64_t Imm = 0;
9287 SMLoc S = getLoc();
9288
9289 if (trySkipId("gpr_idx", AsmToken::LParen)) {
9290 Imm = parseGPRIdxMacro();
9291 if (Imm == UNDEF)
9292 return ParseStatus::Failure;
9293 } else {
9294 if (getParser().parseAbsoluteExpression(Imm))
9295 return ParseStatus::Failure;
9296 if (Imm < 0 || !isUInt<4>(Imm))
9297 return Error(S, "invalid immediate: only 4-bit values are legal");
9298 }
9299
9300 Operands.push_back(
9301 AMDGPUOperand::CreateImm(this, Imm, S, AMDGPUOperand::ImmTyGprIdxMode));
9302 return ParseStatus::Success;
9303}
9304
9305bool AMDGPUOperand::isGPRIdxMode() const { return isImmTy(ImmTyGprIdxMode); }
9306
9307//===----------------------------------------------------------------------===//
9308// sopp branch targets
9309//===----------------------------------------------------------------------===//
9310
9311ParseStatus AMDGPUAsmParser::parseSOPPBrTarget(OperandVector &Operands) {
9312
9313 // Make sure we are not parsing something
9314 // that looks like a label or an expression but is not.
9315 // This will improve error messages.
9316 if (isRegister() || isModifier())
9317 return ParseStatus::NoMatch;
9318
9319 if (!parseExpr(Operands))
9320 return ParseStatus::Failure;
9321
9322 AMDGPUOperand &Opr = ((AMDGPUOperand &)*Operands[Operands.size() - 1]);
9323 assert(Opr.isImm() || Opr.isExpr());
9324 SMLoc Loc = Opr.getStartLoc();
9325
9326 // Currently we do not support arbitrary expressions as branch targets.
9327 // Only labels and absolute expressions are accepted.
9328 if (Opr.isExpr() && !Opr.isSymbolRefExpr()) {
9329 Error(Loc, "expected an absolute expression or a label");
9330 } else if (Opr.isImm() && !Opr.isS16Imm()) {
9331 Error(Loc, "expected a 16-bit signed jump offset");
9332 }
9333
9334 return ParseStatus::Success;
9335}
9336
9337ParseStatus AMDGPUAsmParser::parseSMEMOffsetPCRel(OperandVector &Operands) {
9338 if (isRegister() || isModifier())
9339 return ParseStatus::NoMatch;
9340 if (!parseExpr(Operands))
9341 return ParseStatus::Failure;
9342 AMDGPUOperand &Opr = ((AMDGPUOperand &)*Operands[Operands.size() - 1]);
9343 assert(Opr.isImm() || Opr.isExpr());
9344 // Numeric operands are the encoded offset and are range-checked later.
9345 // Labels are resolved by fixup_si_smem_pcrel.
9346 if (Opr.isExpr() && (!Opr.isSymbolRefExpr() || Opr.hasSymbolSpecifier()))
9347 Error(Opr.getStartLoc(),
9348 "expected an absolute expression or an unqualified label");
9349 return ParseStatus::Success;
9350}
9351
9352//===----------------------------------------------------------------------===//
9353// Boolean holding registers
9354//===----------------------------------------------------------------------===//
9355
9356ParseStatus AMDGPUAsmParser::parseBoolReg(OperandVector &Operands) {
9357 return parseReg(Operands);
9358}
9359
9360//===----------------------------------------------------------------------===//
9361// mubuf
9362//===----------------------------------------------------------------------===//
9363
9364void AMDGPUAsmParser::cvtMubufImpl(MCInst &Inst, const OperandVector &Operands,
9365 bool IsAtomic) {
9366 OptionalImmIndexMap OptionalIdx;
9367 unsigned FirstOperandIdx = 1;
9368 bool IsAtomicReturn = false;
9369
9370 if (IsAtomic) {
9371 IsAtomicReturn = SIInstrFlags::isAtomicRet(MII, Inst);
9372 }
9373
9374 for (unsigned i = FirstOperandIdx, e = Operands.size(); i != e; ++i) {
9375 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
9376
9377 // Add the register arguments
9378 if (Op.isReg()) {
9379 Op.addRegOperands(Inst, 1);
9380 // Insert a tied src for atomic return dst.
9381 // This cannot be postponed as subsequent calls to
9382 // addImmOperands rely on correct number of MC operands.
9383 if (IsAtomicReturn && i == FirstOperandIdx)
9384 Op.addRegOperands(Inst, 1);
9385 continue;
9386 }
9387
9388 // Handle the case where soffset is an immediate
9389 if (Op.isImm() && Op.getImmTy() == AMDGPUOperand::ImmTyNone) {
9390 Op.addImmOperands(Inst, 1);
9391 continue;
9392 }
9393
9394 // Handle tokens like 'offen' which are sometimes hard-coded into the
9395 // asm string. There are no MCInst operands for these.
9396 if (Op.isToken()) {
9397 continue;
9398 }
9399 assert(Op.isImm());
9400
9401 // Handle optional arguments
9402 OptionalIdx[Op.getImmTy()] = i;
9403 }
9404
9405 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9406 AMDGPUOperand::ImmTyOffset);
9407 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyCPol,
9408 0);
9409 // Parse a dummy operand as a placeholder for the SWZ operand. This enforces
9410 // agreement between MCInstrDesc.getNumOperands and MCInst.getNumOperands.
9412 // The LDS variants carry a trailing IsAsync operand. Parse a dummy the same
9413 // way as the SWZ operand.
9414 if (AMDGPU::hasNamedOperand(Inst.getOpcode(), AMDGPU::OpName::IsAsync))
9416}
9417
9418//===----------------------------------------------------------------------===//
9419// smrd
9420//===----------------------------------------------------------------------===//
9421
9422bool AMDGPUOperand::isSMRDOffset8() const {
9423 return isImmLiteral() && isUInt<8>(getImm());
9424}
9425
9426bool AMDGPUOperand::isSMEMOffset() const {
9427 // Offset range is checked later by validator.
9428 return isImmLiteral();
9429}
9430
9431bool AMDGPUOperand::isSMRDLiteralOffset() const {
9432 // 32-bit literals are only supported on CI and we only want to use them
9433 // when the offset is > 8-bits.
9434 return isImmLiteral() && !isUInt<8>(getImm()) && isUInt<32>(getImm());
9435}
9436
9437//===----------------------------------------------------------------------===//
9438// vop3
9439//===----------------------------------------------------------------------===//
9440
9441static bool ConvertOmodMul(int64_t &Mul) {
9442 if (Mul != 1 && Mul != 2 && Mul != 4)
9443 return false;
9444
9445 Mul >>= 1;
9446 return true;
9447}
9448
9449static bool ConvertOmodDiv(int64_t &Div) {
9450 if (Div == 1) {
9451 Div = 0;
9452 return true;
9453 }
9454
9455 if (Div == 2) {
9456 Div = 3;
9457 return true;
9458 }
9459
9460 return false;
9461}
9462
9463// For pre-gfx11 targets, both bound_ctrl:0 and bound_ctrl:1 are encoded as 1.
9464// This is intentional and ensures compatibility with sp3.
9465// See bug 35397 for details.
9466bool AMDGPUAsmParser::convertDppBoundCtrl(int64_t &BoundCtrl) {
9467 if (BoundCtrl == 0 || BoundCtrl == 1) {
9468 if (!isGFX11Plus())
9469 BoundCtrl = 1;
9470 return true;
9471 }
9472 return false;
9473}
9474
9475void AMDGPUAsmParser::onBeginOfFile() {
9476 if (!getParser().getStreamer().getTargetStreamer())
9477 return;
9478
9479 if (!getTargetStreamer().getTargetID())
9480 getTargetStreamer().initializeTargetID(getSTI(),
9481 /*ApplyFeatureString=*/true);
9482}
9483
9484void AMDGPUAsmParser::emitTargetDirective() {
9485 if (!getParser().getStreamer().getTargetStreamer() ||
9486 getSTI().getTargetTriple().getArch() == Triple::r600)
9487 return;
9488
9489 if (isHsaAbi(getSTI()))
9490 getTargetStreamer().emitDirectiveAMDGCNTargetOnce();
9491}
9492
9493/// Parse AMDGPU specific expressions.
9494///
9495/// expr ::= or(expr, ...) |
9496/// max(expr, ...) |
9497/// min(expr, ...)
9498///
9499bool AMDGPUAsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
9500 using AGVK = AMDGPUMCExpr::VariantKind;
9501
9502 if (isToken(AsmToken::Identifier)) {
9503 StringRef TokenId = getTokenStr();
9504 AGVK VK = StringSwitch<AGVK>(TokenId)
9505 .Case("max", AGVK::AGVK_Max)
9506 .Case("min", AGVK::AGVK_Min)
9507 .Case("or", AGVK::AGVK_Or)
9508 .Case("extrasgprs", AGVK::AGVK_ExtraSGPRs)
9509 .Case("totalnumvgprs", AGVK::AGVK_TotalNumVGPRs)
9510 .Case("alignto", AGVK::AGVK_AlignTo)
9511 .Case("occupancy", AGVK::AGVK_Occupancy)
9512 .Case("instprefsize", AGVK::AGVK_InstPrefSize)
9513 .Default(AGVK::AGVK_None);
9514
9515 if (VK != AGVK::AGVK_None && peekToken().is(AsmToken::LParen)) {
9517 uint64_t CommaCount = 0;
9518 lex(); // Eat Arg ('or', 'max', 'occupancy', etc.)
9519 lex(); // Eat '('
9520 while (true) {
9521 if (trySkipToken(AsmToken::RParen)) {
9522 if (Exprs.empty()) {
9523 Error(getToken().getLoc(),
9524 "empty " + Twine(TokenId) + " expression");
9525 return true;
9526 }
9527 if (CommaCount + 1 != Exprs.size()) {
9528 Error(getToken().getLoc(),
9529 "mismatch of commas in " + Twine(TokenId) + " expression");
9530 return true;
9531 }
9532 if (unsigned Expected = AMDGPUMCExpr::getNumExpectedArgs(VK);
9533 Expected && Exprs.size() != Expected) {
9534 Error(getToken().getLoc(), Twine(TokenId) + " expression expects " +
9535 Twine(Expected) + " operands");
9536 return true;
9537 }
9538 Res = AMDGPUMCExpr::create(VK, Exprs, getContext());
9539 return false;
9540 }
9541 const MCExpr *Expr;
9542 if (getParser().parseExpression(Expr, EndLoc))
9543 return true;
9544 Exprs.push_back(Expr);
9545 bool LastTokenWasComma = trySkipToken(AsmToken::Comma);
9546 if (LastTokenWasComma)
9547 CommaCount++;
9548 if (!LastTokenWasComma && !isToken(AsmToken::RParen)) {
9549 Error(getToken().getLoc(),
9550 "unexpected token in " + Twine(TokenId) + " expression");
9551 return true;
9552 }
9553 }
9554 }
9555 }
9556 return getParser().parsePrimaryExpr(Res, EndLoc, nullptr);
9557}
9558
9559ParseStatus AMDGPUAsmParser::parseOModSI(OperandVector &Operands) {
9560 StringRef Name = getTokenStr();
9561 if (Name == "mul") {
9562 return parseIntWithPrefix("mul", Operands, AMDGPUOperand::ImmTyOModSI,
9564 }
9565
9566 if (Name == "div") {
9567 return parseIntWithPrefix("div", Operands, AMDGPUOperand::ImmTyOModSI,
9569 }
9570
9571 return ParseStatus::NoMatch;
9572}
9573
9574// Determines which bit DST_OP_SEL occupies in the op_sel operand according to
9575// the number of src operands present, then copies that bit into src0_modifiers.
9576static void cvtVOP3DstOpSelOnly(MCInst &Inst, const MCRegisterInfo &MRI) {
9577 int Opc = Inst.getOpcode();
9578 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
9579 if (OpSelIdx == -1)
9580 return;
9581
9582 int SrcNum;
9583 const AMDGPU::OpName Ops[] = {AMDGPU::OpName::src0, AMDGPU::OpName::src1,
9584 AMDGPU::OpName::src2};
9585 for (SrcNum = 0; SrcNum < 3 && AMDGPU::hasNamedOperand(Opc, Ops[SrcNum]);
9586 ++SrcNum)
9587 ;
9588 assert(SrcNum > 0);
9589
9590 unsigned OpSel = Inst.getOperand(OpSelIdx).getImm();
9591
9592 int DstIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
9593 if (DstIdx == -1)
9594 return;
9595
9596 const MCOperand &DstOp = Inst.getOperand(DstIdx);
9597 int ModIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers);
9598 uint32_t ModVal = Inst.getOperand(ModIdx).getImm();
9599 if (DstOp.isReg() &&
9600 MRI.getRegClass(AMDGPU::VGPR_16RegClassID).contains(DstOp.getReg())) {
9602 ModVal |= SISrcMods::DST_OP_SEL;
9603 } else {
9604 if ((OpSel & (1 << SrcNum)) != 0)
9605 ModVal |= SISrcMods::DST_OP_SEL;
9606 }
9607 Inst.getOperand(ModIdx).setImm(ModVal);
9608}
9609
9610void AMDGPUAsmParser::cvtVOP3OpSel(MCInst &Inst,
9611 const OperandVector &Operands) {
9612 cvtVOP3P(Inst, Operands);
9613 cvtVOP3DstOpSelOnly(Inst, *getMRI());
9614}
9615
9616void AMDGPUAsmParser::cvtVOP3OpSel(MCInst &Inst, const OperandVector &Operands,
9617 OptionalImmIndexMap &OptionalIdx) {
9618 cvtVOP3P(Inst, Operands, OptionalIdx);
9619 cvtVOP3DstOpSelOnly(Inst, *getMRI());
9620}
9621
9622static bool isRegOrImmWithInputMods(const MCInstrDesc &Desc, unsigned OpNum) {
9623 return
9624 // 1. This operand is input modifiers
9625 Desc.operands()[OpNum].OperandType == AMDGPU::OPERAND_INPUT_MODS
9626 // 2. This is not last operand
9627 && Desc.NumOperands > (OpNum + 1)
9628 // 3. Next operand is register class
9629 && Desc.operands()[OpNum + 1].RegClass != -1
9630 // 4. Next register is not tied to any other operand
9631 && Desc.getOperandConstraint(OpNum + 1,
9633}
9634
9635void AMDGPUAsmParser::cvtOpSelHelper(MCInst &Inst, unsigned OpSel) {
9636 unsigned Opc = Inst.getOpcode();
9637 constexpr AMDGPU::OpName Ops[] = {AMDGPU::OpName::src0, AMDGPU::OpName::src1,
9638 AMDGPU::OpName::src2};
9639 constexpr AMDGPU::OpName ModOps[] = {AMDGPU::OpName::src0_modifiers,
9640 AMDGPU::OpName::src1_modifiers,
9641 AMDGPU::OpName::src2_modifiers};
9642 for (int J = 0; J < 3; ++J) {
9643 int OpIdx = AMDGPU::getNamedOperandIdx(Opc, Ops[J]);
9644 if (OpIdx == -1)
9645 // Some instructions, e.g. v_interp_p2_f16 in GFX9, have src0, src2, but
9646 // no src1. So continue instead of break.
9647 continue;
9648
9649 int ModIdx = AMDGPU::getNamedOperandIdx(Opc, ModOps[J]);
9650 uint32_t ModVal = Inst.getOperand(ModIdx).getImm();
9651
9652 if ((OpSel & (1 << J)) != 0)
9653 ModVal |= SISrcMods::OP_SEL_0;
9654 // op_sel[3] is encoded in src0_modifiers.
9655 if (ModOps[J] == AMDGPU::OpName::src0_modifiers && (OpSel & (1 << 3)) != 0)
9656 ModVal |= SISrcMods::DST_OP_SEL;
9657
9658 Inst.getOperand(ModIdx).setImm(ModVal);
9659 }
9660}
9661
9662void AMDGPUAsmParser::cvtVOP3Interp(MCInst &Inst,
9663 const OperandVector &Operands) {
9664 OptionalImmIndexMap OptionalIdx;
9665 unsigned Opc = Inst.getOpcode();
9666
9667 unsigned I = 1;
9668 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
9669 for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
9670 ((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
9671 }
9672
9673 for (unsigned E = Operands.size(); I != E; ++I) {
9674 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
9676 Op.addRegOrImmWithFPInputModsOperands(Inst, 2);
9677 } else if (Op.isInterpSlot() || Op.isInterpAttr() ||
9678 Op.isInterpAttrChan()) {
9679 Inst.addOperand(MCOperand::createImm(Op.getImm()));
9680 } else if (Op.isImmModifier()) {
9681 OptionalIdx[Op.getImmTy()] = I;
9682 } else {
9683 llvm_unreachable("unhandled operand type");
9684 }
9685 }
9686
9687 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::high))
9688 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9689 AMDGPUOperand::ImmTyHigh);
9690
9691 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::clamp))
9692 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9693 AMDGPUOperand::ImmTyClamp);
9694
9695 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::omod))
9696 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9697 AMDGPUOperand::ImmTyOModSI);
9698
9699 // Some v_interp instructions use op_sel[3] for dst.
9700 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::op_sel)) {
9701 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9702 AMDGPUOperand::ImmTyOpSel);
9703 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
9704 unsigned OpSel = Inst.getOperand(OpSelIdx).getImm();
9705
9706 cvtOpSelHelper(Inst, OpSel);
9707 }
9708}
9709
9710void AMDGPUAsmParser::cvtVINTERP(MCInst &Inst, const OperandVector &Operands) {
9711 OptionalImmIndexMap OptionalIdx;
9712 unsigned Opc = Inst.getOpcode();
9713
9714 unsigned I = 1;
9715 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
9716 for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
9717 ((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
9718 }
9719
9720 for (unsigned E = Operands.size(); I != E; ++I) {
9721 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
9723 Op.addRegOrImmWithFPInputModsOperands(Inst, 2);
9724 } else if (Op.isImmModifier()) {
9725 OptionalIdx[Op.getImmTy()] = I;
9726 } else {
9727 llvm_unreachable("unhandled operand type");
9728 }
9729 }
9730
9731 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyClamp);
9732
9733 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
9734 if (OpSelIdx != -1)
9735 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9736 AMDGPUOperand::ImmTyOpSel);
9737
9738 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9739 AMDGPUOperand::ImmTyWaitEXP);
9740
9741 if (OpSelIdx == -1)
9742 return;
9743
9744 unsigned OpSel = Inst.getOperand(OpSelIdx).getImm();
9745 cvtOpSelHelper(Inst, OpSel);
9746}
9747
9748void AMDGPUAsmParser::cvtScaledMFMA(MCInst &Inst,
9749 const OperandVector &Operands) {
9750 OptionalImmIndexMap OptionalIdx;
9751 unsigned Opc = Inst.getOpcode();
9752 unsigned I = 1;
9753 int CbszOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::cbsz);
9754
9755 const MCInstrDesc &Desc = MII.get(Opc);
9756
9757 for (unsigned J = 0; J < Desc.getNumDefs(); ++J)
9758 static_cast<AMDGPUOperand &>(*Operands[I++]).addRegOperands(Inst, 1);
9759
9760 for (unsigned E = Operands.size(); I != E; ++I) {
9761 AMDGPUOperand &Op = static_cast<AMDGPUOperand &>(*Operands[I]);
9762 int NumOperands = Inst.getNumOperands();
9763 // The order of operands in MCInst and parsed operands are different.
9764 // Adding dummy cbsz and blgp operands at corresponding MCInst operand
9765 // indices for parsing scale values correctly.
9766 if (NumOperands == CbszOpIdx) {
9769 }
9770 if (isRegOrImmWithInputMods(Desc, NumOperands)) {
9771 Op.addRegOrImmWithFPInputModsOperands(Inst, 2);
9772 } else if (Op.isImmModifier()) {
9773 OptionalIdx[Op.getImmTy()] = I;
9774 } else {
9775 Op.addRegOrImmOperands(Inst, 1);
9776 }
9777 }
9778
9779 // Insert CBSZ and BLGP operands for F8F6F4 variants
9780 auto CbszIdx = OptionalIdx.find(AMDGPUOperand::ImmTyCBSZ);
9781 if (CbszIdx != OptionalIdx.end()) {
9782 int CbszVal = ((AMDGPUOperand &)*Operands[CbszIdx->second]).getImm();
9783 Inst.getOperand(CbszOpIdx).setImm(CbszVal);
9784 }
9785
9786 int BlgpOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::blgp);
9787 auto BlgpIdx = OptionalIdx.find(AMDGPUOperand::ImmTyBLGP);
9788 if (BlgpIdx != OptionalIdx.end()) {
9789 int BlgpVal = ((AMDGPUOperand &)*Operands[BlgpIdx->second]).getImm();
9790 Inst.getOperand(BlgpOpIdx).setImm(BlgpVal);
9791 }
9792
9793 // Add dummy src_modifiers
9796
9797 // Handle op_sel fields
9798
9799 unsigned OpSel = 0;
9800 auto OpselIdx = OptionalIdx.find(AMDGPUOperand::ImmTyOpSel);
9801 if (OpselIdx != OptionalIdx.end()) {
9802 OpSel = static_cast<const AMDGPUOperand &>(*Operands[OpselIdx->second])
9803 .getImm();
9804 }
9805
9806 unsigned OpSelHi = 0;
9807 auto OpselHiIdx = OptionalIdx.find(AMDGPUOperand::ImmTyOpSelHi);
9808 if (OpselHiIdx != OptionalIdx.end()) {
9809 OpSelHi = static_cast<const AMDGPUOperand &>(*Operands[OpselHiIdx->second])
9810 .getImm();
9811 }
9812 const AMDGPU::OpName ModOps[] = {AMDGPU::OpName::src0_modifiers,
9813 AMDGPU::OpName::src1_modifiers};
9814
9815 for (unsigned J = 0; J < 2; ++J) {
9816 unsigned ModVal = 0;
9817 if (OpSel & (1 << J))
9818 ModVal |= SISrcMods::OP_SEL_0;
9819 if (OpSelHi & (1 << J))
9820 ModVal |= SISrcMods::OP_SEL_1;
9821
9822 const int ModIdx = AMDGPU::getNamedOperandIdx(Opc, ModOps[J]);
9823 Inst.getOperand(ModIdx).setImm(ModVal);
9824 }
9825}
9826
9827void AMDGPUAsmParser::cvtVOP3(MCInst &Inst, const OperandVector &Operands,
9828 OptionalImmIndexMap &OptionalIdx) {
9829 unsigned Opc = Inst.getOpcode();
9830
9831 unsigned I = 1;
9832 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
9833 for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
9834 ((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
9835 }
9836
9837 for (unsigned E = Operands.size(); I != E; ++I) {
9838 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
9840 Op.addRegOrImmWithFPInputModsOperands(Inst, 2);
9841 } else if (Op.isImmModifier()) {
9842 OptionalIdx[Op.getImmTy()] = I;
9843 } else {
9844 Op.addRegOrImmOperands(Inst, 1);
9845 }
9846 }
9847
9848 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::scale_sel))
9849 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9850 AMDGPUOperand::ImmTyScaleSel);
9851
9852 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::clamp))
9853 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9854 AMDGPUOperand::ImmTyClamp);
9855
9856 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::byte_sel)) {
9857 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::vdst_in))
9858 Inst.addOperand(Inst.getOperand(0));
9859 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9860 AMDGPUOperand::ImmTyByteSel);
9861 }
9862
9863 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::omod))
9864 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9865 AMDGPUOperand::ImmTyOModSI);
9866
9867 // Special case v_mac_{f16, f32} and v_fmac_{f16, f32} (gfx906/gfx10+):
9868 // it has src2 register operand that is tied to dst operand
9869 // we don't allow modifiers for this operand in assembler so src2_modifiers
9870 // should be 0.
9871 if (isMAC(Opc)) {
9872 auto *it = Inst.begin();
9873 std::advance(
9874 it, AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2_modifiers));
9875 it = Inst.insert(it, MCOperand::createImm(0)); // no modifiers for src2
9876 ++it;
9877 // Copy the operand to ensure it's not invalidated when Inst grows.
9878 Inst.insert(it, MCOperand(Inst.getOperand(0))); // src2 = dst
9879 }
9880}
9881
9882void AMDGPUAsmParser::cvtVOP3(MCInst &Inst, const OperandVector &Operands) {
9883 OptionalImmIndexMap OptionalIdx;
9884 cvtVOP3(Inst, Operands, OptionalIdx);
9885}
9886
9887void AMDGPUAsmParser::cvtVOP3P(MCInst &Inst, const OperandVector &Operands,
9888 OptionalImmIndexMap &OptIdx) {
9889 const int Opc = Inst.getOpcode();
9890
9891 const bool IsPacked = SIInstrFlags::isPacked(MII, Inst);
9892
9893 if (Opc == AMDGPU::V_CVT_SCALEF32_PK_FP4_F16_vi ||
9894 Opc == AMDGPU::V_CVT_SCALEF32_PK_FP4_BF16_vi ||
9895 Opc == AMDGPU::V_CVT_SR_BF8_F32_vi ||
9896 Opc == AMDGPU::V_CVT_SR_FP8_F32_vi ||
9897 Opc == AMDGPU::V_CVT_SR_BF8_F32_gfx12_e64_gfx11 ||
9898 Opc == AMDGPU::V_CVT_SR_FP8_F32_gfx12_e64_gfx11 ||
9899 Opc == AMDGPU::V_CVT_SR_BF8_F32_gfx12_e64_gfx12 ||
9900 Opc == AMDGPU::V_CVT_SR_FP8_F32_gfx12_e64_gfx12 ||
9901 Opc == AMDGPU::V_CVT_SR_BF8_F32_gfx12_e64_gfx13 ||
9902 Opc == AMDGPU::V_CVT_SR_FP8_F32_gfx12_e64_gfx13) {
9903 Inst.addOperand(MCOperand::createImm(0)); // Placeholder for src2_mods
9904 Inst.addOperand(Inst.getOperand(0));
9905 }
9906
9907 // Append vdst_in only if a previous converter (cvtVOP3DPP for DPP variants,
9908 // cvtVOP3 for byte_sel variants) hasn't already placed it. Use the position
9909 // of the named operand to detect that, the same way cvtVOP3DPP does
9910 // internally.
9911 int VdstInIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst_in);
9912 if (VdstInIdx != -1 && VdstInIdx == static_cast<int>(Inst.getNumOperands()))
9913 Inst.addOperand(Inst.getOperand(0));
9914
9915 int BitOp3Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::bitop3);
9916 if (BitOp3Idx != -1) {
9917 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyBitOp3);
9918 }
9919
9920 // FIXME: This is messy. Parse the modifiers as if it was a normal VOP3
9921 // instruction, and then figure out where to actually put the modifiers
9922
9923 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
9924 if (OpSelIdx != -1) {
9925 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyOpSel);
9926 }
9927
9928 int OpSelHiIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel_hi);
9929 if (OpSelHiIdx != -1) {
9930 int DefaultVal = IsPacked ? -1 : 0;
9931 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyOpSelHi,
9932 DefaultVal);
9933 }
9934
9935 int MatrixAFMTIdx =
9936 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_a_fmt);
9937 if (MatrixAFMTIdx != -1) {
9938 addOptionalImmOperand(Inst, Operands, OptIdx,
9939 AMDGPUOperand::ImmTyMatrixAFMT, 0);
9940 }
9941
9942 int MatrixBFMTIdx =
9943 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_b_fmt);
9944 if (MatrixBFMTIdx != -1) {
9945 addOptionalImmOperand(Inst, Operands, OptIdx,
9946 AMDGPUOperand::ImmTyMatrixBFMT, 0);
9947 }
9948
9949 int MatrixAScaleIdx =
9950 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_a_scale);
9951 if (MatrixAScaleIdx != -1) {
9952 addOptionalImmOperand(Inst, Operands, OptIdx,
9953 AMDGPUOperand::ImmTyMatrixAScale, 0);
9954 }
9955
9956 int MatrixBScaleIdx =
9957 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_b_scale);
9958 if (MatrixBScaleIdx != -1) {
9959 addOptionalImmOperand(Inst, Operands, OptIdx,
9960 AMDGPUOperand::ImmTyMatrixBScale, 0);
9961 }
9962
9963 int MatrixAScaleFmtIdx =
9964 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_a_scale_fmt);
9965 if (MatrixAScaleFmtIdx != -1) {
9966 addOptionalImmOperand(Inst, Operands, OptIdx,
9967 AMDGPUOperand::ImmTyMatrixAScaleFmt, 0);
9968 }
9969
9970 int MatrixBScaleFmtIdx =
9971 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_b_scale_fmt);
9972 if (MatrixBScaleFmtIdx != -1) {
9973 addOptionalImmOperand(Inst, Operands, OptIdx,
9974 AMDGPUOperand::ImmTyMatrixBScaleFmt, 0);
9975 }
9976
9977 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::matrix_a_reuse))
9978 addOptionalImmOperand(Inst, Operands, OptIdx,
9979 AMDGPUOperand::ImmTyMatrixAReuse, 0);
9980
9981 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::matrix_b_reuse))
9982 addOptionalImmOperand(Inst, Operands, OptIdx,
9983 AMDGPUOperand::ImmTyMatrixBReuse, 0);
9984
9985 int NegLoIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::neg_lo);
9986 if (NegLoIdx != -1)
9987 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyNegLo);
9988
9989 int NegHiIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::neg_hi);
9990 if (NegHiIdx != -1)
9991 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyNegHi);
9992
9993 const AMDGPU::OpName Ops[] = {AMDGPU::OpName::src0, AMDGPU::OpName::src1,
9994 AMDGPU::OpName::src2};
9995 const AMDGPU::OpName ModOps[] = {AMDGPU::OpName::src0_modifiers,
9996 AMDGPU::OpName::src1_modifiers,
9997 AMDGPU::OpName::src2_modifiers};
9998
9999 unsigned OpSel = 0;
10000 unsigned OpSelHi = 0;
10001 unsigned NegLo = 0;
10002 unsigned NegHi = 0;
10003
10004 if (OpSelIdx != -1)
10005 OpSel = Inst.getOperand(OpSelIdx).getImm();
10006
10007 if (OpSelHiIdx != -1)
10008 OpSelHi = Inst.getOperand(OpSelHiIdx).getImm();
10009
10010 if (NegLoIdx != -1)
10011 NegLo = Inst.getOperand(NegLoIdx).getImm();
10012
10013 if (NegHiIdx != -1)
10014 NegHi = Inst.getOperand(NegHiIdx).getImm();
10015
10016 for (int J = 0; J < 3; ++J) {
10017 int OpIdx = AMDGPU::getNamedOperandIdx(Opc, Ops[J]);
10018 if (OpIdx == -1)
10019 break;
10020
10021 int ModIdx = AMDGPU::getNamedOperandIdx(Opc, ModOps[J]);
10022
10023 if (ModIdx == -1)
10024 continue;
10025
10026 // For MAC instructions, src2 is tied to vdst and its op_sel bit
10027 // is not encoded.
10028 if (AMDGPU::isMAC(Opc) && ModOps[J] == AMDGPU::OpName::src2_modifiers)
10029 continue;
10030
10031 uint32_t ModVal = 0;
10032
10033 const MCOperand &SrcOp = Inst.getOperand(OpIdx);
10034 if (SrcOp.isReg() && getMRI()
10035 ->getRegClass(AMDGPU::VGPR_16RegClassID)
10036 .contains(SrcOp.getReg())) {
10037 bool VGPRSuffixIsHi = AMDGPU::isHi16Reg(SrcOp.getReg(), *getMRI());
10038 if (VGPRSuffixIsHi)
10039 ModVal |= SISrcMods::OP_SEL_0;
10040 } else {
10041 if ((OpSel & (1 << J)) != 0)
10042 ModVal |= SISrcMods::OP_SEL_0;
10043 }
10044
10045 if ((OpSelHi & (1 << J)) != 0)
10046 ModVal |= SISrcMods::OP_SEL_1;
10047
10048 if ((NegLo & (1 << J)) != 0)
10049 ModVal |= SISrcMods::NEG;
10050
10051 if ((NegHi & (1 << J)) != 0)
10052 ModVal |= SISrcMods::NEG_HI;
10053
10054 Inst.getOperand(ModIdx).setImm(Inst.getOperand(ModIdx).getImm() | ModVal);
10055 }
10056}
10057
10058void AMDGPUAsmParser::cvtVOP3P(MCInst &Inst, const OperandVector &Operands) {
10059 OptionalImmIndexMap OptIdx;
10060 cvtVOP3(Inst, Operands, OptIdx);
10061 cvtVOP3P(Inst, Operands, OptIdx);
10062}
10063
10065 unsigned i, unsigned Opc,
10066 AMDGPU::OpName OpName) {
10067 if (AMDGPU::getNamedOperandIdx(Opc, OpName) != -1)
10068 ((AMDGPUOperand &)*Operands[i]).addRegOrImmWithFPInputModsOperands(Inst, 2);
10069 else
10070 ((AMDGPUOperand &)*Operands[i]).addRegOperands(Inst, 1);
10071}
10072
10073void AMDGPUAsmParser::cvtSWMMAC(MCInst &Inst, const OperandVector &Operands) {
10074 unsigned Opc = Inst.getOpcode();
10075
10076 ((AMDGPUOperand &)*Operands[1]).addRegOperands(Inst, 1);
10077 addSrcModifiersAndSrc(Inst, Operands, 2, Opc, AMDGPU::OpName::src0_modifiers);
10078 addSrcModifiersAndSrc(Inst, Operands, 3, Opc, AMDGPU::OpName::src1_modifiers);
10079 ((AMDGPUOperand &)*Operands[1]).addRegOperands(Inst, 1); // srcTiedDef
10080 ((AMDGPUOperand &)*Operands[4]).addRegOperands(Inst, 1); // src2
10081
10082 OptionalImmIndexMap OptIdx;
10083 for (unsigned i = 5; i < Operands.size(); ++i) {
10084 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
10085 OptIdx[Op.getImmTy()] = i;
10086 }
10087
10088 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::index_key_8bit))
10089 addOptionalImmOperand(Inst, Operands, OptIdx,
10090 AMDGPUOperand::ImmTyIndexKey8bit);
10091
10092 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::index_key_16bit))
10093 addOptionalImmOperand(Inst, Operands, OptIdx,
10094 AMDGPUOperand::ImmTyIndexKey16bit);
10095
10096 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::index_key_32bit))
10097 addOptionalImmOperand(Inst, Operands, OptIdx,
10098 AMDGPUOperand::ImmTyIndexKey32bit);
10099
10100 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::clamp))
10101 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyClamp);
10102
10103 cvtVOP3P(Inst, Operands, OptIdx);
10104}
10105
10106//===----------------------------------------------------------------------===//
10107// VOPD
10108//===----------------------------------------------------------------------===//
10109
10110ParseStatus AMDGPUAsmParser::parseVOPD(OperandVector &Operands) {
10111 if (!hasVOPD(getSTI()))
10112 return ParseStatus::NoMatch;
10113
10114 if (isToken(AsmToken::Colon) && peekToken(false).is(AsmToken::Colon)) {
10115 SMLoc S = getLoc();
10116 lex();
10117 lex();
10118 Operands.push_back(AMDGPUOperand::CreateToken(this, "::", S));
10119 SMLoc OpYLoc = getLoc();
10120 StringRef OpYName;
10121 if (isToken(AsmToken::Identifier) && !Parser.parseIdentifier(OpYName)) {
10122 Operands.push_back(AMDGPUOperand::CreateToken(this, OpYName, OpYLoc));
10123 return ParseStatus::Success;
10124 }
10125 return Error(OpYLoc, "expected a VOPDY instruction after ::");
10126 }
10127 return ParseStatus::NoMatch;
10128}
10129
10130// Create VOPD MCInst operands using parsed assembler operands.
10131void AMDGPUAsmParser::cvtVOPD(MCInst &Inst, const OperandVector &Operands) {
10132 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
10133
10134 auto addOp = [&](uint16_t ParsedOprIdx) { // NOLINT:function pointer
10135 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[ParsedOprIdx]);
10137 Op.addRegOrImmWithFPInputModsOperands(Inst, 2);
10138 return;
10139 }
10140 if (Op.isReg()) {
10141 Op.addRegOperands(Inst, 1);
10142 return;
10143 }
10144 if (Op.isImm() || Op.isExpr()) {
10145 Op.addImmOperands(Inst, 1);
10146 return;
10147 }
10148 llvm_unreachable("Unhandled operand type in cvtVOPD");
10149 };
10150
10151 const auto &InstInfo = getVOPDInstInfo(Inst.getOpcode(), &MII);
10152
10153 // MCInst operands are ordered as follows:
10154 // dstX, dstY, src0X [, other OpX operands], src0Y [, other OpY operands]
10155
10156 for (auto CompIdx : VOPD::COMPONENTS) {
10157 addOp(InstInfo[CompIdx].getIndexOfDstInParsedOperands());
10158 }
10159
10160 for (auto CompIdx : VOPD::COMPONENTS) {
10161 const auto &CInfo = InstInfo[CompIdx];
10162 auto CompSrcOperandsNum = InstInfo[CompIdx].getCompParsedSrcOperandsNum();
10163 for (unsigned CompSrcIdx = 0; CompSrcIdx < CompSrcOperandsNum; ++CompSrcIdx)
10164 addOp(CInfo.getIndexOfSrcInParsedOperands(CompSrcIdx));
10165 if (CInfo.hasSrc2Acc())
10166 addOp(CInfo.getIndexOfDstInParsedOperands());
10167 }
10168
10169 int BitOp3Idx =
10170 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::bitop3);
10171 if (BitOp3Idx != -1) {
10172 OptionalImmIndexMap OptIdx;
10173 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands.back());
10174 if (Op.isImm())
10175 OptIdx[Op.getImmTy()] = Operands.size() - 1;
10176
10177 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyBitOp3);
10178 }
10179}
10180
10181//===----------------------------------------------------------------------===//
10182// dpp
10183//===----------------------------------------------------------------------===//
10184
10185bool AMDGPUOperand::isDPP8() const { return isImmTy(ImmTyDPP8); }
10186
10187bool AMDGPUOperand::isDPPCtrl() const {
10188 using namespace AMDGPU::DPP;
10189
10190 bool result = isImm() && getImmTy() == ImmTyDppCtrl && isUInt<9>(getImm());
10191 if (result) {
10192 int64_t Imm = getImm();
10193 return (Imm >= DppCtrl::QUAD_PERM_FIRST &&
10194 Imm <= DppCtrl::QUAD_PERM_LAST) ||
10195 (Imm >= DppCtrl::ROW_SHL_FIRST && Imm <= DppCtrl::ROW_SHL_LAST) ||
10196 (Imm >= DppCtrl::ROW_SHR_FIRST && Imm <= DppCtrl::ROW_SHR_LAST) ||
10197 (Imm >= DppCtrl::ROW_ROR_FIRST && Imm <= DppCtrl::ROW_ROR_LAST) ||
10198 (Imm == DppCtrl::WAVE_SHL1) || (Imm == DppCtrl::WAVE_ROL1) ||
10199 (Imm == DppCtrl::WAVE_SHR1) || (Imm == DppCtrl::WAVE_ROR1) ||
10200 (Imm == DppCtrl::ROW_MIRROR) || (Imm == DppCtrl::ROW_HALF_MIRROR) ||
10201 (Imm == DppCtrl::BCAST15) || (Imm == DppCtrl::BCAST31) ||
10202 (Imm >= DppCtrl::ROW_SHARE_FIRST &&
10203 Imm <= DppCtrl::ROW_SHARE_LAST) ||
10204 (Imm >= DppCtrl::ROW_XMASK_FIRST && Imm <= DppCtrl::ROW_XMASK_LAST);
10205 }
10206 return false;
10207}
10208
10209//===----------------------------------------------------------------------===//
10210// mAI
10211//===----------------------------------------------------------------------===//
10212
10213bool AMDGPUOperand::isBLGP() const {
10214 return isImm() && getImmTy() == ImmTyBLGP && isUInt<3>(getImm());
10215}
10216
10217bool AMDGPUOperand::isS16Imm() const {
10218 return isImmLiteral() && (isInt<16>(getImm()) || isUInt<16>(getImm()));
10219}
10220
10221bool AMDGPUOperand::isU16Imm() const {
10222 return isImmLiteral() && isUInt<16>(getImm());
10223}
10224
10225//===----------------------------------------------------------------------===//
10226// dim
10227//===----------------------------------------------------------------------===//
10228
10229bool AMDGPUAsmParser::parseDimId(unsigned &Encoding) {
10230 // We want to allow "dim:1D" etc.,
10231 // but the initial 1 is tokenized as an integer.
10232 std::string Token;
10233 if (isToken(AsmToken::Integer)) {
10234 SMLoc Loc = getToken().getEndLoc();
10235 Token = std::string(getTokenStr());
10236 lex();
10237 if (getLoc() != Loc)
10238 return false;
10239 }
10240
10241 StringRef Suffix;
10242 if (!parseId(Suffix))
10243 return false;
10244 Token += Suffix;
10245
10246 StringRef DimId = Token;
10247 DimId.consume_front("SQ_RSRC_IMG_");
10248
10249 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfoByAsmSuffix(DimId);
10250 if (!DimInfo)
10251 return false;
10252
10253 Encoding = DimInfo->Encoding;
10254 return true;
10255}
10256
10257ParseStatus AMDGPUAsmParser::parseDim(OperandVector &Operands) {
10258 if (!isGFX10Plus())
10259 return ParseStatus::NoMatch;
10260
10261 SMLoc S = getLoc();
10262
10263 if (!trySkipId("dim", AsmToken::Colon))
10264 return ParseStatus::NoMatch;
10265
10266 unsigned Encoding;
10267 SMLoc Loc = getLoc();
10268 if (!parseDimId(Encoding))
10269 return Error(Loc, "invalid dim value");
10270
10271 Operands.push_back(
10272 AMDGPUOperand::CreateImm(this, Encoding, S, AMDGPUOperand::ImmTyDim));
10273 return ParseStatus::Success;
10274}
10275
10276//===----------------------------------------------------------------------===//
10277// dpp
10278//===----------------------------------------------------------------------===//
10279
10280ParseStatus AMDGPUAsmParser::parseDPP8(OperandVector &Operands) {
10281 SMLoc S = getLoc();
10282
10283 if (!isGFX10Plus() || !trySkipId("dpp8", AsmToken::Colon))
10284 return ParseStatus::NoMatch;
10285
10286 // dpp8:[%d,%d,%d,%d,%d,%d,%d,%d]
10287
10288 int64_t Sels[8];
10289
10290 if (!skipToken(AsmToken::LBrac, "expected an opening square bracket"))
10291 return ParseStatus::Failure;
10292
10293 for (size_t i = 0; i < 8; ++i) {
10294 if (i > 0 && !skipToken(AsmToken::Comma, "expected a comma"))
10295 return ParseStatus::Failure;
10296
10297 SMLoc Loc = getLoc();
10298 if (getParser().parseAbsoluteExpression(Sels[i]))
10299 return ParseStatus::Failure;
10300 if (0 > Sels[i] || 7 < Sels[i])
10301 return Error(Loc, "expected a 3-bit value");
10302 }
10303
10304 if (!skipToken(AsmToken::RBrac, "expected a closing square bracket"))
10305 return ParseStatus::Failure;
10306
10307 unsigned DPP8 = 0;
10308 for (size_t i = 0; i < 8; ++i)
10309 DPP8 |= (Sels[i] << (i * 3));
10310
10311 Operands.push_back(
10312 AMDGPUOperand::CreateImm(this, DPP8, S, AMDGPUOperand::ImmTyDPP8));
10313 return ParseStatus::Success;
10314}
10315
10316bool AMDGPUAsmParser::isSupportedDPPCtrl(StringRef Ctrl,
10317 const OperandVector &Operands) {
10318 if (Ctrl == "row_newbcast")
10319 return isGFX90A();
10320
10321 if (Ctrl == "row_share" || Ctrl == "row_xmask")
10322 return isGFX10Plus();
10323
10324 if (Ctrl == "wave_shl" || Ctrl == "wave_shr" || Ctrl == "wave_rol" ||
10325 Ctrl == "wave_ror" || Ctrl == "row_bcast")
10326 return isVI() || isGFX9();
10327
10328 return Ctrl == "row_mirror" || Ctrl == "row_half_mirror" ||
10329 Ctrl == "quad_perm" || Ctrl == "row_shl" || Ctrl == "row_shr" ||
10330 Ctrl == "row_ror";
10331}
10332
10333int64_t AMDGPUAsmParser::parseDPPCtrlPerm() {
10334 // quad_perm:[%d,%d,%d,%d]
10335
10336 if (!skipToken(AsmToken::LBrac, "expected an opening square bracket"))
10337 return -1;
10338
10339 int64_t Val = 0;
10340 for (int i = 0; i < 4; ++i) {
10341 if (i > 0 && !skipToken(AsmToken::Comma, "expected a comma"))
10342 return -1;
10343
10344 int64_t Temp;
10345 SMLoc Loc = getLoc();
10346 if (getParser().parseAbsoluteExpression(Temp))
10347 return -1;
10348 if (Temp < 0 || Temp > 3) {
10349 Error(Loc, "expected a 2-bit value");
10350 return -1;
10351 }
10352
10353 Val += (Temp << i * 2);
10354 }
10355
10356 if (!skipToken(AsmToken::RBrac, "expected a closing square bracket"))
10357 return -1;
10358
10359 return Val;
10360}
10361
10362int64_t AMDGPUAsmParser::parseDPPCtrlSel(StringRef Ctrl) {
10363 using namespace AMDGPU::DPP;
10364
10365 // sel:%d
10366
10367 int64_t Val;
10368 SMLoc Loc = getLoc();
10369
10370 if (getParser().parseAbsoluteExpression(Val))
10371 return -1;
10372
10373 struct DppCtrlCheck {
10374 int64_t Ctrl;
10375 int Lo;
10376 int Hi;
10377 };
10378
10379 DppCtrlCheck Check =
10380 StringSwitch<DppCtrlCheck>(Ctrl)
10381 .Case("wave_shl", {DppCtrl::WAVE_SHL1, 1, 1})
10382 .Case("wave_rol", {DppCtrl::WAVE_ROL1, 1, 1})
10383 .Case("wave_shr", {DppCtrl::WAVE_SHR1, 1, 1})
10384 .Case("wave_ror", {DppCtrl::WAVE_ROR1, 1, 1})
10385 .Case("row_shl", {DppCtrl::ROW_SHL0, 1, 15})
10386 .Case("row_shr", {DppCtrl::ROW_SHR0, 1, 15})
10387 .Case("row_ror", {DppCtrl::ROW_ROR0, 1, 15})
10388 .Case("row_share", {DppCtrl::ROW_SHARE_FIRST, 0, 15})
10389 .Case("row_xmask", {DppCtrl::ROW_XMASK_FIRST, 0, 15})
10390 .Case("row_newbcast", {DppCtrl::ROW_NEWBCAST_FIRST, 0, 15})
10391 .Default({-1, 0, 0});
10392
10393 bool Valid;
10394 if (Check.Ctrl == -1) {
10395 Valid = (Ctrl == "row_bcast" && (Val == 15 || Val == 31));
10396 Val = (Val == 15) ? DppCtrl::BCAST15 : DppCtrl::BCAST31;
10397 } else {
10398 Valid = Check.Lo <= Val && Val <= Check.Hi;
10399 Val = (Check.Lo == Check.Hi) ? Check.Ctrl : (Check.Ctrl | Val);
10400 }
10401
10402 if (!Valid) {
10403 Error(Loc, Twine("invalid ", Ctrl) + Twine(" value"));
10404 return -1;
10405 }
10406
10407 return Val;
10408}
10409
10410ParseStatus AMDGPUAsmParser::parseDPPCtrl(OperandVector &Operands) {
10411 using namespace AMDGPU::DPP;
10412
10413 if (!isToken(AsmToken::Identifier) ||
10414 !isSupportedDPPCtrl(getTokenStr(), Operands))
10415 return ParseStatus::NoMatch;
10416
10417 SMLoc S = getLoc();
10418 int64_t Val = -1;
10419 StringRef Ctrl;
10420
10421 parseId(Ctrl);
10422
10423 if (Ctrl == "row_mirror") {
10424 Val = DppCtrl::ROW_MIRROR;
10425 } else if (Ctrl == "row_half_mirror") {
10426 Val = DppCtrl::ROW_HALF_MIRROR;
10427 } else {
10428 if (skipToken(AsmToken::Colon, "expected a colon")) {
10429 if (Ctrl == "quad_perm") {
10430 Val = parseDPPCtrlPerm();
10431 } else {
10432 Val = parseDPPCtrlSel(Ctrl);
10433 }
10434 }
10435 }
10436
10437 if (Val == -1)
10438 return ParseStatus::Failure;
10439
10440 Operands.push_back(
10441 AMDGPUOperand::CreateImm(this, Val, S, AMDGPUOperand::ImmTyDppCtrl));
10442 return ParseStatus::Success;
10443}
10444
10445void AMDGPUAsmParser::cvtVOP3DPP(MCInst &Inst, const OperandVector &Operands,
10446 bool IsDPP8) {
10447 OptionalImmIndexMap OptionalIdx;
10448 unsigned Opc = Inst.getOpcode();
10449 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
10450
10451 // MAC instructions are special because they have 'old'
10452 // operand which is not tied to dst (but assumed to be).
10453 // They also have dummy unused src2_modifiers.
10454 int OldIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::old);
10455 int Src2ModIdx =
10456 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2_modifiers);
10457 bool IsMAC = OldIdx != -1 && Src2ModIdx != -1 &&
10458 Desc.getOperandConstraint(OldIdx, MCOI::TIED_TO) == -1;
10459
10460 unsigned I = 1;
10461 for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
10462 ((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
10463 }
10464
10465 int Fi = 0;
10466 int VdstInIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst_in);
10467 bool IsVOP3CvtSrDpp = Opc == AMDGPU::V_CVT_SR_BF8_F32_gfx12_e64_dpp8_gfx12 ||
10468 Opc == AMDGPU::V_CVT_SR_BF8_F32_gfx12_e64_dpp8_gfx13 ||
10469 Opc == AMDGPU::V_CVT_SR_FP8_F32_gfx12_e64_dpp8_gfx12 ||
10470 Opc == AMDGPU::V_CVT_SR_FP8_F32_gfx12_e64_dpp8_gfx13 ||
10471 Opc == AMDGPU::V_CVT_SR_BF8_F32_gfx12_e64_dpp_gfx12 ||
10472 Opc == AMDGPU::V_CVT_SR_BF8_F32_gfx12_e64_dpp_gfx13 ||
10473 Opc == AMDGPU::V_CVT_SR_FP8_F32_gfx12_e64_dpp_gfx12 ||
10474 Opc == AMDGPU::V_CVT_SR_FP8_F32_gfx12_e64_dpp_gfx13;
10475
10476 for (unsigned E = Operands.size(); I != E; ++I) {
10477
10478 if (IsMAC) {
10479 int NumOperands = Inst.getNumOperands();
10480 if (OldIdx == NumOperands) {
10481 // Handle old operand
10482 constexpr int DST_IDX = 0;
10483 Inst.addOperand(Inst.getOperand(DST_IDX));
10484 } else if (Src2ModIdx == NumOperands) {
10485 // Add unused dummy src2_modifiers
10487 }
10488 }
10489
10490 if (VdstInIdx == static_cast<int>(Inst.getNumOperands())) {
10491 Inst.addOperand(Inst.getOperand(0));
10492 }
10493
10494 if (IsVOP3CvtSrDpp) {
10495 if (Src2ModIdx == static_cast<int>(Inst.getNumOperands())) {
10497 Inst.addOperand(MCOperand::createReg(MCRegister()));
10498 }
10499 }
10500
10501 auto TiedTo =
10502 Desc.getOperandConstraint(Inst.getNumOperands(), MCOI::TIED_TO);
10503 if (TiedTo != -1) {
10504 assert((unsigned)TiedTo < Inst.getNumOperands());
10505 // handle tied old or src2 for MAC instructions
10506 Inst.addOperand(Inst.getOperand(TiedTo));
10507 }
10508 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
10509 // Add the register arguments
10510 if (IsDPP8 && Op.isDppFI()) {
10511 Fi = Op.getImm();
10512 } else if (isRegOrImmWithInputMods(Desc, Inst.getNumOperands())) {
10513 Op.addRegOrImmWithFPInputModsOperands(Inst, 2);
10514 } else if (Op.isReg()) {
10515 Op.addRegOperands(Inst, 1);
10516 } else if (Op.isImm() &&
10517 Desc.operands()[Inst.getNumOperands()].RegClass != -1) {
10518 Op.addImmOperands(Inst, 1);
10519 } else if (Op.isImm()) {
10520 OptionalIdx[Op.getImmTy()] = I;
10521 } else {
10522 llvm_unreachable("unhandled operand type");
10523 }
10524 }
10525
10526 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::clamp) && !IsVOP3CvtSrDpp)
10527 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10528 AMDGPUOperand::ImmTyClamp);
10529
10530 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::byte_sel)) {
10531 if (VdstInIdx == static_cast<int>(Inst.getNumOperands()))
10532 Inst.addOperand(Inst.getOperand(0));
10533 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10534 AMDGPUOperand::ImmTyByteSel);
10535 }
10536
10537 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::omod))
10538 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10539 AMDGPUOperand::ImmTyOModSI);
10540
10542 cvtVOP3P(Inst, Operands, OptionalIdx);
10543 else if (SIInstrFlags::isVOP3(Desc))
10544 cvtVOP3OpSel(Inst, Operands, OptionalIdx);
10545 else if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::op_sel)) {
10546 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10547 AMDGPUOperand::ImmTyOpSel);
10548 }
10549
10550 if (IsDPP8) {
10551 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10552 AMDGPUOperand::ImmTyDPP8);
10553 using namespace llvm::AMDGPU::DPP;
10554 Inst.addOperand(MCOperand::createImm(Fi ? DPP8_FI_1 : DPP8_FI_0));
10555 } else {
10556 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10557 AMDGPUOperand::ImmTyDppCtrl, 0xe4);
10558 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10559 AMDGPUOperand::ImmTyDppRowMask, 0xf);
10560 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10561 AMDGPUOperand::ImmTyDppBankMask, 0xf);
10562 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10563 AMDGPUOperand::ImmTyDppBoundCtrl);
10564
10565 if (AMDGPU::hasNamedOperand(Inst.getOpcode(), AMDGPU::OpName::fi))
10566 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10567 AMDGPUOperand::ImmTyDppFI);
10568 }
10569}
10570
10571void AMDGPUAsmParser::cvtDPP(MCInst &Inst, const OperandVector &Operands,
10572 bool IsDPP8) {
10573 OptionalImmIndexMap OptionalIdx;
10574
10575 unsigned I = 1;
10576 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
10577 for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
10578 ((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
10579 }
10580
10581 int Fi = 0;
10582 for (unsigned E = Operands.size(); I != E; ++I) {
10583 auto TiedTo =
10584 Desc.getOperandConstraint(Inst.getNumOperands(), MCOI::TIED_TO);
10585 if (TiedTo != -1) {
10586 assert((unsigned)TiedTo < Inst.getNumOperands());
10587 // handle tied old or src2 for MAC instructions
10588 Inst.addOperand(Inst.getOperand(TiedTo));
10589 }
10590 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
10591 // Add the register arguments
10592 if (Op.isReg() && validateVccOperand(Op.getReg())) {
10593 // VOP2b (v_add_u32, v_sub_u32 ...) dpp use "vcc" token.
10594 // Skip it.
10595 continue;
10596 }
10597
10598 if (IsDPP8) {
10599 if (Op.isDPP8()) {
10600 Op.addImmOperands(Inst, 1);
10601 } else if (isRegOrImmWithInputMods(Desc, Inst.getNumOperands())) {
10602 Op.addRegWithFPInputModsOperands(Inst, 2);
10603 } else if (Op.isDppFI()) {
10604 Fi = Op.getImm();
10605 } else if (Op.isReg()) {
10606 Op.addRegOperands(Inst, 1);
10607 } else {
10608 llvm_unreachable("Invalid operand type");
10609 }
10610 } else {
10612 Op.addRegWithFPInputModsOperands(Inst, 2);
10613 } else if (Op.isReg()) {
10614 Op.addRegOperands(Inst, 1);
10615 } else if (Op.isDPPCtrl()) {
10616 Op.addImmOperands(Inst, 1);
10617 } else if (Op.isImm()) {
10618 // Handle optional arguments
10619 OptionalIdx[Op.getImmTy()] = I;
10620 } else {
10621 llvm_unreachable("Invalid operand type");
10622 }
10623 }
10624 }
10625
10626 if (IsDPP8) {
10627 using namespace llvm::AMDGPU::DPP;
10628 Inst.addOperand(MCOperand::createImm(Fi ? DPP8_FI_1 : DPP8_FI_0));
10629 } else {
10630 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10631 AMDGPUOperand::ImmTyDppRowMask, 0xf);
10632 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10633 AMDGPUOperand::ImmTyDppBankMask, 0xf);
10634 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10635 AMDGPUOperand::ImmTyDppBoundCtrl);
10636 if (AMDGPU::hasNamedOperand(Inst.getOpcode(), AMDGPU::OpName::fi)) {
10637 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10638 AMDGPUOperand::ImmTyDppFI);
10639 }
10640 }
10641}
10642
10643//===----------------------------------------------------------------------===//
10644// sdwa
10645//===----------------------------------------------------------------------===//
10646
10647ParseStatus AMDGPUAsmParser::parseSDWASel(OperandVector &Operands,
10648 StringRef Prefix,
10649 AMDGPUOperand::ImmTy Type) {
10650 return parseStringOrIntWithPrefix(
10651 Operands, Prefix,
10652 {"BYTE_0", "BYTE_1", "BYTE_2", "BYTE_3", "WORD_0", "WORD_1", "DWORD"},
10653 Type);
10654}
10655
10656ParseStatus AMDGPUAsmParser::parseSDWADstUnused(OperandVector &Operands) {
10657 return parseStringOrIntWithPrefix(
10658 Operands, "dst_unused", {"UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE"},
10659 AMDGPUOperand::ImmTySDWADstUnused);
10660}
10661
10662void AMDGPUAsmParser::cvtSdwaVOP1(MCInst &Inst, const OperandVector &Operands) {
10663 cvtSDWA(Inst, Operands, SDWAInstType::VOP1);
10664}
10665
10666void AMDGPUAsmParser::cvtSdwaVOP2(MCInst &Inst, const OperandVector &Operands) {
10667 cvtSDWA(Inst, Operands, SDWAInstType::VOP2);
10668}
10669
10670void AMDGPUAsmParser::cvtSdwaVOP2b(MCInst &Inst,
10671 const OperandVector &Operands) {
10672 cvtSDWA(Inst, Operands, SDWAInstType::VOP2, true, true);
10673}
10674
10675void AMDGPUAsmParser::cvtSdwaVOP2e(MCInst &Inst,
10676 const OperandVector &Operands) {
10677 cvtSDWA(Inst, Operands, SDWAInstType::VOP2, false, true);
10678}
10679
10680void AMDGPUAsmParser::cvtSdwaVOPC(MCInst &Inst, const OperandVector &Operands) {
10681 cvtSDWA(Inst, Operands, SDWAInstType::VOPC, isVI());
10682}
10683
10684void AMDGPUAsmParser::cvtSDWA(MCInst &Inst, const OperandVector &Operands,
10685 SDWAInstType BasicInstType, bool SkipDstVcc,
10686 bool SkipSrcVcc) {
10687 using namespace llvm::AMDGPU::SDWA;
10688
10689 OptionalImmIndexMap OptionalIdx;
10690 bool SkipVcc = SkipDstVcc || SkipSrcVcc;
10691 bool SkippedVcc = false;
10692
10693 unsigned I = 1;
10694 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
10695 for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
10696 ((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
10697 }
10698
10699 for (unsigned E = Operands.size(); I != E; ++I) {
10700 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
10701 if (SkipVcc && !SkippedVcc && Op.isReg() &&
10702 (Op.getReg() == AMDGPU::VCC || Op.getReg() == AMDGPU::VCC_LO)) {
10703 // VOP2b (v_add_u32, v_sub_u32 ...) sdwa use "vcc" token as dst.
10704 // Skip it if it's 2nd (e.g. v_add_i32_sdwa v1, vcc, v2, v3)
10705 // or 4th (v_addc_u32_sdwa v1, vcc, v2, v3, vcc) operand.
10706 // Skip VCC only if we didn't skip it on previous iteration.
10707 // Note that src0 and src1 occupy 2 slots each because of modifiers.
10708 if (BasicInstType == SDWAInstType::VOP2 &&
10709 ((SkipDstVcc && Inst.getNumOperands() == 1) ||
10710 (SkipSrcVcc && Inst.getNumOperands() == 5))) {
10711 SkippedVcc = true;
10712 continue;
10713 }
10714 if (BasicInstType == SDWAInstType::VOPC && Inst.getNumOperands() == 0) {
10715 SkippedVcc = true;
10716 continue;
10717 }
10718 }
10720 Op.addRegOrImmWithInputModsOperands(Inst, 2);
10721 } else if (Op.isImm()) {
10722 // Handle optional arguments
10723 OptionalIdx[Op.getImmTy()] = I;
10724 } else {
10725 llvm_unreachable("Invalid operand type");
10726 }
10727 SkippedVcc = false;
10728 }
10729
10730 const unsigned Opc = Inst.getOpcode();
10731 if (Opc != AMDGPU::V_NOP_sdwa_gfx10 && Opc != AMDGPU::V_NOP_sdwa_gfx9 &&
10732 Opc != AMDGPU::V_NOP_sdwa_vi) {
10733 // v_nop_sdwa_sdwa_vi/gfx9 has no optional sdwa arguments
10734 switch (BasicInstType) {
10735 case SDWAInstType::VOP1:
10736 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::clamp))
10737 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10738 AMDGPUOperand::ImmTyClamp, 0);
10739
10740 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::omod))
10741 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10742 AMDGPUOperand::ImmTyOModSI, 0);
10743
10744 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::dst_sel))
10745 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10746 AMDGPUOperand::ImmTySDWADstSel, SdwaSel::DWORD);
10747
10748 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::dst_unused))
10749 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10750 AMDGPUOperand::ImmTySDWADstUnused,
10751 DstUnused::UNUSED_PRESERVE);
10752
10753 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10754 AMDGPUOperand::ImmTySDWASrc0Sel, SdwaSel::DWORD);
10755 break;
10756
10757 case SDWAInstType::VOP2:
10758 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10759 AMDGPUOperand::ImmTyClamp, 0);
10760
10761 if (AMDGPU::hasNamedOperand(Inst.getOpcode(), AMDGPU::OpName::omod))
10762 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10763 AMDGPUOperand::ImmTyOModSI, 0);
10764
10765 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10766 AMDGPUOperand::ImmTySDWADstSel, SdwaSel::DWORD);
10767 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10768 AMDGPUOperand::ImmTySDWADstUnused,
10769 DstUnused::UNUSED_PRESERVE);
10770 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10771 AMDGPUOperand::ImmTySDWASrc0Sel, SdwaSel::DWORD);
10772 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10773 AMDGPUOperand::ImmTySDWASrc1Sel, SdwaSel::DWORD);
10774 break;
10775
10776 case SDWAInstType::VOPC:
10777 if (AMDGPU::hasNamedOperand(Inst.getOpcode(), AMDGPU::OpName::clamp))
10778 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10779 AMDGPUOperand::ImmTyClamp, 0);
10780 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10781 AMDGPUOperand::ImmTySDWASrc0Sel, SdwaSel::DWORD);
10782 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10783 AMDGPUOperand::ImmTySDWASrc1Sel, SdwaSel::DWORD);
10784 break;
10785 }
10786 }
10787
10788 // special case v_mac_{f16, f32}:
10789 // it has src2 register operand that is tied to dst operand
10790 if (Inst.getOpcode() == AMDGPU::V_MAC_F32_sdwa_vi ||
10791 Inst.getOpcode() == AMDGPU::V_MAC_F16_sdwa_vi) {
10792 auto *it = Inst.begin();
10793 std::advance(
10794 it, AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::src2));
10795 Inst.insert(it, Inst.getOperand(0)); // src2 = dst
10796 }
10797}
10798
10799/// Force static initialization.
10800extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void
10806
10807#define GET_MATCHER_IMPLEMENTATION
10808#define GET_MNEMONIC_SPELL_CHECKER
10809#define GET_MNEMONIC_CHECKER
10810#include "AMDGPUGenAsmMatcher.inc"
10811
10812ParseStatus AMDGPUAsmParser::parseCustomOperand(OperandVector &Operands,
10813 unsigned MCK) {
10814 switch (MCK) {
10815 case MCK_addr64:
10816 return parseTokenOp("addr64", Operands);
10817 case MCK_done:
10818 return parseNamedBit("done", Operands, AMDGPUOperand::ImmTyDone, true);
10819 case MCK_idxen:
10820 return parseTokenOp("idxen", Operands);
10821 case MCK_lds:
10822 return parseNamedBit("lds", Operands, AMDGPUOperand::ImmTyLDS,
10823 /*IgnoreNegative=*/true);
10824 case MCK_offen:
10825 return parseTokenOp("offen", Operands);
10826 case MCK_off:
10827 return parseTokenOp("off", Operands);
10828 case MCK_row_95_en:
10829 return parseNamedBit("row_en", Operands, AMDGPUOperand::ImmTyRowEn, true);
10830 case MCK_gds:
10831 return parseNamedBit("gds", Operands, AMDGPUOperand::ImmTyGDS);
10832 case MCK_tfe:
10833 return parseNamedBit("tfe", Operands, AMDGPUOperand::ImmTyTFE);
10834 }
10835 return tryCustomParseOperand(Operands, MCK);
10836}
10837
10838// This function should be defined after auto-generated include so that we have
10839// MatchClassKind enum defined
10840unsigned AMDGPUAsmParser::validateTargetOperandClass(MCParsedAsmOperand &Op,
10841 unsigned Kind) {
10842 // Tokens like "glc" would be parsed as immediate operands in ParseOperand().
10843 // But MatchInstructionImpl() expects to meet token and fails to validate
10844 // operand. This method checks if we are given immediate operand but expect to
10845 // get corresponding token.
10846 AMDGPUOperand &Operand = (AMDGPUOperand &)Op;
10847 switch (Kind) {
10848 case MCK_addr64:
10849 return Operand.isAddr64() ? Match_Success : Match_InvalidOperand;
10850 case MCK_gds:
10851 return Operand.isGDS() ? Match_Success : Match_InvalidOperand;
10852 case MCK_lds:
10853 return Operand.isLDS() ? Match_Success : Match_InvalidOperand;
10854 case MCK_idxen:
10855 return Operand.isIdxen() ? Match_Success : Match_InvalidOperand;
10856 case MCK_offen:
10857 return Operand.isOffen() ? Match_Success : Match_InvalidOperand;
10858 case MCK_tfe:
10859 return Operand.isTFE() ? Match_Success : Match_InvalidOperand;
10860 case MCK_done:
10861 return Operand.isDone() ? Match_Success : Match_InvalidOperand;
10862 case MCK_row_95_en:
10863 return Operand.isRowEn() ? Match_Success : Match_InvalidOperand;
10864 case MCK_SSrc_b32:
10865 // When operands have expression values, they will return true for isToken,
10866 // because it is not possible to distinguish between a token and an
10867 // expression at parse time. MatchInstructionImpl() will always try to
10868 // match an operand as a token, when isToken returns true, and when the
10869 // name of the expression is not a valid token, the match will fail,
10870 // so we need to handle it here.
10871 return Operand.isSSrc_b32() ? Match_Success : Match_InvalidOperand;
10872 case MCK_SSrc_f32:
10873 return Operand.isSSrc_f32() ? Match_Success : Match_InvalidOperand;
10874 case MCK_SOPPBrTarget:
10875 return Operand.isSOPPBrTarget() ? Match_Success : Match_InvalidOperand;
10876 case MCK_VReg32OrOff:
10877 return Operand.isVReg32OrOff() ? Match_Success : Match_InvalidOperand;
10878 case MCK_InterpSlot:
10879 return Operand.isInterpSlot() ? Match_Success : Match_InvalidOperand;
10880 case MCK_InterpAttr:
10881 return Operand.isInterpAttr() ? Match_Success : Match_InvalidOperand;
10882 case MCK_InterpAttrChan:
10883 return Operand.isInterpAttrChan() ? Match_Success : Match_InvalidOperand;
10884 case MCK_SReg_64:
10885 case MCK_SReg_64_XEXEC:
10886 // Null is defined as a 32-bit register but
10887 // it should also be enabled with 64-bit operands or larger.
10888 // The following code enables it for SReg_64 and larger operands
10889 // used as source and destination. Remaining source
10890 // operands are handled in isInlinableImm.
10891 case MCK_SReg_96:
10892 case MCK_SReg_128:
10893 case MCK_SReg_256:
10894 case MCK_SReg_512:
10895 return Operand.isNull() ? Match_Success : Match_InvalidOperand;
10896 default:
10897 return Match_InvalidOperand;
10898 }
10899}
10900
10901//===----------------------------------------------------------------------===//
10902// endpgm
10903//===----------------------------------------------------------------------===//
10904
10905ParseStatus AMDGPUAsmParser::parseEndpgm(OperandVector &Operands) {
10906 SMLoc S = getLoc();
10907 int64_t Imm = 0;
10908
10909 if (!parseExpr(Imm)) {
10910 // The operand is optional, if not present default to 0
10911 Imm = 0;
10912 }
10913
10914 if (!isUInt<16>(Imm))
10915 return Error(S, "expected a 16-bit value");
10916
10917 Operands.push_back(
10918 AMDGPUOperand::CreateImm(this, Imm, S, AMDGPUOperand::ImmTyEndpgm));
10919 return ParseStatus::Success;
10920}
10921
10922bool AMDGPUOperand::isEndpgm() const { return isImmTy(ImmTyEndpgm); }
10923
10924//===----------------------------------------------------------------------===//
10925// Split Barrier
10926//===----------------------------------------------------------------------===//
10927
10928bool AMDGPUOperand::isSplitBarrier() const {
10929 if (!isImm())
10930 return false;
10931
10932 int64_t Imm = getImm();
10935}
#define Success
static const TargetRegisterClass * getRegClass(const MachineInstr &MI, Register Reg)
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
SmallVector< int16_t, MAX_SRC_OPERANDS_NUM > OperandIndices
static bool checkWriteLane(const MCInst &Inst)
static bool getRegNum(StringRef Str, unsigned &Num)
static void addSrcModifiersAndSrc(MCInst &Inst, const OperandVector &Operands, unsigned i, unsigned Opc, AMDGPU::OpName OpName)
static constexpr RegInfo RegularRegisters[]
static const RegInfo * getRegularRegInfo(StringRef Str)
static ArrayRef< unsigned > getAllVariants()
static OperandIndices getSrcOperandIndices(unsigned Opcode, bool AddMandatoryLiterals=false)
static int IsAGPROperand(const MCInst &Inst, AMDGPU::OpName Name, const MCRegisterInfo *MRI)
static bool IsMovrelsSDWAOpcode(const unsigned Opcode)
static const fltSemantics * getFltSemantics(unsigned Size)
static bool isRegularReg(RegisterKind Kind)
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAMDGPUAsmParser()
Force static initialization.
static bool ConvertOmodMul(int64_t &Mul)
#define PARSE_BITS_ENTRY(FIELD, ENTRY, VALUE, RANGE)
static bool isInlineableLiteralOp16(int64_t Val, MVT VT, bool HasInv2Pi)
static bool canLosslesslyConvertToFPType(APFloat &FPLiteral, MVT VT)
static bool AMDGPUCheckMnemonic(StringRef Mnemonic, const FeatureBitset &AvailableFeatures, unsigned VariantID)
static void applyMnemonicAliases(StringRef &Mnemonic, const FeatureBitset &Features, unsigned VariantID)
constexpr unsigned MAX_SRC_OPERANDS_NUM
#define EXPR_RESOLVE_OR_ERROR(RESOLVED)
static bool ConvertOmodDiv(int64_t &Div)
static bool IsRevOpcode(const unsigned Opcode)
static bool encodeCnt(const AMDGPU::IsaVersion ISA, int64_t &IntVal, int64_t CntVal, bool Saturate, unsigned(*encode)(const IsaVersion &Version, unsigned, unsigned), unsigned(*decode)(const IsaVersion &Version, unsigned))
static MCRegister getSpecialRegForName(StringRef RegName)
static void addOptionalImmOperand(MCInst &Inst, const OperandVector &Operands, AMDGPUAsmParser::OptionalImmIndexMap &OptionalIdx, AMDGPUOperand::ImmTy ImmT, int64_t Default=0, std::optional< unsigned > InsertAt=std::nullopt)
static void cvtVOP3DstOpSelOnly(MCInst &Inst, const MCRegisterInfo &MRI)
static bool isRegOrImmWithInputMods(const MCInstrDesc &Desc, unsigned OpNum)
static const fltSemantics * getOpFltSemantics(uint8_t OperandType)
static bool isInvalidVOPDY(const OperandVector &Operands, uint64_t InvalidOprIdx)
static std::string AMDGPUMnemonicSpellCheck(StringRef S, const FeatureBitset &FBS, unsigned VariantID=0)
static LLVM_READNONE unsigned encodeBitmaskPerm(const unsigned AndMask, const unsigned OrMask, const unsigned XorMask)
static bool isSafeTruncation(int64_t Val, unsigned Size)
uint64_t uint64_t
AMDHSA kernel descriptor MCExpr struct for use in MC layer.
Provides AMDGPU specific target descriptions.
AMDGPU metadata definitions and in-memory representations.
Enums shared between the AMDGPU backend (LLVM) and the ELF linker (LLD) for the .amdgpu....
AMDHSA kernel descriptor definitions.
static bool parseExpr(MCAsmParser &MCParser, const MCExpr *&Value, raw_ostream &Err)
MC layer struct for AMDGPUMCKernelCodeT, provides MCExpr functionality where required.
@ AMD_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32
This file declares a class to represent arbitrary precision floating point values and provide a varie...
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_READNONE
Definition Compiler.h:327
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
@ Default
#define Check(C,...)
static llvm::Expected< InlineInfo > decode(GsymDataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr)
Decode an InlineInfo in Data at the specified offset.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
Loop::LoopBounds::Direction Direction
Definition LoopInfo.cpp:249
static bool hasFeature(StringRef Feature, const FeatureBitset &FeatureBits, ArrayRef< SubtargetFeatureKV > ProcFeatures)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static bool isReg(const MCInst &MI, unsigned OpNo)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
MachineRegisterInfo & MRI
MachineInstr *& Lo
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
SI Fold Operands
Interface definition for SIInstrInfo.
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
const char * Msg
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
This file implements the SmallBitVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, const llvm::StringTable &StandardNames, VectorLibrary VecLib)
Initialize the set of available library functions based on the specified target triple.
static Triple::ObjectFormatType parseFormat(StringRef EnvironmentName)
Definition Triple.cpp:728
BinaryOperator * Mul
static const char * getRegisterName(MCRegister Reg)
static const AMDGPUMCExpr * createMax(ArrayRef< const MCExpr * > Args, MCContext &Ctx)
static unsigned getNumExpectedArgs(VariantKind Kind)
static const AMDGPUMCExpr * createLit(LitModifier Lit, int64_t Value, MCContext &Ctx)
static const AMDGPUMCExpr * create(VariantKind Kind, ArrayRef< const MCExpr * > Args, MCContext &Ctx)
static const AMDGPUMCExpr * createExtraSGPRs(const MCExpr *VCCUsed, const MCExpr *FlatScrUsed, bool XNACKUsed, MCContext &Ctx)
Allow delayed MCExpr resolve of ExtraSGPRs (in case VCCUsed or FlatScrUsed are unresolvable but neede...
static const AMDGPUMCExpr * createAlignTo(const MCExpr *Value, const MCExpr *Align, MCContext &Ctx)
static std::optional< TargetID > parseTargetIDString(StringRef TargetIDDirective)
Parse and validate a TargetID from a full "<triple>-<processor>:<features>" directive string.
TargetIDSetting getXnackSetting() const
StringRef getTargetTripleString() const
std::string toString() const
TargetIDSetting getSramEccSetting() const
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:380
static constexpr const fltSemantics & IEEEhalf()
Definition APFloat.h:303
static constexpr const fltSemantics & IEEEsingle()
Definition APFloat.h:305
static constexpr const fltSemantics & BFloat()
Definition APFloat.h:304
static constexpr const fltSemantics & IEEEdouble()
Definition APFloat.h:306
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:396
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6101
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
ArrayRef< T > take_front(size_t N=1) const
Return a copy of *this with only the first N elements.
Definition ArrayRef.h:218
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition ArrayRef.h:194
const T & front() const
Get the first element.
Definition ArrayRef.h:144
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
StringRef getString() const
Get the string for the current token, this includes all characters (for example, the quotes on string...
Definition MCAsmMacro.h:103
bool is(TokenKind K) const
Definition MCAsmMacro.h:75
Register getReg() const
Container class for subtarget features.
constexpr bool test(unsigned I) const
constexpr FeatureBitset & flip(unsigned I)
void printExpr(raw_ostream &, const MCExpr &) const
virtual void Initialize(MCAsmParser &Parser)
Initialize the extension for parsing using the given Parser.
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:342
static const MCBinaryExpr * createDiv(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:352
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:427
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
Context object for machine code objects.
Definition MCContext.h:84
LLVM_ABI MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
unsigned getNumOperands() const
Definition MCInst.h:212
SMLoc getLoc() const
Definition MCInst.h:208
void setLoc(SMLoc loc)
Definition MCInst.h:207
unsigned getOpcode() const
Definition MCInst.h:202
iterator insert(iterator I, const MCOperand &Op)
Definition MCInst.h:232
void addOperand(const MCOperand Op)
Definition MCInst.h:215
iterator begin()
Definition MCInst.h:227
size_t size() const
Definition MCInst.h:226
const MCOperand & getOperand(unsigned i) const
Definition MCInst.h:210
Describe properties that are true of each instruction in the target description file.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition MCInstrInfo.h:89
const int16_t * getRegClassByHwModeTable(unsigned ModeId) const
Definition MCInstrInfo.h:70
int16_t getOpRegClassID(const MCOperandInfo &OpInfo, unsigned HwModeId) const
Return the ID of the register class to use for OpInfo, for the active HwMode HwModeId.
Definition MCInstrInfo.h:79
Instances of this class represent operands of the MCInst class.
Definition MCInst.h:40
void setImm(int64_t Val)
Definition MCInst.h:89
static MCOperand createExpr(const MCExpr *Val)
Definition MCInst.h:166
int64_t getImm() const
Definition MCInst.h:84
static MCOperand createReg(MCRegister Reg)
Definition MCInst.h:138
static MCOperand createImm(int64_t Val)
Definition MCInst.h:145
bool isImm() const
Definition MCInst.h:66
void setReg(MCRegister Reg)
Set the register number.
Definition MCInst.h:79
bool isReg() const
Definition MCInst.h:65
MCRegister getReg() const
Returns the register number.
Definition MCInst.h:73
const MCExpr * getExpr() const
Definition MCInst.h:118
bool isExpr() const
Definition MCInst.h:69
MCParsedAsmOperand - This abstract class represents a source-level assembly instruction operand.
MCRegisterClass - Base class of TargetRegisterClass.
MCRegister getRegister(unsigned i) const
getRegister - Return the specified register in the class.
unsigned getNumRegs() const
getNumRegs - Return the number of registers in this class.
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
constexpr bool isValid() const
Definition MCRegister.h:84
Generic base class for all target subtargets.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
StringRef getName() const
getName - Get the symbol name.
Definition MCSymbol.h:188
bool isVariable() const
isVariable - Check if this is a variable symbol.
Definition MCSymbol.h:267
LLVM_ABI void setVariableValue(const MCExpr *Value)
Definition MCSymbol.cpp:51
void setRedefinable(bool Value)
Mark this symbol as redefinable.
Definition MCSymbol.h:210
const MCExpr * getVariableValue() const
Get the expression of the variable symbol.
Definition MCSymbol.h:270
MCTargetAsmParser - Generic interface to target specific assembly parsers.
Machine Value Type.
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
Ternary parse status returned by various parse* methods.
constexpr bool isFailure() const
static constexpr StatusTy Failure
constexpr bool isSuccess() const
static constexpr StatusTy Success
static constexpr StatusTy NoMatch
constexpr bool isNoMatch() const
constexpr unsigned id() const
Definition Register.h:100
Represents a location in source code.
Definition SMLoc.h:22
static SMLoc getFromPointer(const char *Ptr)
Definition SMLoc.h:35
constexpr const char * getPointer() const
Definition SMLoc.h:33
constexpr bool isValid() const
Definition SMLoc.h:28
SMLoc Start
Definition SMLoc.h:49
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:880
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool consume_back(StringRef Suffix)
Returns true if this StringRef has the given suffix and removes that suffix.
Definition StringRef.h:683
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:589
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:627
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition StringRef.h:270
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:653
bool contains(StringRef key) const
Check if the set contains the given key.
Definition StringSet.h:62
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition StringSet.h:41
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
int encodeDepCtr(const StringRef Name, int64_t Val, unsigned &UsedOprMask, const MCSubtargetInfo &STI)
int getDefaultDepCtrEncoding(const MCSubtargetInfo &STI)
bool isSupportedTgtId(unsigned Id, const MCSubtargetInfo &STI)
unsigned getTgtId(const StringRef Name)
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char NumSGPRs[]
Key for Kernel::CodeProps::Metadata::mNumSGPRs.
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
constexpr char AssemblerDirectiveBegin[]
HSA metadata beginning assembler directive.
constexpr char AssemblerDirectiveEnd[]
HSA metadata ending assembler directive.
constexpr char AssemblerDirectiveBegin[]
Old HSA metadata beginning assembler directive for V2.
int64_t getHwregId(StringRef Name, const MCSubtargetInfo &STI)
unsigned getVGPREncodingGranule(const MCSubtargetInfo &STI, std::optional< bool > EnableWavefrontSize32)
unsigned getSGPREncodingGranule(const MCSubtargetInfo &STI)
bool targetIDSettingsConflict(TargetIDSetting Lhs, TargetIDSetting Rhs)
Returns true if Lhs and Rhs are incompatible (both specific but different).
unsigned getLocalMemorySize(const MCSubtargetInfo &STI)
int64_t convertDfmtNfmt2Ufmt(unsigned Dfmt, unsigned Nfmt, const MCSubtargetInfo &STI)
int64_t encodeDfmtNfmt(unsigned Dfmt, unsigned Nfmt)
int64_t getUnifiedFormat(const StringRef Name, const MCSubtargetInfo &STI)
bool isValidFormatEncoding(unsigned Val, const MCSubtargetInfo &STI)
int64_t getNfmt(const StringRef Name, const MCSubtargetInfo &STI)
int64_t getDfmt(const StringRef Name)
constexpr char AssemblerDirective[]
PAL metadata (old linear format) assembler directive.
constexpr char AssemblerDirectiveBegin[]
PAL metadata (new MsgPack format) beginning assembler directive.
constexpr char AssemblerDirectiveEnd[]
PAL metadata (new MsgPack format) ending assembler directive.
int64_t getMsgOpId(int64_t MsgId, StringRef Name, const MCSubtargetInfo &STI)
Map from a symbolic name for a sendmsg operation to the operation portion of the immediate encoding.
int64_t getMsgId(StringRef Name, const MCSubtargetInfo &STI)
Map from a symbolic name for a msg_id to the message portion of the immediate encoding.
uint64_t encodeMsg(uint64_t MsgId, uint64_t OpId, uint64_t StreamId)
bool msgSupportsStream(int64_t MsgId, int64_t OpId, const MCSubtargetInfo &STI)
bool isValidMsgId(int64_t MsgId, const MCSubtargetInfo &STI)
bool isValidMsgStream(int64_t MsgId, int64_t OpId, int64_t StreamId, const MCSubtargetInfo &STI, bool Strict)
bool msgRequiresOp(int64_t MsgId, const MCSubtargetInfo &STI)
bool isValidMsgOp(int64_t MsgId, int64_t OpId, const MCSubtargetInfo &STI, bool Strict)
ArrayRef< GFXVersion > getGFXVersions()
constexpr unsigned COMPONENTS[]
constexpr const char *const ModMatrixFmt[]
constexpr const char *const ModMatrixScaleFmt[]
constexpr const char *const ModMatrixScale[]
bool isInlineValue(MCRegister Reg)
bool isPKFMACF16InlineConstant(uint32_t Literal, bool IsGFX11Plus)
LLVM_READONLY const MIMGInfo * getMIMGInfo(unsigned Opc)
bool isInlinableLiteralFP16(int16_t Literal, bool HasInv2Pi)
bool isSGPR(MCRegister Reg, const MCRegisterInfo *TRI)
Is Reg - scalar register.
MCRegister getMCReg(MCRegister Reg, const MCSubtargetInfo &STI)
If Reg is a pseudo reg, return the correct hardware register given STI otherwise return Reg.
FuncInfoFlags
Per-function flags packed into INFO_FLAGS entries.
uint8_t wmmaScaleF8F6F4FormatToNumRegs(unsigned Fmt)
const int OPR_ID_UNSUPPORTED
bool isInlinableLiteralV2I16(uint32_t Literal)
bool isHi16Reg(MCRegister Reg, const MCRegisterInfo &MRI)
unsigned getTemporalHintType(const MCInstrDesc TID)
static AMDGPUMCExpr::Specifier getSpecifier(const MCSymbolRefExpr *SRE)
LLVM_READONLY bool isLitExpr(const MCExpr *Expr)
bool isInlinableLiteralV2BF16(uint32_t Literal)
LLVM_ABI bool isCPUValidForSubArch(Triple::SubArchType SubArch, GPUKind AK)
Return true if the GPU AK is usable with the triple subarch SubArch.
unsigned getMaxNumUserSGPRs(const MCSubtargetInfo &STI)
unsigned getNumFlatOffsetBits(const MCSubtargetInfo &ST)
For pre-GFX12 FLAT instructions the offset must be positive; MSB is ignored and forced to zero.
bool hasA16(const MCSubtargetInfo &STI)
bool isLegalSMRDEncodedSignedOffset(const MCSubtargetInfo &ST, int64_t EncodedOffset, bool IsBuffer)
bool isGFX12Plus(const MCSubtargetInfo &STI)
unsigned getNSAMaxSize(const MCSubtargetInfo &STI, bool HasSampler)
bool hasPackedD16(const MCSubtargetInfo &STI)
bool isGFX940(const MCSubtargetInfo &STI)
bool isInlinableLiteralV2F16(uint32_t Literal)
bool isHsaAbi(const MCSubtargetInfo &STI)
bool isGFX11(const MCSubtargetInfo &STI)
const int OPR_VAL_INVALID
bool getSMEMIsBuffer(unsigned Opc)
bool isPackedSingleSGPRFP32Inst(unsigned Opc)
The opcode is a packed fp32 instruction which only reads low 32 bits of a scalar operand and propagat...
LLVM_ABI unsigned getAddressableNumSGPRs(GPUKind AK)
uint8_t mfmaScaleF8F6F4FormatToNumRegs(unsigned EncodingVal)
LLVM_ABI IsaVersion getIsaVersion(StringRef GPU)
unsigned getRegBitWidth(unsigned RCID)
Get the size in bits of a register from the register class RC.
bool isValid32BitLiteral(uint64_t Val, bool IsFP64)
LLVM_ABI unsigned getTotalNumVGPRs(GPUKind AK, bool IsWave32)
CanBeVOPD getCanBeVOPD(unsigned Opc, unsigned EncodingFamily, bool VOPD3)
LLVM_READNONE bool isLegalDPALU_DPPControl(const MCSubtargetInfo &ST, unsigned DC)
bool isSI(const MCSubtargetInfo &STI)
bool hasPrivateApertureRegs(const MCSubtargetInfo &STI)
unsigned decodeLgkmcnt(const IsaVersion &Version, unsigned Waitcnt)
unsigned getWaitcntBitMask(const IsaVersion &Version)
bool isGFX9(const MCSubtargetInfo &STI)
unsigned getVOPDEncodingFamily(const MCSubtargetInfo &ST)
LLVM_READONLY bool hasNamedOperand(uint32_t Opcode, OpName NamedIdx)
bool isKImmOperand(const MCInstrDesc &Desc, unsigned OpNo)
Is this a KImm operand?
GPUKind
GPU kinds supported by the AMDGPU target.
bool isGFX90A(const MCSubtargetInfo &STI)
LLVM_READONLY const MIMGDimInfo * getMIMGDimInfoByEncoding(uint8_t DimEnc)
bool isInlinableLiteral32(int32_t Literal, bool HasInv2Pi)
bool isGFX12(const MCSubtargetInfo &STI)
unsigned encodeExpcnt(const IsaVersion &Version, unsigned Waitcnt, unsigned Expcnt)
bool hasMAIInsts(const MCSubtargetInfo &STI)
constexpr bool isSISrcOperand(const MCOperandInfo &OpInfo)
Is this an AMDGPU specific source operand?
bool isInlinableLiteralBF16(int16_t Literal, bool HasInv2Pi, bool *IsBF16)
LLVM_READONLY const MIMGDimInfo * getMIMGDimInfoByAsmSuffix(StringRef AsmSuffix)
bool hasMIMG_R128(const MCSubtargetInfo &STI)
LLVM_ABI GPUKind parseArchAMDGCN(StringRef CPU)
bool hasG16(const MCSubtargetInfo &STI)
unsigned getAddrSizeMIMGOp(const MIMGBaseOpcodeInfo *BaseOpcode, const MIMGDimInfo *Dim, bool IsA16, bool IsG16Supported)
bool hasArchitectedFlatScratch(const MCSubtargetInfo &STI)
LLVM_READONLY int64_t getLitValue(const MCExpr *Expr)
bool isGFX11Plus(const MCSubtargetInfo &STI)
bool isSISrcFPOperand(const MCInstrDesc &Desc, unsigned OpNo)
Is this floating-point operand?
bool isGFX10Plus(const MCSubtargetInfo &STI)
AMDGPU::TargetID TargetID
int64_t encode32BitLiteral(int64_t Imm, OperandType Type, bool IsLit)
bool isValidWMMAScaleFmtCombination(unsigned AFmt, unsigned AScale, unsigned BFmt, unsigned BScale)
@ OPERAND_REG_IMM_V2FP64
Definition SIDefines.h:447
@ OPERAND_KIMM32
Operand with 32-bit immediate that uses the constant bus.
Definition SIDefines.h:465
@ OPERAND_REG_IMM_INT64
Definition SIDefines.h:432
@ OPERAND_REG_IMM_V2FP16
Definition SIDefines.h:440
@ OPERAND_REG_INLINE_C_FP64
Definition SIDefines.h:456
@ OPERAND_REG_IMM_NOINLINE_FP16
Definition SIDefines.h:438
@ OPERAND_REG_INLINE_C_BF16
Definition SIDefines.h:453
@ OPERAND_REG_INLINE_C_V2BF16
Definition SIDefines.h:458
@ OPERAND_REG_IMM_V2INT64
Definition SIDefines.h:443
@ OPERAND_REG_IMM_V2INT16
Definition SIDefines.h:442
@ OPERAND_REG_IMM_BF16
Definition SIDefines.h:436
@ OPERAND_REG_IMM_INT32
Operands with register, 32-bit, or 64-bit immediate.
Definition SIDefines.h:431
@ OPERAND_REG_IMM_V2BF16
Definition SIDefines.h:439
@ OPERAND_REG_IMM_FP16
Definition SIDefines.h:437
@ OPERAND_REG_IMM_V2FP16_SPLAT
Definition SIDefines.h:441
@ OPERAND_REG_INLINE_C_INT64
Definition SIDefines.h:452
@ OPERAND_REG_INLINE_C_INT16
Operands with register or inline constant.
Definition SIDefines.h:450
@ OPERAND_REG_IMM_NOINLINE_V2FP16
Definition SIDefines.h:444
@ OPERAND_REG_IMM_FP64
Definition SIDefines.h:435
@ OPERAND_REG_INLINE_C_V2FP16
Definition SIDefines.h:459
@ OPERAND_REG_INLINE_AC_INT32
Operands with an AccVGPR register or inline constant.
Definition SIDefines.h:470
@ OPERAND_REG_INLINE_AC_FP32
Definition SIDefines.h:471
@ OPERAND_REG_IMM_V2INT32
Definition SIDefines.h:445
@ OPERAND_REG_IMM_FP32
Definition SIDefines.h:434
@ OPERAND_REG_INLINE_C_FP32
Definition SIDefines.h:455
@ OPERAND_REG_INLINE_C_INT32
Definition SIDefines.h:451
@ OPERAND_REG_INLINE_C_V2INT16
Definition SIDefines.h:457
@ OPERAND_REG_IMM_V2FP32
Definition SIDefines.h:446
@ OPERAND_REG_INLINE_AC_FP64
Definition SIDefines.h:472
@ OPERAND_REG_INLINE_C_FP16
Definition SIDefines.h:454
@ OPERAND_REG_IMM_INT16
Definition SIDefines.h:433
@ OPERAND_INLINE_SPLIT_BARRIER_INT32
Definition SIDefines.h:462
constexpr bool isBF16SrcOperand(const MCOperandInfo &OpInfo)
Is this a scalar (i.e. not packed) bf16 source operand?
bool isDPALU_DPP(const MCInstrDesc &OpDesc, const MCInstrInfo &MII, const MCSubtargetInfo &ST)
LLVM_ABI StringRef getArchNameAMDGCN(GPUKind AK)
bool hasGDS(const MCSubtargetInfo &STI)
bool isLegalSMRDEncodedUnsignedOffset(const MCSubtargetInfo &ST, int64_t EncodedOffset)
bool isGFX9Plus(const MCSubtargetInfo &STI)
bool hasDPPSrc1SGPR(const MCSubtargetInfo &STI)
const int OPR_ID_DUPLICATE
bool isVOPD(unsigned Opc)
VOPD::InstInfo getVOPDInstInfo(const MCInstrDesc &OpX, const MCInstrDesc &OpY)
unsigned encodeVmcnt(const IsaVersion &Version, unsigned Waitcnt, unsigned Vmcnt)
unsigned decodeExpcnt(const IsaVersion &Version, unsigned Waitcnt)
const MIMGBaseOpcodeInfo * getMIMGBaseOpcode(unsigned Opc)
bool isVI(const MCSubtargetInfo &STI)
bool supportsScaleOffset(const MCInstrInfo &MII, unsigned Opcode)
MCRegister mc2PseudoReg(MCRegister Reg)
Convert hardware register Reg to a pseudo register.
unsigned hasKernargPreload(const MCSubtargetInfo &STI)
bool supportsWGP(const MCSubtargetInfo &STI)
bool isMAC(unsigned Opc)
LLVM_READNONE unsigned getOperandSize(const MCOperandInfo &OpInfo)
bool isCI(const MCSubtargetInfo &STI)
unsigned encodeLgkmcnt(const IsaVersion &Version, unsigned Waitcnt, unsigned Lgkmcnt)
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
const int OPR_ID_UNKNOWN
bool isGFX1250Plus(const MCSubtargetInfo &STI)
bool hasPopsExitingWaveID(const MCSubtargetInfo &STI)
unsigned decodeVmcnt(const IsaVersion &Version, unsigned Waitcnt)
bool isInlinableLiteralI16(int32_t Literal, bool HasInv2Pi)
bool hasVOPD(const MCSubtargetInfo &STI)
bool isInlinableLiteral64(int64_t Literal, bool HasInv2Pi)
Is this literal inlinable.
bool isPermlane16(unsigned Opc)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ STT_AMDGPU_HSA_KERNEL
Definition ELF.h:1286
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:235
@ OPERAND_IMMEDIATE
Definition MCInstrDesc.h:61
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
void validate(const Triple &TT, const FeatureBitset &FeatureBits)
constexpr bool isAtomicRet(const T &...O)
Definition SIDefines.h:367
constexpr bool isVOPC(const T &...O)
Definition SIDefines.h:236
constexpr bool isVOP3(const T &...O)
Definition SIDefines.h:239
constexpr bool isVOP1(const T &...O)
Definition SIDefines.h:230
constexpr bool usesTENSOR_CNT(const T &...O)
Definition SIDefines.h:310
constexpr bool isMAI(const T &...O)
Definition SIDefines.h:355
constexpr bool isVOP2(const T &...O)
Definition SIDefines.h:233
constexpr bool isSWMMAC(const T &...O)
Definition SIDefines.h:382
constexpr bool isSOP2(const T &...O)
Definition SIDefines.h:218
constexpr bool isFLAT(const T &...O)
Definition SIDefines.h:286
constexpr bool isVOP3P(const T &...O)
Definition SIDefines.h:242
constexpr bool isBuffer(const T &...O)
Definition SIDefines.h:267
constexpr bool hasIntClamp(const T &...O)
Definition SIDefines.h:334
constexpr bool isAtomicNoRet(const T &...O)
Definition SIDefines.h:364
constexpr bool isSMRD(const T &...O)
Definition SIDefines.h:271
constexpr bool isVOP3Like(const T &...O)
Definition SIDefines.h:245
constexpr bool isMIMG(const T &...O)
Definition SIDefines.h:274
constexpr bool isVMEM(const T &...O)
Definition SIDefines.h:407
constexpr bool isImage(const T &...O)
Definition SIDefines.h:403
constexpr bool isWMMA(const T &...O)
Definition SIDefines.h:370
constexpr bool isVOPD3(const T &...O)
Definition SIDefines.h:385
constexpr bool isGWS(const T &...O)
Definition SIDefines.h:379
constexpr bool isMUBUF(const T &...O)
Definition SIDefines.h:261
constexpr bool isSDWA(const T &...O)
Definition SIDefines.h:252
constexpr bool isSOPC(const T &...O)
Definition SIDefines.h:221
constexpr bool isDOT(const T &...O)
Definition SIDefines.h:358
constexpr bool isVSAMPLE(const T &...O)
Definition SIDefines.h:280
constexpr bool isDS(const T &...O)
Definition SIDefines.h:289
constexpr bool isAtomic(const T &...O)
Definition SIDefines.h:396
constexpr bool isGather4(const T &...O)
Definition SIDefines.h:307
constexpr bool isPacked(const T &...O)
Definition SIDefines.h:343
constexpr bool isDPP(const T &...O)
Definition SIDefines.h:255
constexpr bool isSegmentSpecificFLAT(const T &...O)
Definition SIDefines.h:399
@ Valid
The data is already valid.
EnumSet< Modifier > Modifiers
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
bool isNull(StringRef S)
Definition YAMLTraits.h:571
This is an optimization pass for GlobalISel generic memory operations.
bool errorToBool(Error Err)
Helper for converting an Error to a bool.
Definition Error.h:1129
@ Offset
Definition DWP.cpp:577
StringMapEntry< Value * > ValueName
Definition Value.h:56
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
unsigned encode(MaybeAlign A)
Returns a representation of the alignment that encodes undefined as 0.
Definition Alignment.h:211
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
static bool isMem(const MachineInstr &MI, unsigned Op)
LLVM_ABI std::pair< StringRef, StringRef > getToken(StringRef Source, StringRef Delimiters=" \t\n\v\f\r")
getToken - This function extracts one token from source, ignoring any leading characters that appear ...
static StringRef getCPU(StringRef CPU)
Processes a CPU name.
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
LLVM_ABI void PrintError(const Twine &Msg)
Definition Error.cpp:104
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
Op::Description Desc
Target & getTheR600Target()
The target for R600 GPUs.
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
SmallVectorImpl< std::unique_ptr< MCParsedAsmOperand > > OperandVector
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:151
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:156
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
Target & getTheGCNTarget()
The target for GCN GPUs.
@ Sub
Subtraction of integers.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
unsigned M0(unsigned Val)
Definition VE.h:393
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
Target & getTheGCNLegacyTarget()
The target for GCN GPUs, registered under the legacy "amdgcn" architecture name for use with -march.
@ Enabled
Convert any .debug_str_offsets tables to DWARF64 if needed.
Definition DWP.h:31
#define N
RegisterKind Kind
StringLiteral Name
void initDefault(const MCSubtargetInfo &STI, MCContext &Ctx, bool InitMCExpr=true)
void validate(const MCSubtargetInfo *STI, MCContext &Ctx)
SmallVector< std::pair< MCSymbol *, std::string >, 4 > IndirectCalls
SmallVector< std::pair< MCSymbol *, MCSymbol * >, 8 > Calls
SmallVector< FuncInfo, 8 > Funcs
SmallVector< std::pair< MCSymbol *, std::string >, 4 > TypeIds
SmallVector< std::pair< MCSymbol *, MCSymbol * >, 4 > Uses
Instruction set architecture version.
static void bits_set(const MCExpr *&Dst, const MCExpr *Value, uint32_t Shift, uint32_t Mask, MCContext &Ctx)
static MCKernelDescriptor getDefaultAmdhsaKernelDescriptor(const MCSubtargetInfo *STI, MCContext &Ctx)
RegisterMCAsmParser - Helper template for registering a target specific assembly parser,...