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