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