[Sparc] Add support for parsing sparcv9 instructions addc/subc/addccc/subccc.
[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                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
51                                MCStreamer &Out, unsigned &ErrorInfo,
52                                bool MatchingInlineAsm);
53   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
54   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
55                         SMLoc NameLoc,
56                         SmallVectorImpl<MCParsedAsmOperand*> &Operands);
57   bool ParseDirective(AsmToken DirectiveID);
58
59   virtual unsigned validateTargetOperandClass(MCParsedAsmOperand *Op,
60                                               unsigned Kind);
61
62   // Custom parse functions for Sparc specific operands.
63   OperandMatchResultTy
64   parseMEMOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands);
65
66   OperandMatchResultTy
67   parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
68                StringRef Name);
69
70   OperandMatchResultTy
71   parseSparcAsmOperand(SparcOperand *&Operand, bool isCall = false);
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 { return STI.getTargetTriple().startswith("sparcv9"); }
81 public:
82   SparcAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser,
83                 const MCInstrInfo &MII)
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   SparcOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
153
154   struct Token {
155     const char *Data;
156     unsigned Length;
157   };
158
159   struct RegOp {
160     unsigned RegNum;
161     RegisterKind Kind;
162   };
163
164   struct ImmOp {
165     const MCExpr *Val;
166   };
167
168   struct MemOp {
169     unsigned Base;
170     unsigned OffsetReg;
171     const MCExpr *Off;
172   };
173
174   union {
175     struct Token Tok;
176     struct RegOp Reg;
177     struct ImmOp Imm;
178     struct MemOp Mem;
179   };
180 public:
181   bool isToken() const { return Kind == k_Token; }
182   bool isReg() const { return Kind == k_Register; }
183   bool isImm() const { return Kind == k_Immediate; }
184   bool isMem() const { return isMEMrr() || isMEMri(); }
185   bool isMEMrr() const { return Kind == k_MemoryReg; }
186   bool isMEMri() const { return Kind == k_MemoryImm; }
187
188   bool isFloatReg() const {
189     return (Kind == k_Register && Reg.Kind == rk_FloatReg);
190   }
191
192   bool isFloatOrDoubleReg() const {
193     return (Kind == k_Register && (Reg.Kind == rk_FloatReg
194                                    || Reg.Kind == rk_DoubleReg));
195   }
196
197
198   StringRef getToken() const {
199     assert(Kind == k_Token && "Invalid access!");
200     return StringRef(Tok.Data, Tok.Length);
201   }
202
203   unsigned getReg() const {
204     assert((Kind == k_Register) && "Invalid access!");
205     return Reg.RegNum;
206   }
207
208   const MCExpr *getImm() const {
209     assert((Kind == k_Immediate) && "Invalid access!");
210     return Imm.Val;
211   }
212
213   unsigned getMemBase() const {
214     assert((Kind == k_MemoryReg || Kind == k_MemoryImm) && "Invalid access!");
215     return Mem.Base;
216   }
217
218   unsigned getMemOffsetReg() const {
219     assert((Kind == k_MemoryReg) && "Invalid access!");
220     return Mem.OffsetReg;
221   }
222
223   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.
229   SMLoc getStartLoc() const {
230     return StartLoc;
231   }
232   /// getEndLoc - Get the location of the last token of this operand.
233   SMLoc getEndLoc() const {
234     return EndLoc;
235   }
236
237   virtual void print(raw_ostream &OS) const {
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() != 0);
245       OS << "Mem: " << getMemBase()
246          << "+" << *getMemOff()
247          << "\n"; break;
248     }
249   }
250
251   void addRegOperands(MCInst &Inst, unsigned N) const {
252     assert(N == 1 && "Invalid number of operands!");
253     Inst.addOperand(MCOperand::CreateReg(getReg()));
254   }
255
256   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
262   void addExpr(MCInst &Inst, const MCExpr *Expr) const{
263     // Add as immediate when possible.  Null MCExpr = 0.
264     if (Expr == 0)
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
272   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
281   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
290   static SparcOperand *CreateToken(StringRef Str, SMLoc S) {
291     SparcOperand *Op = new 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
299   static SparcOperand *CreateReg(unsigned RegNum,
300                                  unsigned Kind,
301                                  SMLoc S, SMLoc E) {
302     SparcOperand *Op = new SparcOperand(k_Register);
303     Op->Reg.RegNum = RegNum;
304     Op->Reg.Kind   = (SparcOperand::RegisterKind)Kind;
305     Op->StartLoc = S;
306     Op->EndLoc = E;
307     return Op;
308   }
309
310   static SparcOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
311     SparcOperand *Op = new SparcOperand(k_Immediate);
312     Op->Imm.Val = Val;
313     Op->StartLoc = S;
314     Op->EndLoc = E;
315     return Op;
316   }
317
318   static SparcOperand *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 0;
324     Op->Reg.RegNum = DoubleRegs[regIdx / 2];
325     Op->Reg.Kind = rk_DoubleReg;
326     return Op;
327   }
328
329   static SparcOperand *MorphToQuadReg(SparcOperand *Op) {
330     unsigned Reg = Op->getReg();
331     unsigned regIdx = 0;
332     switch (Op->Reg.Kind) {
333     default: assert(0 && "Unexpected register kind!");
334     case rk_FloatReg:
335       regIdx = Reg - Sparc::F0;
336       if (regIdx % 4 || regIdx > 31)
337         return 0;
338       Reg = QuadFPRegs[regIdx / 4];
339       break;
340     case rk_DoubleReg:
341       regIdx =  Reg - Sparc::D0;
342       if (regIdx % 2 || regIdx > 31)
343         return 0;
344       Reg = QuadFPRegs[regIdx / 2];
345       break;
346     }
347     Op->Reg.RegNum  = Reg;
348     Op->Reg.Kind = rk_QuadReg;
349     return Op;
350   }
351
352   static SparcOperand *MorphToMEMrr(unsigned Base, SparcOperand *Op) {
353     unsigned offsetReg = Op->getReg();
354     Op->Kind = k_MemoryReg;
355     Op->Mem.Base = Base;
356     Op->Mem.OffsetReg = offsetReg;
357     Op->Mem.Off = 0;
358     return Op;
359   }
360
361   static SparcOperand *CreateMEMri(unsigned Base,
362                                  const MCExpr *Off,
363                                  SMLoc S, SMLoc E) {
364     SparcOperand *Op = new 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 SparcOperand *MorphToMEMri(unsigned Base, SparcOperand *Op) {
374     const MCExpr *Imm  = Op->getImm();
375     Op->Kind = k_MemoryImm;
376     Op->Mem.Base = Base;
377     Op->Mem.OffsetReg = 0;
378     Op->Mem.Off = Imm;
379     return Op;
380   }
381 };
382
383 } // end namespace
384
385 bool SparcAsmParser::
386 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
387                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
388                         MCStreamer &Out, unsigned &ErrorInfo,
389                         bool MatchingInlineAsm) {
390   MCInst Inst;
391   SmallVector<MCInst, 8> Instructions;
392   unsigned MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,
393                                               MatchingInlineAsm);
394   switch (MatchResult) {
395   default:
396     break;
397
398   case Match_Success: {
399     Inst.setLoc(IDLoc);
400     Out.EmitInstruction(Inst, STI);
401     return false;
402   }
403
404   case Match_MissingFeature:
405     return Error(IDLoc,
406                  "instruction requires a CPU feature not currently enabled");
407
408   case Match_InvalidOperand: {
409     SMLoc ErrorLoc = IDLoc;
410     if (ErrorInfo != ~0U) {
411       if (ErrorInfo >= Operands.size())
412         return Error(IDLoc, "too few operands for instruction");
413
414       ErrorLoc = ((SparcOperand*) Operands[ErrorInfo])->getStartLoc();
415       if (ErrorLoc == SMLoc())
416         ErrorLoc = IDLoc;
417     }
418
419     return Error(ErrorLoc, "invalid operand for instruction");
420   }
421   case Match_MnemonicFail:
422     return Error(IDLoc, "invalid instruction mnemonic");
423   }
424   return true;
425 }
426
427 bool SparcAsmParser::
428 ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc)
429 {
430   const AsmToken &Tok = Parser.getTok();
431   StartLoc = Tok.getLoc();
432   EndLoc = Tok.getEndLoc();
433   RegNo = 0;
434   if (getLexer().getKind() != AsmToken::Percent)
435     return false;
436   Parser.Lex();
437   unsigned regKind = SparcOperand::rk_None;
438   if (matchRegisterName(Tok, RegNo, regKind)) {
439     Parser.Lex();
440     return false;
441   }
442
443   return Error(StartLoc, "invalid register name");
444 }
445
446 bool SparcAsmParser::
447 ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
448                  SMLoc NameLoc,
449                  SmallVectorImpl<MCParsedAsmOperand*> &Operands)
450 {
451
452   // First operand in MCInst is instruction mnemonic.
453   Operands.push_back(SparcOperand::CreateToken(Name, NameLoc));
454
455   if (getLexer().isNot(AsmToken::EndOfStatement)) {
456     // Read the first operand.
457     if (parseOperand(Operands, Name) != MatchOperand_Success) {
458       SMLoc Loc = getLexer().getLoc();
459       Parser.eatToEndOfStatement();
460       return Error(Loc, "unexpected token");
461     }
462
463     while (getLexer().is(AsmToken::Comma)) {
464       Parser.Lex(); // Eat the comma.
465       // Parse and remember the operand.
466       if (parseOperand(Operands, Name) != MatchOperand_Success) {
467         SMLoc Loc = getLexer().getLoc();
468         Parser.eatToEndOfStatement();
469         return Error(Loc, "unexpected token");
470       }
471     }
472   }
473   if (getLexer().isNot(AsmToken::EndOfStatement)) {
474     SMLoc Loc = getLexer().getLoc();
475     Parser.eatToEndOfStatement();
476     return Error(Loc, "unexpected token");
477   }
478   Parser.Lex(); // Consume the EndOfStatement.
479   return false;
480 }
481
482 bool SparcAsmParser::
483 ParseDirective(AsmToken DirectiveID)
484 {
485   StringRef IDVal = DirectiveID.getString();
486
487   if (IDVal == ".byte")
488     return parseDirectiveWord(1, DirectiveID.getLoc());
489
490   if (IDVal == ".half")
491     return parseDirectiveWord(2, DirectiveID.getLoc());
492
493   if (IDVal == ".word")
494     return parseDirectiveWord(4, DirectiveID.getLoc());
495
496   if (IDVal == ".nword")
497     return parseDirectiveWord(is64Bit() ? 8 : 4, DirectiveID.getLoc());
498
499   if (is64Bit() && IDVal == ".xword")
500     return parseDirectiveWord(8, DirectiveID.getLoc());
501
502   if (IDVal == ".register") {
503     // For now, ignore .register directive.
504     Parser.eatToEndOfStatement();
505     return false;
506   }
507
508   // Let the MC layer to handle other directives.
509   return true;
510 }
511
512 bool SparcAsmParser:: parseDirectiveWord(unsigned Size, SMLoc L) {
513   if (getLexer().isNot(AsmToken::EndOfStatement)) {
514     for (;;) {
515       const MCExpr *Value;
516       if (getParser().parseExpression(Value))
517         return true;
518
519       getParser().getStreamer().EmitValue(Value, Size);
520
521       if (getLexer().is(AsmToken::EndOfStatement))
522         break;
523
524       // FIXME: Improve diagnostic.
525       if (getLexer().isNot(AsmToken::Comma))
526         return Error(L, "unexpected token in directive");
527       Parser.Lex();
528     }
529   }
530   Parser.Lex();
531   return false;
532 }
533
534 SparcAsmParser::OperandMatchResultTy SparcAsmParser::
535 parseMEMOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands)
536 {
537
538   SMLoc S, E;
539   unsigned BaseReg = 0;
540
541   if (ParseRegister(BaseReg, S, E)) {
542     return MatchOperand_NoMatch;
543   }
544
545   switch (getLexer().getKind()) {
546   default: return MatchOperand_NoMatch;
547
548   case AsmToken::Comma:
549   case AsmToken::RBrac:
550   case AsmToken::EndOfStatement:
551     Operands.push_back(SparcOperand::CreateMEMri(BaseReg, 0, S, E));
552     return MatchOperand_Success;
553
554   case AsmToken:: Plus:
555     Parser.Lex(); // Eat the '+'
556     break;
557   case AsmToken::Minus:
558     break;
559   }
560
561   SparcOperand *Offset = 0;
562   OperandMatchResultTy ResTy = parseSparcAsmOperand(Offset);
563   if (ResTy != MatchOperand_Success || !Offset)
564     return MatchOperand_NoMatch;
565
566   Offset = (Offset->isImm()
567             ? SparcOperand::MorphToMEMri(BaseReg, Offset)
568             : SparcOperand::MorphToMEMrr(BaseReg, Offset));
569
570   Operands.push_back(Offset);
571   return MatchOperand_Success;
572 }
573
574 SparcAsmParser::OperandMatchResultTy SparcAsmParser::
575 parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
576              StringRef Mnemonic)
577 {
578
579   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
580
581   // If there wasn't a custom match, try the generic matcher below. Otherwise,
582   // there was a match, but an error occurred, in which case, just return that
583   // the operand parsing failed.
584   if (ResTy == MatchOperand_Success || ResTy == MatchOperand_ParseFail)
585     return ResTy;
586
587   if (getLexer().is(AsmToken::LBrac)) {
588     // Memory operand
589     Operands.push_back(SparcOperand::CreateToken("[",
590                                                  Parser.getTok().getLoc()));
591     Parser.Lex(); // Eat the [
592
593     if (Mnemonic == "cas" || Mnemonic == "casx") {
594       SMLoc S = Parser.getTok().getLoc();
595       if (getLexer().getKind() != AsmToken::Percent)
596         return MatchOperand_NoMatch;
597       Parser.Lex(); // eat %
598
599       unsigned RegNo, RegKind;
600       if (!matchRegisterName(Parser.getTok(), RegNo, RegKind))
601         return MatchOperand_NoMatch;
602
603       Parser.Lex(); // Eat the identifier token.
604       SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer()-1);
605       Operands.push_back(SparcOperand::CreateReg(RegNo, RegKind, S, E));
606       ResTy = MatchOperand_Success;
607     } else {
608       ResTy = parseMEMOperand(Operands);
609     }
610
611     if (ResTy != MatchOperand_Success)
612       return ResTy;
613
614     if (!getLexer().is(AsmToken::RBrac))
615       return MatchOperand_ParseFail;
616
617     Operands.push_back(SparcOperand::CreateToken("]",
618                                                  Parser.getTok().getLoc()));
619     Parser.Lex(); // Eat the ]
620     return MatchOperand_Success;
621   }
622
623   SparcOperand *Op = 0;
624   ResTy = parseSparcAsmOperand(Op, (Mnemonic == "call"));
625   if (ResTy != MatchOperand_Success || !Op)
626     return MatchOperand_ParseFail;
627
628   // Push the parsed operand into the list of operands
629   Operands.push_back(Op);
630
631   return MatchOperand_Success;
632 }
633
634 SparcAsmParser::OperandMatchResultTy
635 SparcAsmParser::parseSparcAsmOperand(SparcOperand *&Op, bool isCall)
636 {
637
638   SMLoc S = Parser.getTok().getLoc();
639   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
640   const MCExpr *EVal;
641
642   Op = 0;
643   switch (getLexer().getKind()) {
644   default:  break;
645
646   case AsmToken::Percent:
647     Parser.Lex(); // Eat the '%'.
648     unsigned RegNo;
649     unsigned RegKind;
650     if (matchRegisterName(Parser.getTok(), RegNo, RegKind)) {
651       StringRef name = Parser.getTok().getString();
652       Parser.Lex(); // Eat the identifier token.
653       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
654       switch (RegNo) {
655       default:
656         Op = SparcOperand::CreateReg(RegNo, RegKind, S, E);
657         break;
658       case Sparc::Y:
659         Op = SparcOperand::CreateToken("%y", S);
660         break;
661
662       case Sparc::ICC:
663         if (name == "xcc")
664           Op = SparcOperand::CreateToken("%xcc", S);
665         else
666           Op = SparcOperand::CreateToken("%icc", S);
667         break;
668
669       case Sparc::FCC:
670         assert(name == "fcc0" && "Cannot handle %fcc other than %fcc0 yet");
671         Op = SparcOperand::CreateToken("%fcc0", S);
672         break;
673       }
674       break;
675     }
676     if (matchSparcAsmModifiers(EVal, E)) {
677       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
678       Op = SparcOperand::CreateImm(EVal, S, E);
679     }
680     break;
681
682   case AsmToken::Minus:
683   case AsmToken::Integer:
684     if (!getParser().parseExpression(EVal, E))
685       Op = SparcOperand::CreateImm(EVal, S, E);
686     break;
687
688   case AsmToken::Identifier: {
689     StringRef Identifier;
690     if (!getParser().parseIdentifier(Identifier)) {
691       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
692       MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier);
693
694       const MCExpr *Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
695                                                   getContext());
696       if (isCall &&
697           getContext().getObjectFileInfo()->getRelocM() == Reloc::PIC_)
698         Res = SparcMCExpr::Create(SparcMCExpr::VK_Sparc_WPLT30, Res,
699                                   getContext());
700       Op = SparcOperand::CreateImm(Res, S, E);
701     }
702     break;
703   }
704   }
705   return (Op) ? MatchOperand_Success : MatchOperand_ParseFail;
706 }
707
708 bool SparcAsmParser::matchRegisterName(const AsmToken &Tok,
709                                        unsigned &RegNo,
710                                        unsigned &RegKind)
711 {
712   int64_t intVal = 0;
713   RegNo = 0;
714   RegKind = SparcOperand::rk_None;
715   if (Tok.is(AsmToken::Identifier)) {
716     StringRef name = Tok.getString();
717
718     // %fp
719     if (name.equals("fp")) {
720       RegNo = Sparc::I6;
721       RegKind = SparcOperand::rk_IntReg;
722       return true;
723     }
724     // %sp
725     if (name.equals("sp")) {
726       RegNo = Sparc::O6;
727       RegKind = SparcOperand::rk_IntReg;
728       return true;
729     }
730
731     if (name.equals("y")) {
732       RegNo = Sparc::Y;
733       RegKind = SparcOperand::rk_Y;
734       return true;
735     }
736
737     if (name.equals("icc")) {
738       RegNo = Sparc::ICC;
739       RegKind = SparcOperand::rk_CCReg;
740       return true;
741     }
742
743     if (name.equals("xcc")) {
744       // FIXME:: check 64bit.
745       RegNo = Sparc::ICC;
746       RegKind = SparcOperand::rk_CCReg;
747       return true;
748     }
749
750     // %fcc0 - %fcc3
751     if (name.substr(0, 3).equals_lower("fcc")
752         && !name.substr(3).getAsInteger(10, intVal)
753         && intVal < 4) {
754       // FIXME: check 64bit and  handle %fcc1 - %fcc3
755       RegNo = Sparc::FCC;
756       RegKind = SparcOperand::rk_CCReg;
757       return true;
758     }
759
760     // %g0 - %g7
761     if (name.substr(0, 1).equals_lower("g")
762         && !name.substr(1).getAsInteger(10, intVal)
763         && intVal < 8) {
764       RegNo = IntRegs[intVal];
765       RegKind = SparcOperand::rk_IntReg;
766       return true;
767     }
768     // %o0 - %o7
769     if (name.substr(0, 1).equals_lower("o")
770         && !name.substr(1).getAsInteger(10, intVal)
771         && intVal < 8) {
772       RegNo = IntRegs[8 + intVal];
773       RegKind = SparcOperand::rk_IntReg;
774       return true;
775     }
776     if (name.substr(0, 1).equals_lower("l")
777         && !name.substr(1).getAsInteger(10, intVal)
778         && intVal < 8) {
779       RegNo = IntRegs[16 + intVal];
780       RegKind = SparcOperand::rk_IntReg;
781       return true;
782     }
783     if (name.substr(0, 1).equals_lower("i")
784         && !name.substr(1).getAsInteger(10, intVal)
785         && intVal < 8) {
786       RegNo = IntRegs[24 + intVal];
787       RegKind = SparcOperand::rk_IntReg;
788       return true;
789     }
790     // %f0 - %f31
791     if (name.substr(0, 1).equals_lower("f")
792         && !name.substr(1, 2).getAsInteger(10, intVal) && intVal < 32) {
793       RegNo = FloatRegs[intVal];
794       RegKind = SparcOperand::rk_FloatReg;
795       return true;
796     }
797     // %f32 - %f62
798     if (name.substr(0, 1).equals_lower("f")
799         && !name.substr(1, 2).getAsInteger(10, intVal)
800         && intVal >= 32 && intVal <= 62 && (intVal % 2 == 0)) {
801       // FIXME: Check V9
802       RegNo = DoubleRegs[intVal/2];
803       RegKind = SparcOperand::rk_DoubleReg;
804       return true;
805     }
806
807     // %r0 - %r31
808     if (name.substr(0, 1).equals_lower("r")
809         && !name.substr(1, 2).getAsInteger(10, intVal) && intVal < 31) {
810       RegNo = IntRegs[intVal];
811       RegKind = SparcOperand::rk_IntReg;
812       return true;
813     }
814   }
815   return false;
816 }
817
818 static bool hasGOTReference(const MCExpr *Expr) {
819   switch (Expr->getKind()) {
820   case MCExpr::Target:
821     if (const SparcMCExpr *SE = dyn_cast<SparcMCExpr>(Expr))
822       return hasGOTReference(SE->getSubExpr());
823     break;
824
825   case MCExpr::Constant:
826     break;
827
828   case MCExpr::Binary: {
829     const MCBinaryExpr *BE = cast<MCBinaryExpr>(Expr);
830     return hasGOTReference(BE->getLHS()) || hasGOTReference(BE->getRHS());
831   }
832
833   case MCExpr::SymbolRef: {
834     const MCSymbolRefExpr &SymRef = *cast<MCSymbolRefExpr>(Expr);
835     return (SymRef.getSymbol().getName() == "_GLOBAL_OFFSET_TABLE_");
836   }
837
838   case MCExpr::Unary:
839     return hasGOTReference(cast<MCUnaryExpr>(Expr)->getSubExpr());
840   }
841   return false;
842 }
843
844 bool SparcAsmParser::matchSparcAsmModifiers(const MCExpr *&EVal,
845                                             SMLoc &EndLoc)
846 {
847   AsmToken Tok = Parser.getTok();
848   if (!Tok.is(AsmToken::Identifier))
849     return false;
850
851   StringRef name = Tok.getString();
852
853   SparcMCExpr::VariantKind VK = SparcMCExpr::parseVariantKind(name);
854
855   if (VK == SparcMCExpr::VK_Sparc_None)
856     return false;
857
858   Parser.Lex(); // Eat the identifier.
859   if (Parser.getTok().getKind() != AsmToken::LParen)
860     return false;
861
862   Parser.Lex(); // Eat the LParen token.
863   const MCExpr *subExpr;
864   if (Parser.parseParenExpression(subExpr, EndLoc))
865     return false;
866
867   bool isPIC = getContext().getObjectFileInfo()->getRelocM() == Reloc::PIC_;
868
869   switch(VK) {
870   default: break;
871   case SparcMCExpr::VK_Sparc_LO:
872     VK =  (hasGOTReference(subExpr)
873            ? SparcMCExpr::VK_Sparc_PC10
874            : (isPIC ? SparcMCExpr::VK_Sparc_GOT10 : VK));
875     break;
876   case SparcMCExpr::VK_Sparc_HI:
877     VK =  (hasGOTReference(subExpr)
878            ? SparcMCExpr::VK_Sparc_PC22
879            : (isPIC ? SparcMCExpr::VK_Sparc_GOT22 : VK));
880     break;
881   }
882
883   EVal = SparcMCExpr::Create(VK, subExpr, getContext());
884   return true;
885 }
886
887
888 extern "C" void LLVMInitializeSparcAsmParser() {
889   RegisterMCAsmParser<SparcAsmParser> A(TheSparcTarget);
890   RegisterMCAsmParser<SparcAsmParser> B(TheSparcV9Target);
891 }
892
893 #define GET_REGISTER_MATCHER
894 #define GET_MATCHER_IMPLEMENTATION
895 #include "SparcGenAsmMatcher.inc"
896
897
898
899 unsigned SparcAsmParser::
900 validateTargetOperandClass(MCParsedAsmOperand *GOp,
901                            unsigned Kind)
902 {
903   SparcOperand *Op = (SparcOperand*)GOp;
904   if (Op->isFloatOrDoubleReg()) {
905     switch (Kind) {
906     default: break;
907     case MCK_DFPRegs:
908       if (!Op->isFloatReg() || SparcOperand::MorphToDoubleReg(Op))
909         return MCTargetAsmParser::Match_Success;
910       break;
911     case MCK_QFPRegs:
912       if (SparcOperand::MorphToQuadReg(Op))
913         return MCTargetAsmParser::Match_Success;
914       break;
915     }
916   }
917   return Match_InvalidOperand;
918 }