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