Re-commit r247683: Replace Triple with a new TargetTuple in MCTargetDesc/* and relate...
[oota-llvm.git] / lib / Target / Sparc / AsmParser / SparcAsmParser.cpp
1 //===-- SparcAsmParser.cpp - Parse Sparc assembly 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/SparcMCTargetDesc.h"
11 #include "MCTargetDesc/SparcMCExpr.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/MC/MCContext.h"
14 #include "llvm/MC/MCInst.h"
15 #include "llvm/MC/MCObjectFileInfo.h"
16 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
17 #include "llvm/MC/MCStreamer.h"
18 #include "llvm/MC/MCSubtargetInfo.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/MC/MCTargetAsmParser.h"
21 #include "llvm/Support/TargetRegistry.h"
22
23 using namespace llvm;
24
25 // The generated AsmMatcher SparcGenAsmMatcher uses "Sparc" as the target
26 // namespace. But SPARC backend uses "SP" as its namespace.
27 namespace llvm {
28   namespace Sparc {
29     using namespace SP;
30   }
31 }
32
33 namespace {
34 class SparcOperand;
35 class SparcAsmParser : public MCTargetAsmParser {
36
37   MCSubtargetInfo &STI;
38   MCAsmParser &Parser;
39
40   /// @name Auto-generated Match Functions
41   /// {
42
43 #define GET_ASSEMBLER_HEADER
44 #include "SparcGenAsmMatcher.inc"
45
46   /// }
47
48   // public interface of the MCTargetAsmParser.
49   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
50                                OperandVector &Operands, MCStreamer &Out,
51                                uint64_t &ErrorInfo,
52                                bool MatchingInlineAsm) override;
53   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
54   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
55                         SMLoc NameLoc, OperandVector &Operands) override;
56   bool ParseDirective(AsmToken DirectiveID) override;
57
58   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
59                                       unsigned Kind) override;
60
61   // Custom parse functions for Sparc specific operands.
62   OperandMatchResultTy parseMEMOperand(OperandVector &Operands);
63
64   OperandMatchResultTy parseOperand(OperandVector &Operands, StringRef Name);
65
66   OperandMatchResultTy
67   parseSparcAsmOperand(std::unique_ptr<SparcOperand> &Operand,
68                        bool isCall = false);
69
70   OperandMatchResultTy parseBranchModifiers(OperandVector &Operands);
71
72   // returns true if Tok is matched to a register and returns register in RegNo.
73   bool matchRegisterName(const AsmToken &Tok, unsigned &RegNo,
74                          unsigned &RegKind);
75
76   bool matchSparcAsmModifiers(const MCExpr *&EVal, SMLoc &EndLoc);
77   bool parseDirectiveWord(unsigned Size, SMLoc L);
78
79   bool is64Bit() const {
80     return STI.getTargetTuple().getArch() == TargetTuple::sparcv9;
81   }
82
83   void expandSET(MCInst &Inst, SMLoc IDLoc,
84                  SmallVectorImpl<MCInst> &Instructions);
85
86 public:
87   SparcAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser,
88                 const MCInstrInfo &MII,
89                 const MCTargetOptions &Options)
90       : MCTargetAsmParser(Options), STI(sti), Parser(parser) {
91     // Initialize the set of available features.
92     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
93   }
94
95 };
96
97   static unsigned IntRegs[32] = {
98     Sparc::G0, Sparc::G1, Sparc::G2, Sparc::G3,
99     Sparc::G4, Sparc::G5, Sparc::G6, Sparc::G7,
100     Sparc::O0, Sparc::O1, Sparc::O2, Sparc::O3,
101     Sparc::O4, Sparc::O5, Sparc::O6, Sparc::O7,
102     Sparc::L0, Sparc::L1, Sparc::L2, Sparc::L3,
103     Sparc::L4, Sparc::L5, Sparc::L6, Sparc::L7,
104     Sparc::I0, Sparc::I1, Sparc::I2, Sparc::I3,
105     Sparc::I4, Sparc::I5, Sparc::I6, Sparc::I7 };
106
107   static unsigned FloatRegs[32] = {
108     Sparc::F0,  Sparc::F1,  Sparc::F2,  Sparc::F3,
109     Sparc::F4,  Sparc::F5,  Sparc::F6,  Sparc::F7,
110     Sparc::F8,  Sparc::F9,  Sparc::F10, Sparc::F11,
111     Sparc::F12, Sparc::F13, Sparc::F14, Sparc::F15,
112     Sparc::F16, Sparc::F17, Sparc::F18, Sparc::F19,
113     Sparc::F20, Sparc::F21, Sparc::F22, Sparc::F23,
114     Sparc::F24, Sparc::F25, Sparc::F26, Sparc::F27,
115     Sparc::F28, Sparc::F29, Sparc::F30, Sparc::F31 };
116
117   static unsigned DoubleRegs[32] = {
118     Sparc::D0,  Sparc::D1,  Sparc::D2,  Sparc::D3,
119     Sparc::D4,  Sparc::D5,  Sparc::D6,  Sparc::D7,
120     Sparc::D8,  Sparc::D7,  Sparc::D8,  Sparc::D9,
121     Sparc::D12, Sparc::D13, Sparc::D14, Sparc::D15,
122     Sparc::D16, Sparc::D17, Sparc::D18, Sparc::D19,
123     Sparc::D20, Sparc::D21, Sparc::D22, Sparc::D23,
124     Sparc::D24, Sparc::D25, Sparc::D26, Sparc::D27,
125     Sparc::D28, Sparc::D29, Sparc::D30, Sparc::D31 };
126
127   static unsigned QuadFPRegs[32] = {
128     Sparc::Q0,  Sparc::Q1,  Sparc::Q2,  Sparc::Q3,
129     Sparc::Q4,  Sparc::Q5,  Sparc::Q6,  Sparc::Q7,
130     Sparc::Q8,  Sparc::Q9,  Sparc::Q10, Sparc::Q11,
131     Sparc::Q12, Sparc::Q13, Sparc::Q14, Sparc::Q15 };
132
133   static unsigned ASRRegs[32] = {
134     SP::Y,     SP::ASR1,  SP::ASR2,  SP::ASR3,
135     SP::ASR4,  SP::ASR5,  SP::ASR6, SP::ASR7,
136     SP::ASR8,  SP::ASR9,  SP::ASR10, SP::ASR11,
137     SP::ASR12, SP::ASR13, SP::ASR14, SP::ASR15,
138     SP::ASR16, SP::ASR17, SP::ASR18, SP::ASR19,
139     SP::ASR20, SP::ASR21, SP::ASR22, SP::ASR23,
140     SP::ASR24, SP::ASR25, SP::ASR26, SP::ASR27,
141     SP::ASR28, SP::ASR29, SP::ASR30, SP::ASR31};
142
143   static unsigned IntPairRegs[] = {
144     Sparc::G0_G1, Sparc::G2_G3, Sparc::G4_G5, Sparc::G6_G7,
145     Sparc::O0_O1, Sparc::O2_O3, Sparc::O4_O5, Sparc::O6_O7,
146     Sparc::L0_L1, Sparc::L2_L3, Sparc::L4_L5, Sparc::L6_L7,
147     Sparc::I0_I1, Sparc::I2_I3, Sparc::I4_I5, Sparc::I6_I7};
148
149 /// SparcOperand - Instances of this class represent a parsed Sparc machine
150 /// instruction.
151 class SparcOperand : public MCParsedAsmOperand {
152 public:
153   enum RegisterKind {
154     rk_None,
155     rk_IntReg,
156     rk_IntPairReg,
157     rk_FloatReg,
158     rk_DoubleReg,
159     rk_QuadReg,
160     rk_Special,
161   };
162
163 private:
164   enum KindTy {
165     k_Token,
166     k_Register,
167     k_Immediate,
168     k_MemoryReg,
169     k_MemoryImm
170   } Kind;
171
172   SMLoc StartLoc, EndLoc;
173
174   struct Token {
175     const char *Data;
176     unsigned Length;
177   };
178
179   struct RegOp {
180     unsigned RegNum;
181     RegisterKind Kind;
182   };
183
184   struct ImmOp {
185     const MCExpr *Val;
186   };
187
188   struct MemOp {
189     unsigned Base;
190     unsigned OffsetReg;
191     const MCExpr *Off;
192   };
193
194   union {
195     struct Token Tok;
196     struct RegOp Reg;
197     struct ImmOp Imm;
198     struct MemOp Mem;
199   };
200 public:
201   SparcOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
202
203   bool isToken() const override { return Kind == k_Token; }
204   bool isReg() const override { return Kind == k_Register; }
205   bool isImm() const override { return Kind == k_Immediate; }
206   bool isMem() const override { return isMEMrr() || isMEMri(); }
207   bool isMEMrr() const { return Kind == k_MemoryReg; }
208   bool isMEMri() const { return Kind == k_MemoryImm; }
209
210   bool isIntReg() const {
211     return (Kind == k_Register && Reg.Kind == rk_IntReg);
212   }
213
214   bool isFloatReg() const {
215     return (Kind == k_Register && Reg.Kind == rk_FloatReg);
216   }
217
218   bool isFloatOrDoubleReg() const {
219     return (Kind == k_Register && (Reg.Kind == rk_FloatReg
220                                    || Reg.Kind == rk_DoubleReg));
221   }
222
223
224   StringRef getToken() const {
225     assert(Kind == k_Token && "Invalid access!");
226     return StringRef(Tok.Data, Tok.Length);
227   }
228
229   unsigned getReg() const override {
230     assert((Kind == k_Register) && "Invalid access!");
231     return Reg.RegNum;
232   }
233
234   const MCExpr *getImm() const {
235     assert((Kind == k_Immediate) && "Invalid access!");
236     return Imm.Val;
237   }
238
239   unsigned getMemBase() const {
240     assert((Kind == k_MemoryReg || Kind == k_MemoryImm) && "Invalid access!");
241     return Mem.Base;
242   }
243
244   unsigned getMemOffsetReg() const {
245     assert((Kind == k_MemoryReg) && "Invalid access!");
246     return Mem.OffsetReg;
247   }
248
249   const MCExpr *getMemOff() const {
250     assert((Kind == k_MemoryImm) && "Invalid access!");
251     return Mem.Off;
252   }
253
254   /// getStartLoc - Get the location of the first token of this operand.
255   SMLoc getStartLoc() const override {
256     return StartLoc;
257   }
258   /// getEndLoc - Get the location of the last token of this operand.
259   SMLoc getEndLoc() const override {
260     return EndLoc;
261   }
262
263   void print(raw_ostream &OS) const override {
264     switch (Kind) {
265     case k_Token:     OS << "Token: " << getToken() << "\n"; break;
266     case k_Register:  OS << "Reg: #" << getReg() << "\n"; break;
267     case k_Immediate: OS << "Imm: " << getImm() << "\n"; break;
268     case k_MemoryReg: OS << "Mem: " << getMemBase() << "+"
269                          << getMemOffsetReg() << "\n"; break;
270     case k_MemoryImm: assert(getMemOff() != nullptr);
271       OS << "Mem: " << getMemBase()
272          << "+" << *getMemOff()
273          << "\n"; break;
274     }
275   }
276
277   void addRegOperands(MCInst &Inst, unsigned N) const {
278     assert(N == 1 && "Invalid number of operands!");
279     Inst.addOperand(MCOperand::createReg(getReg()));
280   }
281
282   void addImmOperands(MCInst &Inst, unsigned N) const {
283     assert(N == 1 && "Invalid number of operands!");
284     const MCExpr *Expr = getImm();
285     addExpr(Inst, Expr);
286   }
287
288   void addExpr(MCInst &Inst, const MCExpr *Expr) const{
289     // Add as immediate when possible.  Null MCExpr = 0.
290     if (!Expr)
291       Inst.addOperand(MCOperand::createImm(0));
292     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
293       Inst.addOperand(MCOperand::createImm(CE->getValue()));
294     else
295       Inst.addOperand(MCOperand::createExpr(Expr));
296   }
297
298   void addMEMrrOperands(MCInst &Inst, unsigned N) const {
299     assert(N == 2 && "Invalid number of operands!");
300
301     Inst.addOperand(MCOperand::createReg(getMemBase()));
302
303     assert(getMemOffsetReg() != 0 && "Invalid offset");
304     Inst.addOperand(MCOperand::createReg(getMemOffsetReg()));
305   }
306
307   void addMEMriOperands(MCInst &Inst, unsigned N) const {
308     assert(N == 2 && "Invalid number of operands!");
309
310     Inst.addOperand(MCOperand::createReg(getMemBase()));
311
312     const MCExpr *Expr = getMemOff();
313     addExpr(Inst, Expr);
314   }
315
316   static std::unique_ptr<SparcOperand> CreateToken(StringRef Str, SMLoc S) {
317     auto Op = make_unique<SparcOperand>(k_Token);
318     Op->Tok.Data = Str.data();
319     Op->Tok.Length = Str.size();
320     Op->StartLoc = S;
321     Op->EndLoc = S;
322     return Op;
323   }
324
325   static std::unique_ptr<SparcOperand> CreateReg(unsigned RegNum, unsigned Kind,
326                                                  SMLoc S, SMLoc E) {
327     auto Op = make_unique<SparcOperand>(k_Register);
328     Op->Reg.RegNum = RegNum;
329     Op->Reg.Kind   = (SparcOperand::RegisterKind)Kind;
330     Op->StartLoc = S;
331     Op->EndLoc = E;
332     return Op;
333   }
334
335   static std::unique_ptr<SparcOperand> CreateImm(const MCExpr *Val, SMLoc S,
336                                                  SMLoc E) {
337     auto Op = make_unique<SparcOperand>(k_Immediate);
338     Op->Imm.Val = Val;
339     Op->StartLoc = S;
340     Op->EndLoc = E;
341     return Op;
342   }
343
344   static bool MorphToIntPairReg(SparcOperand &Op) {
345     unsigned Reg = Op.getReg();
346     assert(Op.Reg.Kind == rk_IntReg);
347     unsigned regIdx = 32;
348     if (Reg >= Sparc::G0 && Reg <= Sparc::G7)
349       regIdx = Reg - Sparc::G0;
350     else if (Reg >= Sparc::O0 && Reg <= Sparc::O7)
351       regIdx = Reg - Sparc::O0 + 8;
352     else if (Reg >= Sparc::L0 && Reg <= Sparc::L7)
353       regIdx = Reg - Sparc::L0 + 16;
354     else if (Reg >= Sparc::I0 && Reg <= Sparc::I7)
355       regIdx = Reg - Sparc::I0 + 24;
356     if (regIdx % 2 || regIdx > 31)
357       return false;
358     Op.Reg.RegNum = IntPairRegs[regIdx / 2];
359     Op.Reg.Kind = rk_IntPairReg;
360     return true;
361   }
362
363   static bool MorphToDoubleReg(SparcOperand &Op) {
364     unsigned Reg = Op.getReg();
365     assert(Op.Reg.Kind == rk_FloatReg);
366     unsigned regIdx = Reg - Sparc::F0;
367     if (regIdx % 2 || regIdx > 31)
368       return false;
369     Op.Reg.RegNum = DoubleRegs[regIdx / 2];
370     Op.Reg.Kind = rk_DoubleReg;
371     return true;
372   }
373
374   static bool MorphToQuadReg(SparcOperand &Op) {
375     unsigned Reg = Op.getReg();
376     unsigned regIdx = 0;
377     switch (Op.Reg.Kind) {
378     default: llvm_unreachable("Unexpected register kind!");
379     case rk_FloatReg:
380       regIdx = Reg - Sparc::F0;
381       if (regIdx % 4 || regIdx > 31)
382         return false;
383       Reg = QuadFPRegs[regIdx / 4];
384       break;
385     case rk_DoubleReg:
386       regIdx =  Reg - Sparc::D0;
387       if (regIdx % 2 || regIdx > 31)
388         return false;
389       Reg = QuadFPRegs[regIdx / 2];
390       break;
391     }
392     Op.Reg.RegNum = Reg;
393     Op.Reg.Kind = rk_QuadReg;
394     return true;
395   }
396
397   static std::unique_ptr<SparcOperand>
398   MorphToMEMrr(unsigned Base, std::unique_ptr<SparcOperand> Op) {
399     unsigned offsetReg = Op->getReg();
400     Op->Kind = k_MemoryReg;
401     Op->Mem.Base = Base;
402     Op->Mem.OffsetReg = offsetReg;
403     Op->Mem.Off = nullptr;
404     return Op;
405   }
406
407   static std::unique_ptr<SparcOperand>
408   CreateMEMr(unsigned Base, SMLoc S, SMLoc E) {
409     auto Op = make_unique<SparcOperand>(k_MemoryReg);
410     Op->Mem.Base = Base;
411     Op->Mem.OffsetReg = Sparc::G0;  // always 0
412     Op->Mem.Off = nullptr;
413     Op->StartLoc = S;
414     Op->EndLoc = E;
415     return Op;
416   }
417
418   static std::unique_ptr<SparcOperand>
419   MorphToMEMri(unsigned Base, std::unique_ptr<SparcOperand> Op) {
420     const MCExpr *Imm  = Op->getImm();
421     Op->Kind = k_MemoryImm;
422     Op->Mem.Base = Base;
423     Op->Mem.OffsetReg = 0;
424     Op->Mem.Off = Imm;
425     return Op;
426   }
427 };
428
429 } // end namespace
430
431 void SparcAsmParser::expandSET(MCInst &Inst, SMLoc IDLoc,
432                                SmallVectorImpl<MCInst> &Instructions) {
433   MCOperand MCRegOp = Inst.getOperand(0);
434   MCOperand MCValOp = Inst.getOperand(1);
435   assert(MCRegOp.isReg());
436   assert(MCValOp.isImm() || MCValOp.isExpr());
437
438   // the imm operand can be either an expression or an immediate.
439   bool IsImm = Inst.getOperand(1).isImm();
440   int64_t RawImmValue = IsImm ? MCValOp.getImm() : 0;
441
442   // Allow either a signed or unsigned 32-bit immediate.
443   if (RawImmValue < -2147483648LL || RawImmValue > 4294967295LL) {
444     Error(IDLoc, "set: argument must be between -2147483648 and 4294967295");
445     return;
446   }
447
448   // If the value was expressed as a large unsigned number, that's ok.
449   // We want to see if it "looks like" a small signed number.
450   int32_t ImmValue = RawImmValue;
451   // For 'set' you can't use 'or' with a negative operand on V9 because
452   // that would splat the sign bit across the upper half of the destination
453   // register, whereas 'set' is defined to zero the high 32 bits.
454   bool IsEffectivelyImm13 =
455       IsImm && ((is64Bit() ? 0 : -4096) <= ImmValue && ImmValue < 4096);
456   const MCExpr *ValExpr;
457   if (IsImm)
458     ValExpr = MCConstantExpr::create(ImmValue, getContext());
459   else
460     ValExpr = MCValOp.getExpr();
461
462   MCOperand PrevReg = MCOperand::createReg(Sparc::G0);
463
464   // If not just a signed imm13 value, then either we use a 'sethi' with a
465   // following 'or', or a 'sethi' by itself if there are no more 1 bits.
466   // In either case, start with the 'sethi'.
467   if (!IsEffectivelyImm13) {
468     MCInst TmpInst;
469     const MCExpr *Expr =
470         SparcMCExpr::create(SparcMCExpr::VK_Sparc_HI, ValExpr, getContext());
471     TmpInst.setLoc(IDLoc);
472     TmpInst.setOpcode(SP::SETHIi);
473     TmpInst.addOperand(MCRegOp);
474     TmpInst.addOperand(MCOperand::createExpr(Expr));
475     Instructions.push_back(TmpInst);
476     PrevReg = MCRegOp;
477   }
478
479   // The low bits require touching in 3 cases:
480   // * A non-immediate value will always require both instructions.
481   // * An effectively imm13 value needs only an 'or' instruction.
482   // * Otherwise, an immediate that is not effectively imm13 requires the
483   //   'or' only if bits remain after clearing the 22 bits that 'sethi' set.
484   // If the low bits are known zeros, there's nothing to do.
485   // In the second case, and only in that case, must we NOT clear
486   // bits of the immediate value via the %lo() assembler function.
487   // Note also, the 'or' instruction doesn't mind a large value in the case
488   // where the operand to 'set' was 0xFFFFFzzz - it does exactly what you mean.
489   if (!IsImm || IsEffectivelyImm13 || (ImmValue & 0x3ff)) {
490     MCInst TmpInst;
491     const MCExpr *Expr;
492     if (IsEffectivelyImm13)
493       Expr = ValExpr;
494     else
495       Expr =
496           SparcMCExpr::create(SparcMCExpr::VK_Sparc_LO, ValExpr, getContext());
497     TmpInst.setLoc(IDLoc);
498     TmpInst.setOpcode(SP::ORri);
499     TmpInst.addOperand(MCRegOp);
500     TmpInst.addOperand(PrevReg);
501     TmpInst.addOperand(MCOperand::createExpr(Expr));
502     Instructions.push_back(TmpInst);
503   }
504 }
505
506 bool SparcAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
507                                              OperandVector &Operands,
508                                              MCStreamer &Out,
509                                              uint64_t &ErrorInfo,
510                                              bool MatchingInlineAsm) {
511   MCInst Inst;
512   SmallVector<MCInst, 8> Instructions;
513   unsigned MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,
514                                               MatchingInlineAsm);
515   switch (MatchResult) {
516   case Match_Success: {
517     switch (Inst.getOpcode()) {
518     default:
519       Inst.setLoc(IDLoc);
520       Instructions.push_back(Inst);
521       break;
522     case SP::SET:
523       expandSET(Inst, IDLoc, Instructions);
524       break;
525     }
526
527     for (const MCInst &I : Instructions) {
528       Out.EmitInstruction(I, STI);
529     }
530     return false;
531   }
532
533   case Match_MissingFeature:
534     return Error(IDLoc,
535                  "instruction requires a CPU feature not currently enabled");
536
537   case Match_InvalidOperand: {
538     SMLoc ErrorLoc = IDLoc;
539     if (ErrorInfo != ~0ULL) {
540       if (ErrorInfo >= Operands.size())
541         return Error(IDLoc, "too few operands for instruction");
542
543       ErrorLoc = ((SparcOperand &)*Operands[ErrorInfo]).getStartLoc();
544       if (ErrorLoc == SMLoc())
545         ErrorLoc = IDLoc;
546     }
547
548     return Error(ErrorLoc, "invalid operand for instruction");
549   }
550   case Match_MnemonicFail:
551     return Error(IDLoc, "invalid instruction mnemonic");
552   }
553   llvm_unreachable("Implement any new match types added!");
554 }
555
556 bool SparcAsmParser::
557 ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc)
558 {
559   const AsmToken &Tok = Parser.getTok();
560   StartLoc = Tok.getLoc();
561   EndLoc = Tok.getEndLoc();
562   RegNo = 0;
563   if (getLexer().getKind() != AsmToken::Percent)
564     return false;
565   Parser.Lex();
566   unsigned regKind = SparcOperand::rk_None;
567   if (matchRegisterName(Tok, RegNo, regKind)) {
568     Parser.Lex();
569     return false;
570   }
571
572   return Error(StartLoc, "invalid register name");
573 }
574
575 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
576                                  unsigned VariantID);
577
578 bool SparcAsmParser::ParseInstruction(ParseInstructionInfo &Info,
579                                       StringRef Name, SMLoc NameLoc,
580                                       OperandVector &Operands) {
581
582   // First operand in MCInst is instruction mnemonic.
583   Operands.push_back(SparcOperand::CreateToken(Name, NameLoc));
584
585   // apply mnemonic aliases, if any, so that we can parse operands correctly.
586   applyMnemonicAliases(Name, getAvailableFeatures(), 0);
587
588   if (getLexer().isNot(AsmToken::EndOfStatement)) {
589     // Read the first operand.
590     if (getLexer().is(AsmToken::Comma)) {
591       if (parseBranchModifiers(Operands) != MatchOperand_Success) {
592         SMLoc Loc = getLexer().getLoc();
593         Parser.eatToEndOfStatement();
594         return Error(Loc, "unexpected token");
595       }
596     }
597     if (parseOperand(Operands, Name) != MatchOperand_Success) {
598       SMLoc Loc = getLexer().getLoc();
599       Parser.eatToEndOfStatement();
600       return Error(Loc, "unexpected token");
601     }
602
603     while (getLexer().is(AsmToken::Comma)) {
604       Parser.Lex(); // Eat the comma.
605       // Parse and remember the operand.
606       if (parseOperand(Operands, Name) != MatchOperand_Success) {
607         SMLoc Loc = getLexer().getLoc();
608         Parser.eatToEndOfStatement();
609         return Error(Loc, "unexpected token");
610       }
611     }
612   }
613   if (getLexer().isNot(AsmToken::EndOfStatement)) {
614     SMLoc Loc = getLexer().getLoc();
615     Parser.eatToEndOfStatement();
616     return Error(Loc, "unexpected token");
617   }
618   Parser.Lex(); // Consume the EndOfStatement.
619   return false;
620 }
621
622 bool SparcAsmParser::
623 ParseDirective(AsmToken DirectiveID)
624 {
625   StringRef IDVal = DirectiveID.getString();
626
627   if (IDVal == ".byte")
628     return parseDirectiveWord(1, DirectiveID.getLoc());
629
630   if (IDVal == ".half")
631     return parseDirectiveWord(2, DirectiveID.getLoc());
632
633   if (IDVal == ".word")
634     return parseDirectiveWord(4, DirectiveID.getLoc());
635
636   if (IDVal == ".nword")
637     return parseDirectiveWord(is64Bit() ? 8 : 4, DirectiveID.getLoc());
638
639   if (is64Bit() && IDVal == ".xword")
640     return parseDirectiveWord(8, DirectiveID.getLoc());
641
642   if (IDVal == ".register") {
643     // For now, ignore .register directive.
644     Parser.eatToEndOfStatement();
645     return false;
646   }
647
648   // Let the MC layer to handle other directives.
649   return true;
650 }
651
652 bool SparcAsmParser:: parseDirectiveWord(unsigned Size, SMLoc L) {
653   if (getLexer().isNot(AsmToken::EndOfStatement)) {
654     for (;;) {
655       const MCExpr *Value;
656       if (getParser().parseExpression(Value))
657         return true;
658
659       getParser().getStreamer().EmitValue(Value, Size);
660
661       if (getLexer().is(AsmToken::EndOfStatement))
662         break;
663
664       // FIXME: Improve diagnostic.
665       if (getLexer().isNot(AsmToken::Comma))
666         return Error(L, "unexpected token in directive");
667       Parser.Lex();
668     }
669   }
670   Parser.Lex();
671   return false;
672 }
673
674 SparcAsmParser::OperandMatchResultTy
675 SparcAsmParser::parseMEMOperand(OperandVector &Operands) {
676
677   SMLoc S, E;
678   unsigned BaseReg = 0;
679
680   if (ParseRegister(BaseReg, S, E)) {
681     return MatchOperand_NoMatch;
682   }
683
684   switch (getLexer().getKind()) {
685   default: return MatchOperand_NoMatch;
686
687   case AsmToken::Comma:
688   case AsmToken::RBrac:
689   case AsmToken::EndOfStatement:
690     Operands.push_back(SparcOperand::CreateMEMr(BaseReg, S, E));
691     return MatchOperand_Success;
692
693   case AsmToken:: Plus:
694     Parser.Lex(); // Eat the '+'
695     break;
696   case AsmToken::Minus:
697     break;
698   }
699
700   std::unique_ptr<SparcOperand> Offset;
701   OperandMatchResultTy ResTy = parseSparcAsmOperand(Offset);
702   if (ResTy != MatchOperand_Success || !Offset)
703     return MatchOperand_NoMatch;
704
705   Operands.push_back(
706       Offset->isImm() ? SparcOperand::MorphToMEMri(BaseReg, std::move(Offset))
707                       : SparcOperand::MorphToMEMrr(BaseReg, std::move(Offset)));
708
709   return MatchOperand_Success;
710 }
711
712 SparcAsmParser::OperandMatchResultTy
713 SparcAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
714
715   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
716
717   // If there wasn't a custom match, try the generic matcher below. Otherwise,
718   // there was a match, but an error occurred, in which case, just return that
719   // the operand parsing failed.
720   if (ResTy == MatchOperand_Success || ResTy == MatchOperand_ParseFail)
721     return ResTy;
722
723   if (getLexer().is(AsmToken::LBrac)) {
724     // Memory operand
725     Operands.push_back(SparcOperand::CreateToken("[",
726                                                  Parser.getTok().getLoc()));
727     Parser.Lex(); // Eat the [
728
729     if (Mnemonic == "cas" || Mnemonic == "casx") {
730       SMLoc S = Parser.getTok().getLoc();
731       if (getLexer().getKind() != AsmToken::Percent)
732         return MatchOperand_NoMatch;
733       Parser.Lex(); // eat %
734
735       unsigned RegNo, RegKind;
736       if (!matchRegisterName(Parser.getTok(), RegNo, RegKind))
737         return MatchOperand_NoMatch;
738
739       Parser.Lex(); // Eat the identifier token.
740       SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer()-1);
741       Operands.push_back(SparcOperand::CreateReg(RegNo, RegKind, S, E));
742       ResTy = MatchOperand_Success;
743     } else {
744       ResTy = parseMEMOperand(Operands);
745     }
746
747     if (ResTy != MatchOperand_Success)
748       return ResTy;
749
750     if (!getLexer().is(AsmToken::RBrac))
751       return MatchOperand_ParseFail;
752
753     Operands.push_back(SparcOperand::CreateToken("]",
754                                                  Parser.getTok().getLoc()));
755     Parser.Lex(); // Eat the ]
756
757     // Parse an optional address-space identifier after the address.
758     if (getLexer().is(AsmToken::Integer)) {
759       std::unique_ptr<SparcOperand> Op;
760       ResTy = parseSparcAsmOperand(Op, false);
761       if (ResTy != MatchOperand_Success || !Op)
762         return MatchOperand_ParseFail;
763       Operands.push_back(std::move(Op));
764     }
765     return MatchOperand_Success;
766   }
767
768   std::unique_ptr<SparcOperand> Op;
769
770   ResTy = parseSparcAsmOperand(Op, (Mnemonic == "call"));
771   if (ResTy != MatchOperand_Success || !Op)
772     return MatchOperand_ParseFail;
773
774   // Push the parsed operand into the list of operands
775   Operands.push_back(std::move(Op));
776
777   return MatchOperand_Success;
778 }
779
780 SparcAsmParser::OperandMatchResultTy
781 SparcAsmParser::parseSparcAsmOperand(std::unique_ptr<SparcOperand> &Op,
782                                      bool isCall) {
783
784   SMLoc S = Parser.getTok().getLoc();
785   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
786   const MCExpr *EVal;
787
788   Op = nullptr;
789   switch (getLexer().getKind()) {
790   default:  break;
791
792   case AsmToken::Percent:
793     Parser.Lex(); // Eat the '%'.
794     unsigned RegNo;
795     unsigned RegKind;
796     if (matchRegisterName(Parser.getTok(), RegNo, RegKind)) {
797       StringRef name = Parser.getTok().getString();
798       Parser.Lex(); // Eat the identifier token.
799       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
800       switch (RegNo) {
801       default:
802         Op = SparcOperand::CreateReg(RegNo, RegKind, S, E);
803         break;
804       case Sparc::PSR:
805         Op = SparcOperand::CreateToken("%psr", S);
806         break;
807       case Sparc::FSR:
808         Op = SparcOperand::CreateToken("%fsr", S);
809         break;
810       case Sparc::WIM:
811         Op = SparcOperand::CreateToken("%wim", S);
812         break;
813       case Sparc::TBR:
814         Op = SparcOperand::CreateToken("%tbr", S);
815         break;
816       case Sparc::ICC:
817         if (name == "xcc")
818           Op = SparcOperand::CreateToken("%xcc", S);
819         else
820           Op = SparcOperand::CreateToken("%icc", S);
821         break;
822       }
823       break;
824     }
825     if (matchSparcAsmModifiers(EVal, E)) {
826       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
827       Op = SparcOperand::CreateImm(EVal, S, E);
828     }
829     break;
830
831   case AsmToken::Minus:
832   case AsmToken::Integer:
833   case AsmToken::LParen:
834   case AsmToken::Dot:
835     if (!getParser().parseExpression(EVal, E))
836       Op = SparcOperand::CreateImm(EVal, S, E);
837     break;
838
839   case AsmToken::Identifier: {
840     StringRef Identifier;
841     if (!getParser().parseIdentifier(Identifier)) {
842       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
843       MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
844
845       const MCExpr *Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
846                                                   getContext());
847       if (isCall &&
848           getContext().getObjectFileInfo()->getRelocM() == Reloc::PIC_)
849         Res = SparcMCExpr::create(SparcMCExpr::VK_Sparc_WPLT30, Res,
850                                   getContext());
851       Op = SparcOperand::CreateImm(Res, S, E);
852     }
853     break;
854   }
855   }
856   return (Op) ? MatchOperand_Success : MatchOperand_ParseFail;
857 }
858
859 SparcAsmParser::OperandMatchResultTy
860 SparcAsmParser::parseBranchModifiers(OperandVector &Operands) {
861
862   // parse (,a|,pn|,pt)+
863
864   while (getLexer().is(AsmToken::Comma)) {
865
866     Parser.Lex(); // Eat the comma
867
868     if (!getLexer().is(AsmToken::Identifier))
869       return MatchOperand_ParseFail;
870     StringRef modName = Parser.getTok().getString();
871     if (modName == "a" || modName == "pn" || modName == "pt") {
872       Operands.push_back(SparcOperand::CreateToken(modName,
873                                                    Parser.getTok().getLoc()));
874       Parser.Lex(); // eat the identifier.
875     }
876   }
877   return MatchOperand_Success;
878 }
879
880 bool SparcAsmParser::matchRegisterName(const AsmToken &Tok,
881                                        unsigned &RegNo,
882                                        unsigned &RegKind)
883 {
884   int64_t intVal = 0;
885   RegNo = 0;
886   RegKind = SparcOperand::rk_None;
887   if (Tok.is(AsmToken::Identifier)) {
888     StringRef name = Tok.getString();
889
890     // %fp
891     if (name.equals("fp")) {
892       RegNo = Sparc::I6;
893       RegKind = SparcOperand::rk_IntReg;
894       return true;
895     }
896     // %sp
897     if (name.equals("sp")) {
898       RegNo = Sparc::O6;
899       RegKind = SparcOperand::rk_IntReg;
900       return true;
901     }
902
903     if (name.equals("y")) {
904       RegNo = Sparc::Y;
905       RegKind = SparcOperand::rk_Special;
906       return true;
907     }
908
909     if (name.substr(0, 3).equals_lower("asr")
910         && !name.substr(3).getAsInteger(10, intVal)
911         && intVal > 0 && intVal < 32) {
912       RegNo = ASRRegs[intVal];
913       RegKind = SparcOperand::rk_Special;
914       return true;
915     }
916
917     // %fprs is an alias of %asr6.
918     if (name.equals("fprs")) {
919       RegNo = ASRRegs[6];
920       RegKind = SparcOperand::rk_Special;
921       return true;
922     }
923
924     if (name.equals("icc")) {
925       RegNo = Sparc::ICC;
926       RegKind = SparcOperand::rk_Special;
927       return true;
928     }
929
930     if (name.equals("psr")) {
931       RegNo = Sparc::PSR;
932       RegKind = SparcOperand::rk_Special;
933       return true;
934     }
935
936     if (name.equals("fsr")) {
937       RegNo = Sparc::FSR;
938       RegKind = SparcOperand::rk_Special;
939       return true;
940     }
941
942     if (name.equals("wim")) {
943       RegNo = Sparc::WIM;
944       RegKind = SparcOperand::rk_Special;
945       return true;
946     }
947
948     if (name.equals("tbr")) {
949       RegNo = Sparc::TBR;
950       RegKind = SparcOperand::rk_Special;
951       return true;
952     }
953
954     if (name.equals("xcc")) {
955       // FIXME:: check 64bit.
956       RegNo = Sparc::ICC;
957       RegKind = SparcOperand::rk_Special;
958       return true;
959     }
960
961     // %fcc0 - %fcc3
962     if (name.substr(0, 3).equals_lower("fcc")
963         && !name.substr(3).getAsInteger(10, intVal)
964         && intVal < 4) {
965       // FIXME: check 64bit and  handle %fcc1 - %fcc3
966       RegNo = Sparc::FCC0 + intVal;
967       RegKind = SparcOperand::rk_Special;
968       return true;
969     }
970
971     // %g0 - %g7
972     if (name.substr(0, 1).equals_lower("g")
973         && !name.substr(1).getAsInteger(10, intVal)
974         && intVal < 8) {
975       RegNo = IntRegs[intVal];
976       RegKind = SparcOperand::rk_IntReg;
977       return true;
978     }
979     // %o0 - %o7
980     if (name.substr(0, 1).equals_lower("o")
981         && !name.substr(1).getAsInteger(10, intVal)
982         && intVal < 8) {
983       RegNo = IntRegs[8 + intVal];
984       RegKind = SparcOperand::rk_IntReg;
985       return true;
986     }
987     if (name.substr(0, 1).equals_lower("l")
988         && !name.substr(1).getAsInteger(10, intVal)
989         && intVal < 8) {
990       RegNo = IntRegs[16 + intVal];
991       RegKind = SparcOperand::rk_IntReg;
992       return true;
993     }
994     if (name.substr(0, 1).equals_lower("i")
995         && !name.substr(1).getAsInteger(10, intVal)
996         && intVal < 8) {
997       RegNo = IntRegs[24 + intVal];
998       RegKind = SparcOperand::rk_IntReg;
999       return true;
1000     }
1001     // %f0 - %f31
1002     if (name.substr(0, 1).equals_lower("f")
1003         && !name.substr(1, 2).getAsInteger(10, intVal) && intVal < 32) {
1004       RegNo = FloatRegs[intVal];
1005       RegKind = SparcOperand::rk_FloatReg;
1006       return true;
1007     }
1008     // %f32 - %f62
1009     if (name.substr(0, 1).equals_lower("f")
1010         && !name.substr(1, 2).getAsInteger(10, intVal)
1011         && intVal >= 32 && intVal <= 62 && (intVal % 2 == 0)) {
1012       // FIXME: Check V9
1013       RegNo = DoubleRegs[intVal/2];
1014       RegKind = SparcOperand::rk_DoubleReg;
1015       return true;
1016     }
1017
1018     // %r0 - %r31
1019     if (name.substr(0, 1).equals_lower("r")
1020         && !name.substr(1, 2).getAsInteger(10, intVal) && intVal < 31) {
1021       RegNo = IntRegs[intVal];
1022       RegKind = SparcOperand::rk_IntReg;
1023       return true;
1024     }
1025   }
1026   return false;
1027 }
1028
1029 // Determine if an expression contains a reference to the symbol
1030 // "_GLOBAL_OFFSET_TABLE_".
1031 static bool hasGOTReference(const MCExpr *Expr) {
1032   switch (Expr->getKind()) {
1033   case MCExpr::Target:
1034     if (const SparcMCExpr *SE = dyn_cast<SparcMCExpr>(Expr))
1035       return hasGOTReference(SE->getSubExpr());
1036     break;
1037
1038   case MCExpr::Constant:
1039     break;
1040
1041   case MCExpr::Binary: {
1042     const MCBinaryExpr *BE = cast<MCBinaryExpr>(Expr);
1043     return hasGOTReference(BE->getLHS()) || hasGOTReference(BE->getRHS());
1044   }
1045
1046   case MCExpr::SymbolRef: {
1047     const MCSymbolRefExpr &SymRef = *cast<MCSymbolRefExpr>(Expr);
1048     return (SymRef.getSymbol().getName() == "_GLOBAL_OFFSET_TABLE_");
1049   }
1050
1051   case MCExpr::Unary:
1052     return hasGOTReference(cast<MCUnaryExpr>(Expr)->getSubExpr());
1053   }
1054   return false;
1055 }
1056
1057 bool SparcAsmParser::matchSparcAsmModifiers(const MCExpr *&EVal,
1058                                             SMLoc &EndLoc)
1059 {
1060   AsmToken Tok = Parser.getTok();
1061   if (!Tok.is(AsmToken::Identifier))
1062     return false;
1063
1064   StringRef name = Tok.getString();
1065
1066   SparcMCExpr::VariantKind VK = SparcMCExpr::parseVariantKind(name);
1067
1068   if (VK == SparcMCExpr::VK_Sparc_None)
1069     return false;
1070
1071   Parser.Lex(); // Eat the identifier.
1072   if (Parser.getTok().getKind() != AsmToken::LParen)
1073     return false;
1074
1075   Parser.Lex(); // Eat the LParen token.
1076   const MCExpr *subExpr;
1077   if (Parser.parseParenExpression(subExpr, EndLoc))
1078     return false;
1079
1080   bool isPIC = getContext().getObjectFileInfo()->getRelocM() == Reloc::PIC_;
1081
1082   // Ugly: if a sparc assembly expression says "%hi(...)" but the
1083   // expression within contains _GLOBAL_OFFSET_TABLE_, it REALLY means
1084   // %pc22. Same with %lo -> %pc10. Worse, if it doesn't contain that,
1085   // the meaning depends on whether the assembler was invoked with
1086   // -KPIC or not: if so, it really means %got22/%got10; if not, it
1087   // actually means what it said! Sigh, historical mistakes...
1088
1089   switch(VK) {
1090   default: break;
1091   case SparcMCExpr::VK_Sparc_LO:
1092     VK =  (hasGOTReference(subExpr)
1093            ? SparcMCExpr::VK_Sparc_PC10
1094            : (isPIC ? SparcMCExpr::VK_Sparc_GOT10 : VK));
1095     break;
1096   case SparcMCExpr::VK_Sparc_HI:
1097     VK =  (hasGOTReference(subExpr)
1098            ? SparcMCExpr::VK_Sparc_PC22
1099            : (isPIC ? SparcMCExpr::VK_Sparc_GOT22 : VK));
1100     break;
1101   }
1102
1103   EVal = SparcMCExpr::create(VK, subExpr, getContext());
1104   return true;
1105 }
1106
1107 extern "C" void LLVMInitializeSparcAsmParser() {
1108   RegisterMCAsmParser<SparcAsmParser> A(TheSparcTarget);
1109   RegisterMCAsmParser<SparcAsmParser> B(TheSparcV9Target);
1110   RegisterMCAsmParser<SparcAsmParser> C(TheSparcelTarget);
1111 }
1112
1113 #define GET_REGISTER_MATCHER
1114 #define GET_MATCHER_IMPLEMENTATION
1115 #include "SparcGenAsmMatcher.inc"
1116
1117 unsigned SparcAsmParser::validateTargetOperandClass(MCParsedAsmOperand &GOp,
1118                                                     unsigned Kind) {
1119   SparcOperand &Op = (SparcOperand &)GOp;
1120   if (Op.isFloatOrDoubleReg()) {
1121     switch (Kind) {
1122     default: break;
1123     case MCK_DFPRegs:
1124       if (!Op.isFloatReg() || SparcOperand::MorphToDoubleReg(Op))
1125         return MCTargetAsmParser::Match_Success;
1126       break;
1127     case MCK_QFPRegs:
1128       if (SparcOperand::MorphToQuadReg(Op))
1129         return MCTargetAsmParser::Match_Success;
1130       break;
1131     }
1132   }
1133   if (Op.isIntReg() && Kind == MCK_IntPair) {
1134     if (SparcOperand::MorphToIntPairReg(Op))
1135       return MCTargetAsmParser::Match_Success;
1136   }
1137   return Match_InvalidOperand;
1138 }