AMDGPU/SI: Remove unused variable
[oota-llvm.git] / lib / Target / AMDGPU / AsmParser / AMDGPUAsmParser.cpp
1 //===-- AMDGPUAsmParser.cpp - Parse SI asm to MCInst instructions ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
11 #include "MCTargetDesc/AMDGPUTargetStreamer.h"
12 #include "Utils/AMDGPUBaseInfo.h"
13 #include "SIDefines.h"
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCParser/MCAsmLexer.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSubtargetInfo.h"
30 #include "llvm/MC/MCTargetAsmParser.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Support/Debug.h"
35
36 using namespace llvm;
37
38 namespace {
39
40 struct OptionalOperand;
41
42 class AMDGPUOperand : public MCParsedAsmOperand {
43   enum KindTy {
44     Token,
45     Immediate,
46     Register,
47     Expression
48   } Kind;
49
50   SMLoc StartLoc, EndLoc;
51
52 public:
53   AMDGPUOperand(enum KindTy K) : MCParsedAsmOperand(), Kind(K) {}
54
55   MCContext *Ctx;
56
57   enum ImmTy {
58     ImmTyNone,
59     ImmTyDSOffset0,
60     ImmTyDSOffset1,
61     ImmTyGDS,
62     ImmTyOffset,
63     ImmTyGLC,
64     ImmTySLC,
65     ImmTyTFE,
66     ImmTyClamp,
67     ImmTyOMod
68   };
69
70   struct TokOp {
71     const char *Data;
72     unsigned Length;
73   };
74
75   struct ImmOp {
76     bool IsFPImm;
77     ImmTy Type;
78     int64_t Val;
79   };
80
81   struct RegOp {
82     unsigned RegNo;
83     int Modifiers;
84     const MCRegisterInfo *TRI;
85     bool IsForcedVOP3;
86   };
87
88   union {
89     TokOp Tok;
90     ImmOp Imm;
91     RegOp Reg;
92     const MCExpr *Expr;
93   };
94
95   void addImmOperands(MCInst &Inst, unsigned N) const {
96     Inst.addOperand(MCOperand::createImm(getImm()));
97   }
98
99   StringRef getToken() const {
100     return StringRef(Tok.Data, Tok.Length);
101   }
102
103   void addRegOperands(MCInst &Inst, unsigned N) const {
104     Inst.addOperand(MCOperand::createReg(getReg()));
105   }
106
107   void addRegOrImmOperands(MCInst &Inst, unsigned N) const {
108     if (isReg())
109       addRegOperands(Inst, N);
110     else
111       addImmOperands(Inst, N);
112   }
113
114   void addRegWithInputModsOperands(MCInst &Inst, unsigned N) const {
115     Inst.addOperand(MCOperand::createImm(
116         Reg.Modifiers == -1 ? 0 : Reg.Modifiers));
117     addRegOperands(Inst, N);
118   }
119
120   void addSoppBrTargetOperands(MCInst &Inst, unsigned N) const {
121     if (isImm())
122       addImmOperands(Inst, N);
123     else {
124       assert(isExpr());
125       Inst.addOperand(MCOperand::createExpr(Expr));
126     }
127   }
128
129   bool defaultTokenHasSuffix() const {
130     StringRef Token(Tok.Data, Tok.Length);
131
132     return Token.endswith("_e32") || Token.endswith("_e64");
133   }
134
135   bool isToken() const override {
136     return Kind == Token;
137   }
138
139   bool isImm() const override {
140     return Kind == Immediate;
141   }
142
143   bool isInlineImm() const {
144     float F = BitsToFloat(Imm.Val);
145     // TODO: Add 0.5pi for VI
146     return isImm() && ((Imm.Val <= 64 && Imm.Val >= -16) ||
147            (F == 0.0 || F == 0.5 || F == -0.5 || F == 1.0 || F == -1.0 ||
148            F == 2.0 || F == -2.0 || F == 4.0 || F == -4.0));
149   }
150
151   bool isDSOffset0() const {
152     assert(isImm());
153     return Imm.Type == ImmTyDSOffset0;
154   }
155
156   bool isDSOffset1() const {
157     assert(isImm());
158     return Imm.Type == ImmTyDSOffset1;
159   }
160
161   int64_t getImm() const {
162     return Imm.Val;
163   }
164
165   enum ImmTy getImmTy() const {
166     assert(isImm());
167     return Imm.Type;
168   }
169
170   bool isRegKind() const {
171     return Kind == Register;
172   }
173
174   bool isReg() const override {
175     return Kind == Register && Reg.Modifiers == -1;
176   }
177
178   bool isRegWithInputMods() const {
179     return Kind == Register && (Reg.IsForcedVOP3 || Reg.Modifiers != -1);
180   }
181
182   void setModifiers(unsigned Mods) {
183     assert(isReg());
184     Reg.Modifiers = Mods;
185   }
186
187   bool hasModifiers() const {
188     assert(isRegKind());
189     return Reg.Modifiers != -1;
190   }
191
192   unsigned getReg() const override {
193     return Reg.RegNo;
194   }
195
196   bool isRegOrImm() const {
197     return isReg() || isImm();
198   }
199
200   bool isRegClass(unsigned RCID) const {
201     return Reg.TRI->getRegClass(RCID).contains(getReg());
202   }
203
204   bool isSCSrc32() const {
205     return isInlineImm() || (isReg() && isRegClass(AMDGPU::SReg_32RegClassID));
206   }
207
208   bool isSSrc32() const {
209     return isImm() || (isReg() && isRegClass(AMDGPU::SReg_32RegClassID));
210   }
211
212   bool isSSrc64() const {
213     return isImm() || isInlineImm() ||
214            (isReg() && isRegClass(AMDGPU::SReg_64RegClassID));
215   }
216
217   bool isVCSrc32() const {
218     return isInlineImm() || (isReg() && isRegClass(AMDGPU::VS_32RegClassID));
219   }
220
221   bool isVCSrc64() const {
222     return isInlineImm() || (isReg() && isRegClass(AMDGPU::VS_64RegClassID));
223   }
224
225   bool isVSrc32() const {
226     return isImm() || (isReg() && isRegClass(AMDGPU::VS_32RegClassID));
227   }
228
229   bool isVSrc64() const {
230     return isImm() || (isReg() && isRegClass(AMDGPU::VS_64RegClassID));
231   }
232
233   bool isMem() const override {
234     return false;
235   }
236
237   bool isExpr() const {
238     return Kind == Expression;
239   }
240
241   bool isSoppBrTarget() const {
242     return isExpr() || isImm();
243   }
244
245   SMLoc getStartLoc() const override {
246     return StartLoc;
247   }
248
249   SMLoc getEndLoc() const override {
250     return EndLoc;
251   }
252
253   void print(raw_ostream &OS) const override { }
254
255   static std::unique_ptr<AMDGPUOperand> CreateImm(int64_t Val, SMLoc Loc,
256                                                   enum ImmTy Type = ImmTyNone,
257                                                   bool IsFPImm = false) {
258     auto Op = llvm::make_unique<AMDGPUOperand>(Immediate);
259     Op->Imm.Val = Val;
260     Op->Imm.IsFPImm = IsFPImm;
261     Op->Imm.Type = Type;
262     Op->StartLoc = Loc;
263     Op->EndLoc = Loc;
264     return Op;
265   }
266
267   static std::unique_ptr<AMDGPUOperand> CreateToken(StringRef Str, SMLoc Loc,
268                                            bool HasExplicitEncodingSize = true) {
269     auto Res = llvm::make_unique<AMDGPUOperand>(Token);
270     Res->Tok.Data = Str.data();
271     Res->Tok.Length = Str.size();
272     Res->StartLoc = Loc;
273     Res->EndLoc = Loc;
274     return Res;
275   }
276
277   static std::unique_ptr<AMDGPUOperand> CreateReg(unsigned RegNo, SMLoc S,
278                                                   SMLoc E,
279                                                   const MCRegisterInfo *TRI,
280                                                   bool ForceVOP3) {
281     auto Op = llvm::make_unique<AMDGPUOperand>(Register);
282     Op->Reg.RegNo = RegNo;
283     Op->Reg.TRI = TRI;
284     Op->Reg.Modifiers = -1;
285     Op->Reg.IsForcedVOP3 = ForceVOP3;
286     Op->StartLoc = S;
287     Op->EndLoc = E;
288     return Op;
289   }
290
291   static std::unique_ptr<AMDGPUOperand> CreateExpr(const class MCExpr *Expr, SMLoc S) {
292     auto Op = llvm::make_unique<AMDGPUOperand>(Expression);
293     Op->Expr = Expr;
294     Op->StartLoc = S;
295     Op->EndLoc = S;
296     return Op;
297   }
298
299   bool isDSOffset() const;
300   bool isDSOffset01() const;
301   bool isSWaitCnt() const;
302   bool isMubufOffset() const;
303 };
304
305 class AMDGPUAsmParser : public MCTargetAsmParser {
306   MCSubtargetInfo &STI;
307   const MCInstrInfo &MII;
308   MCAsmParser &Parser;
309
310   unsigned ForcedEncodingSize;
311   /// @name Auto-generated Match Functions
312   /// {
313
314 #define GET_ASSEMBLER_HEADER
315 #include "AMDGPUGenAsmMatcher.inc"
316
317   /// }
318
319 private:
320   bool ParseDirectiveMajorMinor(uint32_t &Major, uint32_t &Minor);
321   bool ParseDirectiveHSACodeObjectVersion();
322   bool ParseDirectiveHSACodeObjectISA();
323
324 public:
325   AMDGPUAsmParser(MCSubtargetInfo &STI, MCAsmParser &_Parser,
326                const MCInstrInfo &MII,
327                const MCTargetOptions &Options)
328       : MCTargetAsmParser(), STI(STI), MII(MII), Parser(_Parser),
329         ForcedEncodingSize(0){
330
331     if (STI.getFeatureBits().none()) {
332       // Set default features.
333       STI.ToggleFeature("SOUTHERN_ISLANDS");
334     }
335
336     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
337   }
338
339   AMDGPUTargetStreamer &getTargetStreamer() {
340     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
341     return static_cast<AMDGPUTargetStreamer &>(TS);
342   }
343
344   unsigned getForcedEncodingSize() const {
345     return ForcedEncodingSize;
346   }
347
348   void setForcedEncodingSize(unsigned Size) {
349     ForcedEncodingSize = Size;
350   }
351
352   bool isForcedVOP3() const {
353     return ForcedEncodingSize == 64;
354   }
355
356   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
357   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
358   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
359                                OperandVector &Operands, MCStreamer &Out,
360                                uint64_t &ErrorInfo,
361                                bool MatchingInlineAsm) override;
362   bool ParseDirective(AsmToken DirectiveID) override;
363   OperandMatchResultTy parseOperand(OperandVector &Operands, StringRef Mnemonic);
364   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
365                         SMLoc NameLoc, OperandVector &Operands) override;
366
367   OperandMatchResultTy parseIntWithPrefix(const char *Prefix, int64_t &Int,
368                                           int64_t Default = 0);
369   OperandMatchResultTy parseIntWithPrefix(const char *Prefix,
370                                           OperandVector &Operands,
371                                           enum AMDGPUOperand::ImmTy ImmTy =
372                                                       AMDGPUOperand::ImmTyNone);
373   OperandMatchResultTy parseNamedBit(const char *Name, OperandVector &Operands,
374                                      enum AMDGPUOperand::ImmTy ImmTy =
375                                                       AMDGPUOperand::ImmTyNone);
376   OperandMatchResultTy parseOptionalOps(
377                                    const ArrayRef<OptionalOperand> &OptionalOps,
378                                    OperandVector &Operands);
379
380
381   void cvtDSOffset01(MCInst &Inst, const OperandVector &Operands);
382   void cvtDS(MCInst &Inst, const OperandVector &Operands);
383   OperandMatchResultTy parseDSOptionalOps(OperandVector &Operands);
384   OperandMatchResultTy parseDSOff01OptionalOps(OperandVector &Operands);
385   OperandMatchResultTy parseDSOffsetOptional(OperandVector &Operands);
386
387   bool parseCnt(int64_t &IntVal);
388   OperandMatchResultTy parseSWaitCntOps(OperandVector &Operands);
389   OperandMatchResultTy parseSOppBrTarget(OperandVector &Operands);
390
391   OperandMatchResultTy parseFlatOptionalOps(OperandVector &Operands);
392   OperandMatchResultTy parseFlatAtomicOptionalOps(OperandVector &Operands);
393   void cvtFlat(MCInst &Inst, const OperandVector &Operands);
394
395   void cvtMubuf(MCInst &Inst, const OperandVector &Operands);
396   OperandMatchResultTy parseOffset(OperandVector &Operands);
397   OperandMatchResultTy parseMubufOptionalOps(OperandVector &Operands);
398   OperandMatchResultTy parseGLC(OperandVector &Operands);
399   OperandMatchResultTy parseSLC(OperandVector &Operands);
400   OperandMatchResultTy parseTFE(OperandVector &Operands);
401
402   OperandMatchResultTy parseDMask(OperandVector &Operands);
403   OperandMatchResultTy parseUNorm(OperandVector &Operands);
404   OperandMatchResultTy parseR128(OperandVector &Operands);
405
406   void cvtVOP3(MCInst &Inst, const OperandVector &Operands);
407   OperandMatchResultTy parseVOP3OptionalOps(OperandVector &Operands);
408 };
409
410 struct OptionalOperand {
411   const char *Name;
412   AMDGPUOperand::ImmTy Type;
413   bool IsBit;
414   int64_t Default;
415   bool (*ConvertResult)(int64_t&);
416 };
417
418 }
419
420 static unsigned getRegClass(bool IsVgpr, unsigned RegWidth) {
421   if (IsVgpr) {
422     switch (RegWidth) {
423       default: llvm_unreachable("Unknown register width");
424       case 1: return AMDGPU::VGPR_32RegClassID;
425       case 2: return AMDGPU::VReg_64RegClassID;
426       case 3: return AMDGPU::VReg_96RegClassID;
427       case 4: return AMDGPU::VReg_128RegClassID;
428       case 8: return AMDGPU::VReg_256RegClassID;
429       case 16: return AMDGPU::VReg_512RegClassID;
430     }
431   }
432
433   switch (RegWidth) {
434     default: llvm_unreachable("Unknown register width");
435     case 1: return AMDGPU::SGPR_32RegClassID;
436     case 2: return AMDGPU::SGPR_64RegClassID;
437     case 4: return AMDGPU::SReg_128RegClassID;
438     case 8: return AMDGPU::SReg_256RegClassID;
439     case 16: return AMDGPU::SReg_512RegClassID;
440   }
441 }
442
443 static unsigned getRegForName(const StringRef &RegName) {
444
445   return StringSwitch<unsigned>(RegName)
446     .Case("exec", AMDGPU::EXEC)
447     .Case("vcc", AMDGPU::VCC)
448     .Case("flat_scr", AMDGPU::FLAT_SCR)
449     .Case("m0", AMDGPU::M0)
450     .Case("scc", AMDGPU::SCC)
451     .Case("flat_scr_lo", AMDGPU::FLAT_SCR_LO)
452     .Case("flat_scr_hi", AMDGPU::FLAT_SCR_HI)
453     .Case("vcc_lo", AMDGPU::VCC_LO)
454     .Case("vcc_hi", AMDGPU::VCC_HI)
455     .Case("exec_lo", AMDGPU::EXEC_LO)
456     .Case("exec_hi", AMDGPU::EXEC_HI)
457     .Default(0);
458 }
459
460 bool AMDGPUAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) {
461   const AsmToken Tok = Parser.getTok();
462   StartLoc = Tok.getLoc();
463   EndLoc = Tok.getEndLoc();
464   const StringRef &RegName = Tok.getString();
465   RegNo = getRegForName(RegName);
466
467   if (RegNo) {
468     Parser.Lex();
469     return false;
470   }
471
472   // Match vgprs and sgprs
473   if (RegName[0] != 's' && RegName[0] != 'v')
474     return true;
475
476   bool IsVgpr = RegName[0] == 'v';
477   unsigned RegWidth;
478   unsigned RegIndexInClass;
479   if (RegName.size() > 1) {
480     // We have a 32-bit register
481     RegWidth = 1;
482     if (RegName.substr(1).getAsInteger(10, RegIndexInClass))
483       return true;
484     Parser.Lex();
485   } else {
486     // We have a register greater than 32-bits.
487
488     int64_t RegLo, RegHi;
489     Parser.Lex();
490     if (getLexer().isNot(AsmToken::LBrac))
491       return true;
492
493     Parser.Lex();
494     if (getParser().parseAbsoluteExpression(RegLo))
495       return true;
496
497     if (getLexer().isNot(AsmToken::Colon))
498       return true;
499
500     Parser.Lex();
501     if (getParser().parseAbsoluteExpression(RegHi))
502       return true;
503
504     if (getLexer().isNot(AsmToken::RBrac))
505       return true;
506
507     Parser.Lex();
508     RegWidth = (RegHi - RegLo) + 1;
509     if (IsVgpr) {
510       // VGPR registers aren't aligned.
511       RegIndexInClass = RegLo;
512     } else {
513       // SGPR registers are aligned.  Max alignment is 4 dwords.
514       RegIndexInClass = RegLo / std::min(RegWidth, 4u);
515     }
516   }
517
518   const MCRegisterInfo *TRC = getContext().getRegisterInfo();
519   unsigned RC = getRegClass(IsVgpr, RegWidth);
520   if (RegIndexInClass > TRC->getRegClass(RC).getNumRegs())
521     return true;
522   RegNo = TRC->getRegClass(RC).getRegister(RegIndexInClass);
523   return false;
524 }
525
526 unsigned AMDGPUAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
527
528   uint64_t TSFlags = MII.get(Inst.getOpcode()).TSFlags;
529
530   if ((getForcedEncodingSize() == 32 && (TSFlags & SIInstrFlags::VOP3)) ||
531       (getForcedEncodingSize() == 64 && !(TSFlags & SIInstrFlags::VOP3)))
532     return Match_InvalidOperand;
533
534   return Match_Success;
535 }
536
537
538 bool AMDGPUAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
539                                               OperandVector &Operands,
540                                               MCStreamer &Out,
541                                               uint64_t &ErrorInfo,
542                                               bool MatchingInlineAsm) {
543   MCInst Inst;
544
545   switch (MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm)) {
546     default: break;
547     case Match_Success:
548       Inst.setLoc(IDLoc);
549       Out.EmitInstruction(Inst, STI);
550       return false;
551     case Match_MissingFeature:
552       return Error(IDLoc, "instruction not supported on this GPU");
553
554     case Match_MnemonicFail:
555       return Error(IDLoc, "unrecognized instruction mnemonic");
556
557     case Match_InvalidOperand: {
558       SMLoc ErrorLoc = IDLoc;
559       if (ErrorInfo != ~0ULL) {
560         if (ErrorInfo >= Operands.size()) {
561           if (isForcedVOP3()) {
562             // If 64-bit encoding has been forced we can end up with no
563             // clamp or omod operands if none of the registers have modifiers,
564             // so we need to add these to the operand list.
565             AMDGPUOperand &LastOp =
566                 ((AMDGPUOperand &)*Operands[Operands.size() - 1]);
567             if (LastOp.isRegKind() ||
568                (LastOp.isImm() &&
569                 LastOp.getImmTy() != AMDGPUOperand::ImmTyNone)) {
570               SMLoc S = Parser.getTok().getLoc();
571               Operands.push_back(AMDGPUOperand::CreateImm(0, S,
572                                  AMDGPUOperand::ImmTyClamp));
573               Operands.push_back(AMDGPUOperand::CreateImm(0, S,
574                                  AMDGPUOperand::ImmTyOMod));
575               bool Res = MatchAndEmitInstruction(IDLoc, Opcode, Operands,
576                                                  Out, ErrorInfo,
577                                                  MatchingInlineAsm);
578               if (!Res)
579                 return Res;
580             }
581
582           }
583           return Error(IDLoc, "too few operands for instruction");
584         }
585
586         ErrorLoc = ((AMDGPUOperand &)*Operands[ErrorInfo]).getStartLoc();
587         if (ErrorLoc == SMLoc())
588           ErrorLoc = IDLoc;
589       }
590       return Error(ErrorLoc, "invalid operand for instruction");
591     }
592   }
593   llvm_unreachable("Implement any new match types added!");
594 }
595
596 bool AMDGPUAsmParser::ParseDirectiveMajorMinor(uint32_t &Major,
597                                                uint32_t &Minor) {
598   if (getLexer().isNot(AsmToken::Integer))
599     return TokError("invalid major version");
600
601   Major = getLexer().getTok().getIntVal();
602   Lex();
603
604   if (getLexer().isNot(AsmToken::Comma))
605     return TokError("minor version number required, comma expected");
606   Lex();
607
608   if (getLexer().isNot(AsmToken::Integer))
609     return TokError("invalid minor version");
610
611   Minor = getLexer().getTok().getIntVal();
612   Lex();
613
614   return false;
615 }
616
617 bool AMDGPUAsmParser::ParseDirectiveHSACodeObjectVersion() {
618
619   uint32_t Major;
620   uint32_t Minor;
621
622   if (ParseDirectiveMajorMinor(Major, Minor))
623     return true;
624
625   getTargetStreamer().EmitDirectiveHSACodeObjectVersion(Major, Minor);
626   return false;
627 }
628
629 bool AMDGPUAsmParser::ParseDirectiveHSACodeObjectISA() {
630
631   uint32_t Major;
632   uint32_t Minor;
633   uint32_t Stepping;
634   StringRef VendorName;
635   StringRef ArchName;
636
637   // If this directive has no arguments, then use the ISA version for the
638   // targeted GPU.
639   if (getLexer().is(AsmToken::EndOfStatement)) {
640     AMDGPU::IsaVersion Isa = AMDGPU::getIsaVersion(STI.getFeatureBits());
641     getTargetStreamer().EmitDirectiveHSACodeObjectISA(Isa.Major, Isa.Minor,
642                                                       Isa.Stepping,
643                                                       "AMD", "AMDGPU");
644     return false;
645   }
646
647
648   if (ParseDirectiveMajorMinor(Major, Minor))
649     return true;
650
651   if (getLexer().isNot(AsmToken::Comma))
652     return TokError("stepping version number required, comma expected");
653   Lex();
654
655   if (getLexer().isNot(AsmToken::Integer))
656     return TokError("invalid stepping version");
657
658   Stepping = getLexer().getTok().getIntVal();
659   Lex();
660
661   if (getLexer().isNot(AsmToken::Comma))
662     return TokError("vendor name required, comma expected");
663   Lex();
664
665   if (getLexer().isNot(AsmToken::String))
666     return TokError("invalid vendor name");
667
668   VendorName = getLexer().getTok().getStringContents();
669   Lex();
670
671   if (getLexer().isNot(AsmToken::Comma))
672     return TokError("arch name required, comma expected");
673   Lex();
674
675   if (getLexer().isNot(AsmToken::String))
676     return TokError("invalid arch name");
677
678   ArchName = getLexer().getTok().getStringContents();
679   Lex();
680
681   getTargetStreamer().EmitDirectiveHSACodeObjectISA(Major, Minor, Stepping,
682                                                     VendorName, ArchName);
683   return false;
684 }
685
686 bool AMDGPUAsmParser::ParseDirective(AsmToken DirectiveID) {
687   StringRef IDVal = DirectiveID.getString();
688
689   if (IDVal == ".hsa_code_object_version")
690     return ParseDirectiveHSACodeObjectVersion();
691
692   if (IDVal == ".hsa_code_object_isa")
693     return ParseDirectiveHSACodeObjectISA();
694
695   return true;
696 }
697
698 static bool operandsHaveModifiers(const OperandVector &Operands) {
699
700   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
701     const AMDGPUOperand &Op = ((AMDGPUOperand&)*Operands[i]);
702     if (Op.isRegKind() && Op.hasModifiers())
703       return true;
704     if (Op.isImm() && (Op.getImmTy() == AMDGPUOperand::ImmTyOMod ||
705                        Op.getImmTy() == AMDGPUOperand::ImmTyClamp))
706       return true;
707   }
708   return false;
709 }
710
711 AMDGPUAsmParser::OperandMatchResultTy
712 AMDGPUAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
713
714   // Try to parse with a custom parser
715   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
716
717   // If we successfully parsed the operand or if there as an error parsing,
718   // we are done.
719   //
720   // If we are parsing after we reach EndOfStatement then this means we
721   // are appending default values to the Operands list.  This is only done
722   // by custom parser, so we shouldn't continue on to the generic parsing.
723   if (ResTy == MatchOperand_Success || ResTy == MatchOperand_ParseFail ||
724       getLexer().is(AsmToken::EndOfStatement))
725     return ResTy;
726
727   bool Negate = false, Abs = false;
728   if (getLexer().getKind()== AsmToken::Minus) {
729     Parser.Lex();
730     Negate = true;
731   }
732
733   if (getLexer().getKind() == AsmToken::Pipe) {
734     Parser.Lex();
735     Abs = true;
736   }
737
738   switch(getLexer().getKind()) {
739     case AsmToken::Integer: {
740       SMLoc S = Parser.getTok().getLoc();
741       int64_t IntVal;
742       if (getParser().parseAbsoluteExpression(IntVal))
743         return MatchOperand_ParseFail;
744       APInt IntVal32(32, IntVal);
745       if (IntVal32.getSExtValue() != IntVal) {
746         Error(S, "invalid immediate: only 32-bit values are legal");
747         return MatchOperand_ParseFail;
748       }
749
750       IntVal = IntVal32.getSExtValue();
751       if (Negate)
752         IntVal *= -1;
753       Operands.push_back(AMDGPUOperand::CreateImm(IntVal, S));
754       return MatchOperand_Success;
755     }
756     case AsmToken::Real: {
757       // FIXME: We should emit an error if a double precisions floating-point
758       // value is used.  I'm not sure the best way to detect this.
759       SMLoc S = Parser.getTok().getLoc();
760       int64_t IntVal;
761       if (getParser().parseAbsoluteExpression(IntVal))
762         return MatchOperand_ParseFail;
763
764       APFloat F((float)BitsToDouble(IntVal));
765       if (Negate)
766         F.changeSign();
767       Operands.push_back(
768           AMDGPUOperand::CreateImm(F.bitcastToAPInt().getZExtValue(), S));
769       return MatchOperand_Success;
770     }
771     case AsmToken::Identifier: {
772       SMLoc S, E;
773       unsigned RegNo;
774       if (!ParseRegister(RegNo, S, E)) {
775
776         bool HasModifiers = operandsHaveModifiers(Operands);
777         unsigned Modifiers = 0;
778
779         if (Negate)
780           Modifiers |= 0x1;
781
782         if (Abs) {
783           if (getLexer().getKind() != AsmToken::Pipe)
784             return MatchOperand_ParseFail;
785           Parser.Lex();
786           Modifiers |= 0x2;
787         }
788
789         if (Modifiers && !HasModifiers) {
790           // We are adding a modifier to src1 or src2 and previous sources
791           // don't have modifiers, so we need to go back and empty modifers
792           // for each previous source.
793           for (unsigned PrevRegIdx = Operands.size() - 1; PrevRegIdx > 1;
794                --PrevRegIdx) {
795
796             AMDGPUOperand &RegOp = ((AMDGPUOperand&)*Operands[PrevRegIdx]);
797             RegOp.setModifiers(0);
798           }
799         }
800
801
802         Operands.push_back(AMDGPUOperand::CreateReg(
803             RegNo, S, E, getContext().getRegisterInfo(),
804             isForcedVOP3()));
805
806         if (HasModifiers || Modifiers) {
807           AMDGPUOperand &RegOp = ((AMDGPUOperand&)*Operands[Operands.size() - 1]);
808           RegOp.setModifiers(Modifiers);
809
810         }
811      }  else {
812       Operands.push_back(AMDGPUOperand::CreateToken(Parser.getTok().getString(),
813                                                     S));
814       Parser.Lex();
815      }
816      return MatchOperand_Success;
817     }
818     default:
819       return MatchOperand_NoMatch;
820   }
821 }
822
823 bool AMDGPUAsmParser::ParseInstruction(ParseInstructionInfo &Info,
824                                        StringRef Name,
825                                        SMLoc NameLoc, OperandVector &Operands) {
826
827   // Clear any forced encodings from the previous instruction.
828   setForcedEncodingSize(0);
829
830   if (Name.endswith("_e64"))
831     setForcedEncodingSize(64);
832   else if (Name.endswith("_e32"))
833     setForcedEncodingSize(32);
834
835   // Add the instruction mnemonic
836   Operands.push_back(AMDGPUOperand::CreateToken(Name, NameLoc));
837
838   while (!getLexer().is(AsmToken::EndOfStatement)) {
839     AMDGPUAsmParser::OperandMatchResultTy Res = parseOperand(Operands, Name);
840
841     // Eat the comma or space if there is one.
842     if (getLexer().is(AsmToken::Comma))
843       Parser.Lex();
844
845     switch (Res) {
846       case MatchOperand_Success: break;
847       case MatchOperand_ParseFail: return Error(getLexer().getLoc(),
848                                                 "failed parsing operand.");
849       case MatchOperand_NoMatch: return Error(getLexer().getLoc(),
850                                               "not a valid operand.");
851     }
852   }
853
854   // Once we reach end of statement, continue parsing so we can add default
855   // values for optional arguments.
856   AMDGPUAsmParser::OperandMatchResultTy Res;
857   while ((Res = parseOperand(Operands, Name)) != MatchOperand_NoMatch) {
858     if (Res != MatchOperand_Success)
859       return Error(getLexer().getLoc(), "failed parsing operand.");
860   }
861   return false;
862 }
863
864 //===----------------------------------------------------------------------===//
865 // Utility functions
866 //===----------------------------------------------------------------------===//
867
868 AMDGPUAsmParser::OperandMatchResultTy
869 AMDGPUAsmParser::parseIntWithPrefix(const char *Prefix, int64_t &Int,
870                                     int64_t Default) {
871
872   // We are at the end of the statement, and this is a default argument, so
873   // use a default value.
874   if (getLexer().is(AsmToken::EndOfStatement)) {
875     Int = Default;
876     return MatchOperand_Success;
877   }
878
879   switch(getLexer().getKind()) {
880     default: return MatchOperand_NoMatch;
881     case AsmToken::Identifier: {
882       StringRef OffsetName = Parser.getTok().getString();
883       if (!OffsetName.equals(Prefix))
884         return MatchOperand_NoMatch;
885
886       Parser.Lex();
887       if (getLexer().isNot(AsmToken::Colon))
888         return MatchOperand_ParseFail;
889
890       Parser.Lex();
891       if (getLexer().isNot(AsmToken::Integer))
892         return MatchOperand_ParseFail;
893
894       if (getParser().parseAbsoluteExpression(Int))
895         return MatchOperand_ParseFail;
896       break;
897     }
898   }
899   return MatchOperand_Success;
900 }
901
902 AMDGPUAsmParser::OperandMatchResultTy
903 AMDGPUAsmParser::parseIntWithPrefix(const char *Prefix, OperandVector &Operands,
904                                     enum AMDGPUOperand::ImmTy ImmTy) {
905
906   SMLoc S = Parser.getTok().getLoc();
907   int64_t Offset = 0;
908
909   AMDGPUAsmParser::OperandMatchResultTy Res = parseIntWithPrefix(Prefix, Offset);
910   if (Res != MatchOperand_Success)
911     return Res;
912
913   Operands.push_back(AMDGPUOperand::CreateImm(Offset, S, ImmTy));
914   return MatchOperand_Success;
915 }
916
917 AMDGPUAsmParser::OperandMatchResultTy
918 AMDGPUAsmParser::parseNamedBit(const char *Name, OperandVector &Operands,
919                                enum AMDGPUOperand::ImmTy ImmTy) {
920   int64_t Bit = 0;
921   SMLoc S = Parser.getTok().getLoc();
922
923   // We are at the end of the statement, and this is a default argument, so
924   // use a default value.
925   if (getLexer().isNot(AsmToken::EndOfStatement)) {
926     switch(getLexer().getKind()) {
927       case AsmToken::Identifier: {
928         StringRef Tok = Parser.getTok().getString();
929         if (Tok == Name) {
930           Bit = 1;
931           Parser.Lex();
932         } else if (Tok.startswith("no") && Tok.endswith(Name)) {
933           Bit = 0;
934           Parser.Lex();
935         } else {
936           return MatchOperand_NoMatch;
937         }
938         break;
939       }
940       default:
941         return MatchOperand_NoMatch;
942     }
943   }
944
945   Operands.push_back(AMDGPUOperand::CreateImm(Bit, S, ImmTy));
946   return MatchOperand_Success;
947 }
948
949 static bool operandsHasOptionalOp(const OperandVector &Operands,
950                                   const OptionalOperand &OOp) {
951   for (unsigned i = 0; i < Operands.size(); i++) {
952     const AMDGPUOperand &ParsedOp = ((const AMDGPUOperand &)*Operands[i]);
953     if ((ParsedOp.isImm() && ParsedOp.getImmTy() == OOp.Type) ||
954         (ParsedOp.isToken() && ParsedOp.getToken() == OOp.Name))
955       return true;
956
957   }
958   return false;
959 }
960
961 AMDGPUAsmParser::OperandMatchResultTy
962 AMDGPUAsmParser::parseOptionalOps(const ArrayRef<OptionalOperand> &OptionalOps,
963                                    OperandVector &Operands) {
964   SMLoc S = Parser.getTok().getLoc();
965   for (const OptionalOperand &Op : OptionalOps) {
966     if (operandsHasOptionalOp(Operands, Op))
967       continue;
968     AMDGPUAsmParser::OperandMatchResultTy Res;
969     int64_t Value;
970     if (Op.IsBit) {
971       Res = parseNamedBit(Op.Name, Operands, Op.Type);
972       if (Res == MatchOperand_NoMatch)
973         continue;
974       return Res;
975     }
976
977     Res = parseIntWithPrefix(Op.Name, Value, Op.Default);
978
979     if (Res == MatchOperand_NoMatch)
980       continue;
981
982     if (Res != MatchOperand_Success)
983       return Res;
984
985     if (Op.ConvertResult && !Op.ConvertResult(Value)) {
986       return MatchOperand_ParseFail;
987     }
988
989     Operands.push_back(AMDGPUOperand::CreateImm(Value, S, Op.Type));
990     return MatchOperand_Success;
991   }
992   return MatchOperand_NoMatch;
993 }
994
995 //===----------------------------------------------------------------------===//
996 // ds
997 //===----------------------------------------------------------------------===//
998
999 static const OptionalOperand DSOptionalOps [] = {
1000   {"offset",  AMDGPUOperand::ImmTyOffset, false, 0, nullptr},
1001   {"gds",     AMDGPUOperand::ImmTyGDS, true, 0, nullptr}
1002 };
1003
1004 static const OptionalOperand DSOptionalOpsOff01 [] = {
1005   {"offset0", AMDGPUOperand::ImmTyDSOffset0, false, 0, nullptr},
1006   {"offset1", AMDGPUOperand::ImmTyDSOffset1, false, 0, nullptr},
1007   {"gds",     AMDGPUOperand::ImmTyGDS, true, 0, nullptr}
1008 };
1009
1010 AMDGPUAsmParser::OperandMatchResultTy
1011 AMDGPUAsmParser::parseDSOptionalOps(OperandVector &Operands) {
1012   return parseOptionalOps(DSOptionalOps, Operands);
1013 }
1014 AMDGPUAsmParser::OperandMatchResultTy
1015 AMDGPUAsmParser::parseDSOff01OptionalOps(OperandVector &Operands) {
1016   return parseOptionalOps(DSOptionalOpsOff01, Operands);
1017 }
1018
1019 AMDGPUAsmParser::OperandMatchResultTy
1020 AMDGPUAsmParser::parseDSOffsetOptional(OperandVector &Operands) {
1021   SMLoc S = Parser.getTok().getLoc();
1022   AMDGPUAsmParser::OperandMatchResultTy Res =
1023     parseIntWithPrefix("offset", Operands, AMDGPUOperand::ImmTyOffset);
1024   if (Res == MatchOperand_NoMatch) {
1025     Operands.push_back(AMDGPUOperand::CreateImm(0, S,
1026                        AMDGPUOperand::ImmTyOffset));
1027     Res = MatchOperand_Success;
1028   }
1029   return Res;
1030 }
1031
1032 bool AMDGPUOperand::isDSOffset() const {
1033   return isImm() && isUInt<16>(getImm());
1034 }
1035
1036 bool AMDGPUOperand::isDSOffset01() const {
1037   return isImm() && isUInt<8>(getImm());
1038 }
1039
1040 void AMDGPUAsmParser::cvtDSOffset01(MCInst &Inst,
1041                                     const OperandVector &Operands) {
1042
1043   std::map<enum AMDGPUOperand::ImmTy, unsigned> OptionalIdx;
1044
1045   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1046     AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
1047
1048     // Add the register arguments
1049     if (Op.isReg()) {
1050       Op.addRegOperands(Inst, 1);
1051       continue;
1052     }
1053
1054     // Handle optional arguments
1055     OptionalIdx[Op.getImmTy()] = i;
1056   }
1057
1058   unsigned Offset0Idx = OptionalIdx[AMDGPUOperand::ImmTyDSOffset0];
1059   unsigned Offset1Idx = OptionalIdx[AMDGPUOperand::ImmTyDSOffset1];
1060   unsigned GDSIdx = OptionalIdx[AMDGPUOperand::ImmTyGDS];
1061
1062   ((AMDGPUOperand &)*Operands[Offset0Idx]).addImmOperands(Inst, 1); // offset0
1063   ((AMDGPUOperand &)*Operands[Offset1Idx]).addImmOperands(Inst, 1); // offset1
1064   ((AMDGPUOperand &)*Operands[GDSIdx]).addImmOperands(Inst, 1); // gds
1065   Inst.addOperand(MCOperand::createReg(AMDGPU::M0)); // m0
1066 }
1067
1068 void AMDGPUAsmParser::cvtDS(MCInst &Inst, const OperandVector &Operands) {
1069
1070   std::map<enum AMDGPUOperand::ImmTy, unsigned> OptionalIdx;
1071   bool GDSOnly = false;
1072
1073   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1074     AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
1075
1076     // Add the register arguments
1077     if (Op.isReg()) {
1078       Op.addRegOperands(Inst, 1);
1079       continue;
1080     }
1081
1082     if (Op.isToken() && Op.getToken() == "gds") {
1083       GDSOnly = true;
1084       continue;
1085     }
1086
1087     // Handle optional arguments
1088     OptionalIdx[Op.getImmTy()] = i;
1089   }
1090
1091   unsigned OffsetIdx = OptionalIdx[AMDGPUOperand::ImmTyOffset];
1092   ((AMDGPUOperand &)*Operands[OffsetIdx]).addImmOperands(Inst, 1); // offset
1093
1094   if (!GDSOnly) {
1095     unsigned GDSIdx = OptionalIdx[AMDGPUOperand::ImmTyGDS];
1096     ((AMDGPUOperand &)*Operands[GDSIdx]).addImmOperands(Inst, 1); // gds
1097   }
1098   Inst.addOperand(MCOperand::createReg(AMDGPU::M0)); // m0
1099 }
1100
1101
1102 //===----------------------------------------------------------------------===//
1103 // s_waitcnt
1104 //===----------------------------------------------------------------------===//
1105
1106 bool AMDGPUAsmParser::parseCnt(int64_t &IntVal) {
1107   StringRef CntName = Parser.getTok().getString();
1108   int64_t CntVal;
1109
1110   Parser.Lex();
1111   if (getLexer().isNot(AsmToken::LParen))
1112     return true;
1113
1114   Parser.Lex();
1115   if (getLexer().isNot(AsmToken::Integer))
1116     return true;
1117
1118   if (getParser().parseAbsoluteExpression(CntVal))
1119     return true;
1120
1121   if (getLexer().isNot(AsmToken::RParen))
1122     return true;
1123
1124   Parser.Lex();
1125   if (getLexer().is(AsmToken::Amp) || getLexer().is(AsmToken::Comma))
1126     Parser.Lex();
1127
1128   int CntShift;
1129   int CntMask;
1130
1131   if (CntName == "vmcnt") {
1132     CntMask = 0xf;
1133     CntShift = 0;
1134   } else if (CntName == "expcnt") {
1135     CntMask = 0x7;
1136     CntShift = 4;
1137   } else if (CntName == "lgkmcnt") {
1138     CntMask = 0x7;
1139     CntShift = 8;
1140   } else {
1141     return true;
1142   }
1143
1144   IntVal &= ~(CntMask << CntShift);
1145   IntVal |= (CntVal << CntShift);
1146   return false;
1147 }
1148
1149 AMDGPUAsmParser::OperandMatchResultTy
1150 AMDGPUAsmParser::parseSWaitCntOps(OperandVector &Operands) {
1151   // Disable all counters by default.
1152   // vmcnt   [3:0]
1153   // expcnt  [6:4]
1154   // lgkmcnt [10:8]
1155   int64_t CntVal = 0x77f;
1156   SMLoc S = Parser.getTok().getLoc();
1157
1158   switch(getLexer().getKind()) {
1159     default: return MatchOperand_ParseFail;
1160     case AsmToken::Integer:
1161       // The operand can be an integer value.
1162       if (getParser().parseAbsoluteExpression(CntVal))
1163         return MatchOperand_ParseFail;
1164       break;
1165
1166     case AsmToken::Identifier:
1167       do {
1168         if (parseCnt(CntVal))
1169           return MatchOperand_ParseFail;
1170       } while(getLexer().isNot(AsmToken::EndOfStatement));
1171       break;
1172   }
1173   Operands.push_back(AMDGPUOperand::CreateImm(CntVal, S));
1174   return MatchOperand_Success;
1175 }
1176
1177 bool AMDGPUOperand::isSWaitCnt() const {
1178   return isImm();
1179 }
1180
1181 //===----------------------------------------------------------------------===//
1182 // sopp branch targets
1183 //===----------------------------------------------------------------------===//
1184
1185 AMDGPUAsmParser::OperandMatchResultTy
1186 AMDGPUAsmParser::parseSOppBrTarget(OperandVector &Operands) {
1187   SMLoc S = Parser.getTok().getLoc();
1188
1189   switch (getLexer().getKind()) {
1190     default: return MatchOperand_ParseFail;
1191     case AsmToken::Integer: {
1192       int64_t Imm;
1193       if (getParser().parseAbsoluteExpression(Imm))
1194         return MatchOperand_ParseFail;
1195       Operands.push_back(AMDGPUOperand::CreateImm(Imm, S));
1196       return MatchOperand_Success;
1197     }
1198
1199     case AsmToken::Identifier:
1200       Operands.push_back(AMDGPUOperand::CreateExpr(
1201           MCSymbolRefExpr::create(getContext().getOrCreateSymbol(
1202                                   Parser.getTok().getString()), getContext()), S));
1203       Parser.Lex();
1204       return MatchOperand_Success;
1205   }
1206 }
1207
1208 //===----------------------------------------------------------------------===//
1209 // flat
1210 //===----------------------------------------------------------------------===//
1211
1212 static const OptionalOperand FlatOptionalOps [] = {
1213   {"glc",    AMDGPUOperand::ImmTyGLC, true, 0, nullptr},
1214   {"slc",    AMDGPUOperand::ImmTySLC, true, 0, nullptr},
1215   {"tfe",    AMDGPUOperand::ImmTyTFE, true, 0, nullptr}
1216 };
1217
1218 static const OptionalOperand FlatAtomicOptionalOps [] = {
1219   {"slc",    AMDGPUOperand::ImmTySLC, true, 0, nullptr},
1220   {"tfe",    AMDGPUOperand::ImmTyTFE, true, 0, nullptr}
1221 };
1222
1223 AMDGPUAsmParser::OperandMatchResultTy
1224 AMDGPUAsmParser::parseFlatOptionalOps(OperandVector &Operands) {
1225   return parseOptionalOps(FlatOptionalOps, Operands);
1226 }
1227
1228 AMDGPUAsmParser::OperandMatchResultTy
1229 AMDGPUAsmParser::parseFlatAtomicOptionalOps(OperandVector &Operands) {
1230   return parseOptionalOps(FlatAtomicOptionalOps, Operands);
1231 }
1232
1233 void AMDGPUAsmParser::cvtFlat(MCInst &Inst,
1234                                const OperandVector &Operands) {
1235   std::map<AMDGPUOperand::ImmTy, unsigned> OptionalIdx;
1236
1237   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1238     AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
1239
1240     // Add the register arguments
1241     if (Op.isReg()) {
1242       Op.addRegOperands(Inst, 1);
1243       continue;
1244     }
1245
1246     // Handle 'glc' token which is sometimes hard-coded into the
1247     // asm string.  There are no MCInst operands for these.
1248     if (Op.isToken())
1249       continue;
1250
1251     // Handle optional arguments
1252     OptionalIdx[Op.getImmTy()] = i;
1253
1254   }
1255
1256   // flat atomic instructions don't have a glc argument.
1257   if (OptionalIdx.count(AMDGPUOperand::ImmTyGLC)) {
1258     unsigned GLCIdx = OptionalIdx[AMDGPUOperand::ImmTyGLC];
1259     ((AMDGPUOperand &)*Operands[GLCIdx]).addImmOperands(Inst, 1);
1260   }
1261
1262   unsigned SLCIdx = OptionalIdx[AMDGPUOperand::ImmTySLC];
1263   unsigned TFEIdx = OptionalIdx[AMDGPUOperand::ImmTyTFE];
1264
1265   ((AMDGPUOperand &)*Operands[SLCIdx]).addImmOperands(Inst, 1);
1266   ((AMDGPUOperand &)*Operands[TFEIdx]).addImmOperands(Inst, 1);
1267 }
1268
1269 //===----------------------------------------------------------------------===//
1270 // mubuf
1271 //===----------------------------------------------------------------------===//
1272
1273 static const OptionalOperand MubufOptionalOps [] = {
1274   {"offset", AMDGPUOperand::ImmTyOffset, false, 0, nullptr},
1275   {"glc",    AMDGPUOperand::ImmTyGLC, true, 0, nullptr},
1276   {"slc",    AMDGPUOperand::ImmTySLC, true, 0, nullptr},
1277   {"tfe",    AMDGPUOperand::ImmTyTFE, true, 0, nullptr}
1278 };
1279
1280 AMDGPUAsmParser::OperandMatchResultTy
1281 AMDGPUAsmParser::parseMubufOptionalOps(OperandVector &Operands) {
1282   return parseOptionalOps(MubufOptionalOps, Operands);
1283 }
1284
1285 AMDGPUAsmParser::OperandMatchResultTy
1286 AMDGPUAsmParser::parseOffset(OperandVector &Operands) {
1287   return parseIntWithPrefix("offset", Operands);
1288 }
1289
1290 AMDGPUAsmParser::OperandMatchResultTy
1291 AMDGPUAsmParser::parseGLC(OperandVector &Operands) {
1292   return parseNamedBit("glc", Operands);
1293 }
1294
1295 AMDGPUAsmParser::OperandMatchResultTy
1296 AMDGPUAsmParser::parseSLC(OperandVector &Operands) {
1297   return parseNamedBit("slc", Operands);
1298 }
1299
1300 AMDGPUAsmParser::OperandMatchResultTy
1301 AMDGPUAsmParser::parseTFE(OperandVector &Operands) {
1302   return parseNamedBit("tfe", Operands);
1303 }
1304
1305 bool AMDGPUOperand::isMubufOffset() const {
1306   return isImm() && isUInt<12>(getImm());
1307 }
1308
1309 void AMDGPUAsmParser::cvtMubuf(MCInst &Inst,
1310                                const OperandVector &Operands) {
1311   std::map<enum AMDGPUOperand::ImmTy, unsigned> OptionalIdx;
1312
1313   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1314     AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
1315
1316     // Add the register arguments
1317     if (Op.isReg()) {
1318       Op.addRegOperands(Inst, 1);
1319       continue;
1320     }
1321
1322     // Handle the case where soffset is an immediate
1323     if (Op.isImm() && Op.getImmTy() == AMDGPUOperand::ImmTyNone) {
1324       Op.addImmOperands(Inst, 1);
1325       continue;
1326     }
1327
1328     // Handle tokens like 'offen' which are sometimes hard-coded into the
1329     // asm string.  There are no MCInst operands for these.
1330     if (Op.isToken()) {
1331       continue;
1332     }
1333     assert(Op.isImm());
1334
1335     // Handle optional arguments
1336     OptionalIdx[Op.getImmTy()] = i;
1337   }
1338
1339   assert(OptionalIdx.size() == 4);
1340
1341   unsigned OffsetIdx = OptionalIdx[AMDGPUOperand::ImmTyOffset];
1342   unsigned GLCIdx = OptionalIdx[AMDGPUOperand::ImmTyGLC];
1343   unsigned SLCIdx = OptionalIdx[AMDGPUOperand::ImmTySLC];
1344   unsigned TFEIdx = OptionalIdx[AMDGPUOperand::ImmTyTFE];
1345
1346   ((AMDGPUOperand &)*Operands[OffsetIdx]).addImmOperands(Inst, 1);
1347   ((AMDGPUOperand &)*Operands[GLCIdx]).addImmOperands(Inst, 1);
1348   ((AMDGPUOperand &)*Operands[SLCIdx]).addImmOperands(Inst, 1);
1349   ((AMDGPUOperand &)*Operands[TFEIdx]).addImmOperands(Inst, 1);
1350 }
1351
1352 //===----------------------------------------------------------------------===//
1353 // mimg
1354 //===----------------------------------------------------------------------===//
1355
1356 AMDGPUAsmParser::OperandMatchResultTy
1357 AMDGPUAsmParser::parseDMask(OperandVector &Operands) {
1358   return parseIntWithPrefix("dmask", Operands);
1359 }
1360
1361 AMDGPUAsmParser::OperandMatchResultTy
1362 AMDGPUAsmParser::parseUNorm(OperandVector &Operands) {
1363   return parseNamedBit("unorm", Operands);
1364 }
1365
1366 AMDGPUAsmParser::OperandMatchResultTy
1367 AMDGPUAsmParser::parseR128(OperandVector &Operands) {
1368   return parseNamedBit("r128", Operands);
1369 }
1370
1371 //===----------------------------------------------------------------------===//
1372 // vop3
1373 //===----------------------------------------------------------------------===//
1374
1375 static bool ConvertOmodMul(int64_t &Mul) {
1376   if (Mul != 1 && Mul != 2 && Mul != 4)
1377     return false;
1378
1379   Mul >>= 1;
1380   return true;
1381 }
1382
1383 static bool ConvertOmodDiv(int64_t &Div) {
1384   if (Div == 1) {
1385     Div = 0;
1386     return true;
1387   }
1388
1389   if (Div == 2) {
1390     Div = 3;
1391     return true;
1392   }
1393
1394   return false;
1395 }
1396
1397 static const OptionalOperand VOP3OptionalOps [] = {
1398   {"clamp", AMDGPUOperand::ImmTyClamp, true, 0, nullptr},
1399   {"mul",   AMDGPUOperand::ImmTyOMod, false, 1, ConvertOmodMul},
1400   {"div",   AMDGPUOperand::ImmTyOMod, false, 1, ConvertOmodDiv},
1401 };
1402
1403 static bool isVOP3(OperandVector &Operands) {
1404   if (operandsHaveModifiers(Operands))
1405     return true;
1406
1407   AMDGPUOperand &DstOp = ((AMDGPUOperand&)*Operands[1]);
1408
1409   if (DstOp.isReg() && DstOp.isRegClass(AMDGPU::SGPR_64RegClassID))
1410     return true;
1411
1412   if (Operands.size() >= 5)
1413     return true;
1414
1415   if (Operands.size() > 3) {
1416     AMDGPUOperand &Src1Op = ((AMDGPUOperand&)*Operands[3]);
1417     if (Src1Op.getReg() && (Src1Op.isRegClass(AMDGPU::SReg_32RegClassID) ||
1418                             Src1Op.isRegClass(AMDGPU::SReg_64RegClassID)))
1419       return true;
1420   }
1421   return false;
1422 }
1423
1424 AMDGPUAsmParser::OperandMatchResultTy
1425 AMDGPUAsmParser::parseVOP3OptionalOps(OperandVector &Operands) {
1426
1427   // The value returned by this function may change after parsing
1428   // an operand so store the original value here.
1429   bool HasModifiers = operandsHaveModifiers(Operands);
1430
1431   bool IsVOP3 = isVOP3(Operands);
1432   if (HasModifiers || IsVOP3 ||
1433       getLexer().isNot(AsmToken::EndOfStatement) ||
1434       getForcedEncodingSize() == 64) {
1435
1436     AMDGPUAsmParser::OperandMatchResultTy Res =
1437         parseOptionalOps(VOP3OptionalOps, Operands);
1438
1439     if (!HasModifiers && Res == MatchOperand_Success) {
1440       // We have added a modifier operation, so we need to make sure all
1441       // previous register operands have modifiers
1442       for (unsigned i = 2, e = Operands.size(); i != e; ++i) {
1443         AMDGPUOperand &Op = ((AMDGPUOperand&)*Operands[i]);
1444         if (Op.isReg())
1445           Op.setModifiers(0);
1446       }
1447     }
1448     return Res;
1449   }
1450   return MatchOperand_NoMatch;
1451 }
1452
1453 void AMDGPUAsmParser::cvtVOP3(MCInst &Inst, const OperandVector &Operands) {
1454   ((AMDGPUOperand &)*Operands[1]).addRegOperands(Inst, 1);
1455   unsigned i = 2;
1456
1457   std::map<enum AMDGPUOperand::ImmTy, unsigned> OptionalIdx;
1458
1459   if (operandsHaveModifiers(Operands)) {
1460     for (unsigned e = Operands.size(); i != e; ++i) {
1461       AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
1462
1463       if (Op.isRegWithInputMods()) {
1464         ((AMDGPUOperand &)*Operands[i]).addRegWithInputModsOperands(Inst, 2);
1465         continue;
1466       }
1467       OptionalIdx[Op.getImmTy()] = i;
1468     }
1469
1470     unsigned ClampIdx = OptionalIdx[AMDGPUOperand::ImmTyClamp];
1471     unsigned OModIdx = OptionalIdx[AMDGPUOperand::ImmTyOMod];
1472
1473     ((AMDGPUOperand &)*Operands[ClampIdx]).addImmOperands(Inst, 1);
1474     ((AMDGPUOperand &)*Operands[OModIdx]).addImmOperands(Inst, 1);
1475   } else {
1476     for (unsigned e = Operands.size(); i != e; ++i)
1477       ((AMDGPUOperand &)*Operands[i]).addRegOrImmOperands(Inst, 1);
1478   }
1479 }
1480
1481 /// Force static initialization.
1482 extern "C" void LLVMInitializeAMDGPUAsmParser() {
1483   RegisterMCAsmParser<AMDGPUAsmParser> A(TheAMDGPUTarget);
1484   RegisterMCAsmParser<AMDGPUAsmParser> B(TheGCNTarget);
1485 }
1486
1487 #define GET_REGISTER_MATCHER
1488 #define GET_MATCHER_IMPLEMENTATION
1489 #include "AMDGPUGenAsmMatcher.inc"
1490