[Sparc] Add the initial implementation of an asm parser for sparc/sparcv9.
[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 "llvm/ADT/STLExtras.h"
12 #include "llvm/MC/MCContext.h"
13 #include "llvm/MC/MCInst.h"
14 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
15 #include "llvm/MC/MCStreamer.h"
16 #include "llvm/MC/MCSubtargetInfo.h"
17 #include "llvm/MC/MCTargetAsmParser.h"
18 #include "llvm/Support/TargetRegistry.h"
19
20 using namespace llvm;
21
22 // The generated AsmMatcher SparcGenAsmMatcher uses "Sparc" as the target
23 // namespace. But SPARC backend uses "SP" as its namespace.
24 namespace llvm {
25   namespace Sparc {
26     using namespace SP;
27   }
28 }
29
30 namespace {
31 class SparcAsmParser : public MCTargetAsmParser {
32
33   MCSubtargetInfo &STI;
34   MCAsmParser &Parser;
35
36   /// @name Auto-generated Match Functions
37   /// {
38
39 #define GET_ASSEMBLER_HEADER
40 #include "SparcGenAsmMatcher.inc"
41
42   /// }
43
44   // public interface of the MCTargetAsmParser.
45   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
46                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
47                                MCStreamer &Out, unsigned &ErrorInfo,
48                                bool MatchingInlineAsm);
49   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
50   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
51                         SMLoc NameLoc,
52                         SmallVectorImpl<MCParsedAsmOperand*> &Operands);
53   bool ParseDirective(AsmToken DirectiveID);
54
55
56   // Custom parse functions for Sparc specific operands.
57   OperandMatchResultTy
58   parseMEMrrOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands);
59   OperandMatchResultTy
60   parseMEMriOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands);
61
62   OperandMatchResultTy
63   parseMEMOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
64                   int ImmOffsetOrReg);
65
66   OperandMatchResultTy
67   parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
68                StringRef Name);
69
70   // returns true if Tok is matched to a register and returns register in RegNo.
71   bool matchRegisterName(const AsmToken &Tok, unsigned &RegNo, bool isDFP,
72                          bool isQFP);
73
74 public:
75   SparcAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser,
76                 const MCInstrInfo &MII)
77       : MCTargetAsmParser(), STI(sti), Parser(parser) {
78     // Initialize the set of available features.
79     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
80   }
81
82 };
83
84   static unsigned IntRegs[32] = {
85     Sparc::G0, Sparc::G1, Sparc::G2, Sparc::G3,
86     Sparc::G4, Sparc::G5, Sparc::G6, Sparc::G7,
87     Sparc::O0, Sparc::O1, Sparc::O2, Sparc::O3,
88     Sparc::O4, Sparc::O5, Sparc::O6, Sparc::O7,
89     Sparc::L0, Sparc::L1, Sparc::L2, Sparc::L3,
90     Sparc::L4, Sparc::L5, Sparc::L6, Sparc::L7,
91     Sparc::I0, Sparc::I1, Sparc::I2, Sparc::I3,
92     Sparc::I4, Sparc::I5, Sparc::I6, Sparc::I7 };
93
94   static unsigned FloatRegs[32] = {
95     Sparc::F0,  Sparc::F1,  Sparc::F2,  Sparc::F3,
96     Sparc::F4,  Sparc::F5,  Sparc::F6,  Sparc::F7,
97     Sparc::F8,  Sparc::F9,  Sparc::F10, Sparc::F11,
98     Sparc::F12, Sparc::F13, Sparc::F14, Sparc::F15,
99     Sparc::F16, Sparc::F17, Sparc::F18, Sparc::F19,
100     Sparc::F20, Sparc::F21, Sparc::F22, Sparc::F23,
101     Sparc::F24, Sparc::F25, Sparc::F26, Sparc::F27,
102     Sparc::F28, Sparc::F29, Sparc::F30, Sparc::F31 };
103
104   static unsigned DoubleRegs[32] = {
105     Sparc::D0,  Sparc::D1,  Sparc::D2,  Sparc::D3,
106     Sparc::D4,  Sparc::D5,  Sparc::D6,  Sparc::D7,
107     Sparc::D8,  Sparc::D7,  Sparc::D8,  Sparc::D9,
108     Sparc::D12, Sparc::D13, Sparc::D14, Sparc::D15,
109     Sparc::D16, Sparc::D17, Sparc::D18, Sparc::D19,
110     Sparc::D20, Sparc::D21, Sparc::D22, Sparc::D23,
111     Sparc::D24, Sparc::D25, Sparc::D26, Sparc::D27,
112     Sparc::D28, Sparc::D29, Sparc::D30, Sparc::D31 };
113
114   static unsigned QuadFPRegs[32] = {
115     Sparc::Q0,  Sparc::Q1,  Sparc::Q2,  Sparc::Q3,
116     Sparc::Q4,  Sparc::Q5,  Sparc::Q6,  Sparc::Q7,
117     Sparc::Q8,  Sparc::Q7,  Sparc::Q8,  Sparc::Q9,
118     Sparc::Q12, Sparc::Q13, Sparc::Q14, Sparc::Q15 };
119
120
121 /// SparcOperand - Instances of this class represent a parsed Sparc machine
122 /// instruction.
123 class SparcOperand : public MCParsedAsmOperand {
124 public:
125   enum RegisterKind {
126     rk_None,
127     rk_IntReg,
128     rk_FloatReg,
129     rk_DoubleReg,
130     rk_QuadReg,
131     rk_CCReg,
132     rk_Y
133   };
134 private:
135   enum KindTy {
136     k_Token,
137     k_Register,
138     k_Immediate,
139     k_MemoryReg,
140     k_MemoryImm
141   } Kind;
142
143   SMLoc StartLoc, EndLoc;
144
145   SparcOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
146
147   struct Token {
148     const char *Data;
149     unsigned Length;
150   };
151
152   struct RegOp {
153     unsigned RegNum;
154     RegisterKind Kind;
155   };
156
157   struct ImmOp {
158     const MCExpr *Val;
159   };
160
161   struct MemOp {
162     unsigned Base;
163     unsigned OffsetReg;
164     const MCExpr *Off;
165   };
166
167   union {
168     struct Token Tok;
169     struct RegOp Reg;
170     struct ImmOp Imm;
171     struct MemOp Mem;
172   };
173 public:
174   bool isToken() const { return Kind == k_Token; }
175   bool isReg() const { return Kind == k_Register; }
176   bool isImm() const { return Kind == k_Immediate; }
177   bool isMem() const { return isMEMrr() || isMEMri(); }
178   bool isMEMrr() const { return Kind == k_MemoryReg; }
179   bool isMEMri() const { return Kind == k_MemoryImm; }
180
181   StringRef getToken() const {
182     assert(Kind == k_Token && "Invalid access!");
183     return StringRef(Tok.Data, Tok.Length);
184   }
185
186   unsigned getReg() const {
187     assert((Kind == k_Register) && "Invalid access!");
188     return Reg.RegNum;
189   }
190
191   const MCExpr *getImm() const {
192     assert((Kind == k_Immediate) && "Invalid access!");
193     return Imm.Val;
194   }
195
196   unsigned getMemBase() const {
197     assert((Kind == k_MemoryReg || Kind == k_MemoryImm) && "Invalid access!");
198     return Mem.Base;
199   }
200
201   unsigned getMemOffsetReg() const {
202     assert((Kind == k_MemoryReg) && "Invalid access!");
203     return Mem.OffsetReg;
204   }
205
206   const MCExpr *getMemOff() const {
207     assert((Kind == k_MemoryImm) && "Invalid access!");
208     return Mem.Off;
209   }
210
211   /// getStartLoc - Get the location of the first token of this operand.
212   SMLoc getStartLoc() const {
213     return StartLoc;
214   }
215   /// getEndLoc - Get the location of the last token of this operand.
216   SMLoc getEndLoc() const {
217     return EndLoc;
218   }
219
220   virtual void print(raw_ostream &OS) const {
221     switch (Kind) {
222     case k_Token:     OS << "Token: " << getToken() << "\n"; break;
223     case k_Register:  OS << "Reg: #" << getReg() << "\n"; break;
224     case k_Immediate: OS << "Imm: " << getImm() << "\n"; break;
225     case k_MemoryReg: OS << "Mem: " << getMemBase() << "+"
226                          << getMemOffsetReg() << "\n"; break;
227     case k_MemoryImm: assert(getMemOff() != 0);
228       OS << "Mem: " << getMemBase()
229          << "+" << *getMemOff()
230          << "\n"; break;
231     }
232   }
233
234   void addRegOperands(MCInst &Inst, unsigned N) const {
235     assert(N == 1 && "Invalid number of operands!");
236     Inst.addOperand(MCOperand::CreateReg(getReg()));
237   }
238
239   void addImmOperands(MCInst &Inst, unsigned N) const {
240     assert(N == 1 && "Invalid number of operands!");
241     const MCExpr *Expr = getImm();
242     addExpr(Inst, Expr);
243   }
244
245   void addExpr(MCInst &Inst, const MCExpr *Expr) const{
246     // Add as immediate when possible.  Null MCExpr = 0.
247     if (Expr == 0)
248       Inst.addOperand(MCOperand::CreateImm(0));
249     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
250       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
251     else
252       Inst.addOperand(MCOperand::CreateExpr(Expr));
253   }
254
255   void addMEMrrOperands(MCInst &Inst, unsigned N) const {
256     assert(N == 2 && "Invalid number of operands!");
257
258     Inst.addOperand(MCOperand::CreateReg(getMemBase()));
259
260     assert(getMemOffsetReg() != 0 && "Invalid offset");
261     Inst.addOperand(MCOperand::CreateReg(getMemOffsetReg()));
262   }
263
264   void addMEMriOperands(MCInst &Inst, unsigned N) const {
265     assert(N == 2 && "Invalid number of operands!");
266
267     Inst.addOperand(MCOperand::CreateReg(getMemBase()));
268
269     const MCExpr *Expr = getMemOff();
270     addExpr(Inst, Expr);
271   }
272
273   static SparcOperand *CreateToken(StringRef Str, SMLoc S) {
274     SparcOperand *Op = new SparcOperand(k_Token);
275     Op->Tok.Data = Str.data();
276     Op->Tok.Length = Str.size();
277     Op->StartLoc = S;
278     Op->EndLoc = S;
279     return Op;
280   }
281
282   static SparcOperand *CreateReg(unsigned RegNum,
283                                  SparcOperand::RegisterKind Kind,
284                                  SMLoc S, SMLoc E) {
285     SparcOperand *Op = new SparcOperand(k_Register);
286     Op->Reg.RegNum = RegNum;
287     Op->Reg.Kind   = Kind;
288     Op->StartLoc = S;
289     Op->EndLoc = E;
290     return Op;
291   }
292
293   static SparcOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
294     SparcOperand *Op = new SparcOperand(k_Immediate);
295     Op->Imm.Val = Val;
296     Op->StartLoc = S;
297     Op->EndLoc = E;
298     return Op;
299   }
300
301
302 };
303
304 } // end namespace
305
306 bool SparcAsmParser::
307 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
308                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
309                         MCStreamer &Out, unsigned &ErrorInfo,
310                         bool MatchingInlineAsm) {
311   MCInst Inst;
312   SmallVector<MCInst, 8> Instructions;
313   unsigned MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,
314                                               MatchingInlineAsm);
315   switch (MatchResult) {
316   default:
317     break;
318
319   case Match_Success: {
320     Inst.setLoc(IDLoc);
321     Out.EmitInstruction(Inst);
322     return false;
323   }
324
325   case Match_MissingFeature:
326     return Error(IDLoc,
327                  "instruction requires a CPU feature not currently enabled");
328
329   case Match_InvalidOperand: {
330     SMLoc ErrorLoc = IDLoc;
331     if (ErrorInfo != ~0U) {
332       if (ErrorInfo >= Operands.size())
333         return Error(IDLoc, "too few operands for instruction");
334
335       ErrorLoc = ((SparcOperand*) Operands[ErrorInfo])->getStartLoc();
336       if (ErrorLoc == SMLoc())
337         ErrorLoc = IDLoc;
338     }
339
340     return Error(ErrorLoc, "invalid operand for instruction");
341   }
342   case Match_MnemonicFail:
343     return Error(IDLoc, "invalid instruction");
344   }
345   return true;
346 }
347
348 bool SparcAsmParser::
349 ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc)
350 {
351   const AsmToken &Tok = Parser.getTok();
352   StartLoc = Tok.getLoc();
353   EndLoc = Tok.getEndLoc();
354   RegNo = 0;
355   if (getLexer().getKind() != AsmToken::Percent)
356     return false;
357   Parser.Lex();
358   if (matchRegisterName(Tok, RegNo, false, false)) {
359     Parser.Lex();
360     return false;
361   }
362
363   return Error(StartLoc, "invalid register name");
364 }
365
366 bool SparcAsmParser::
367 ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
368                  SMLoc NameLoc,
369                  SmallVectorImpl<MCParsedAsmOperand*> &Operands)
370 {
371   // Check if we have valid mnemonic.
372   if (!mnemonicIsValid(Name, 0)) {
373     Parser.eatToEndOfStatement();
374     return Error(NameLoc, "Unknown instruction");
375   }
376   // First operand in MCInst is instruction mnemonic.
377   Operands.push_back(SparcOperand::CreateToken(Name, NameLoc));
378
379   if (getLexer().isNot(AsmToken::EndOfStatement)) {
380     // Read the first operand.
381     if (parseOperand(Operands, Name) != MatchOperand_Success) {
382       SMLoc Loc = getLexer().getLoc();
383       Parser.eatToEndOfStatement();
384       return Error(Loc, "unexpected token");
385     }
386
387     while (getLexer().is(AsmToken::Comma)) {
388       Parser.Lex(); // Eat the comma.
389       // Parse and remember the operand.
390       if (parseOperand(Operands, Name) != MatchOperand_Success) {
391         SMLoc Loc = getLexer().getLoc();
392         Parser.eatToEndOfStatement();
393         return Error(Loc, "unexpected token");
394       }
395     }
396   }
397   if (getLexer().isNot(AsmToken::EndOfStatement)) {
398     SMLoc Loc = getLexer().getLoc();
399     Parser.eatToEndOfStatement();
400     return Error(Loc, "unexpected token");
401   }
402   Parser.Lex(); // Consume the EndOfStatement.
403   return false;
404 }
405
406 bool SparcAsmParser::
407 ParseDirective(AsmToken DirectiveID)
408 {
409   // Ignore all directives for now.
410   Parser.eatToEndOfStatement();
411   return false;
412 }
413
414 SparcAsmParser::OperandMatchResultTy SparcAsmParser::
415 parseMEMOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
416                 int ImmOffsetOrReg)
417 {
418   // FIXME: Implement memory operand parsing here.
419   return MatchOperand_NoMatch;
420 }
421
422 SparcAsmParser::OperandMatchResultTy SparcAsmParser::
423 parseMEMrrOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands)
424 {
425   return parseMEMOperand(Operands, 2);
426 }
427
428 SparcAsmParser::OperandMatchResultTy SparcAsmParser::
429 parseMEMriOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands)
430 {
431   return parseMEMOperand(Operands, 1);
432 }
433
434 SparcAsmParser::OperandMatchResultTy SparcAsmParser::
435 parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
436              StringRef Mnemonic)
437 {
438   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
439   if (ResTy == MatchOperand_Success)
440     return ResTy;
441   // If there wasn't a custom match, try the generic matcher below. Otherwise,
442   // there was a match, but an error occurred, in which case, just return that
443   // the operand parsing failed.
444   if (ResTy == MatchOperand_ParseFail)
445     return ResTy;
446
447   SMLoc S = Parser.getTok().getLoc();
448   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
449   const MCExpr *EVal;
450   SparcOperand *Op;
451   switch (getLexer().getKind()) {
452   case AsmToken::Percent:
453     Parser.Lex(); // Eat the '%'.
454     unsigned RegNo;
455     if (matchRegisterName(Parser.getTok(), RegNo, false, false)) {
456       Parser.Lex(); // Eat the identifier token.
457       Op = SparcOperand::CreateReg(RegNo, SparcOperand::rk_None, S, E);
458       break;
459     }
460     // FIXME: Handle modifiers like %hi, %lo etc.,
461     return MatchOperand_ParseFail;
462
463   case AsmToken::Minus:
464   case AsmToken::Integer:
465     if (getParser().parseExpression(EVal))
466       return MatchOperand_ParseFail;
467
468     Op = SparcOperand::CreateImm(EVal, S, E);
469     break;
470
471   case AsmToken::Identifier: {
472     StringRef Identifier;
473     if (getParser().parseIdentifier(Identifier))
474       return MatchOperand_ParseFail;
475     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
476     MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier);
477
478     // Otherwise create a symbol reference.
479     const MCExpr *Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
480                                                 getContext());
481
482     Op = SparcOperand::CreateImm(Res, S, E);
483     break;
484   }
485
486   case AsmToken::LBrac:  // handle [
487     return parseMEMOperand(Operands, 0);
488
489   default:
490     return MatchOperand_ParseFail;
491   }
492   // Push the parsed operand into the list of operands
493   Operands.push_back(Op);
494   return MatchOperand_Success;
495 }
496
497 bool SparcAsmParser::matchRegisterName(const AsmToken &Tok,
498                                        unsigned &RegNo,
499                                        bool isDFP,
500                                        bool isQFP)
501 {
502   int64_t intVal = 0;
503   RegNo = 0;
504   if (Tok.is(AsmToken::Identifier)) {
505     StringRef name = Tok.getString();
506
507     // %fp
508     if (name.equals("fp")) {
509       RegNo = Sparc::I6;
510       return true;
511     }
512     // %sp
513     if (name.equals("sp")) {
514       RegNo = Sparc::O6;
515       return true;
516     }
517
518     if (name.equals("y")) {
519       RegNo = Sparc::Y;
520       return true;
521     }
522
523     if (name.equals("icc")) {
524       RegNo = Sparc::ICC;
525       return true;
526     }
527
528     if (name.equals("xcc")) {
529       // FIXME:: check 64bit.
530       RegNo = Sparc::ICC;
531       return true;
532     }
533
534     // %fcc0 - %fcc3
535     if (name.substr(0, 3).equals_lower("fcc")
536         && !name.substr(3).getAsInteger(10, intVal)
537         && intVal < 4) {
538       // FIXME: check 64bit and  handle %fcc1 - %fcc3
539       RegNo = Sparc::FCC;
540       return true;
541     }
542
543     // %g0 - %g7
544     if (name.substr(0, 1).equals_lower("g")
545         && !name.substr(1).getAsInteger(10, intVal)
546         && intVal < 8) {
547       RegNo = IntRegs[intVal];
548       return true;
549     }
550     // %o0 - %o7
551     if (name.substr(0, 1).equals_lower("o")
552         && !name.substr(1).getAsInteger(10, intVal)
553         && intVal < 8) {
554       RegNo = IntRegs[8 + intVal];
555       return true;
556     }
557     if (name.substr(0, 1).equals_lower("l")
558         && !name.substr(1).getAsInteger(10, intVal)
559         && intVal < 8) {
560       RegNo = IntRegs[16 + intVal];
561       return true;
562     }
563     if (name.substr(0, 1).equals_lower("i")
564         && !name.substr(1).getAsInteger(10, intVal)
565         && intVal < 8) {
566       RegNo = IntRegs[24 + intVal];
567       return true;
568     }
569     // %f0 - %f31
570     if (name.substr(0, 1).equals_lower("f")
571         && !name.substr(1, 2).getAsInteger(10, intVal) && intVal < 32) {
572       if (isDFP && (intVal%2 == 0)) {
573         RegNo = DoubleRegs[intVal/2];
574       } else if (isQFP && (intVal%4 == 0)) {
575         RegNo = QuadFPRegs[intVal/4];
576       } else {
577         RegNo = FloatRegs[intVal];
578       }
579       return true;
580     }
581     // %f32 - %f62
582     if (name.substr(0, 1).equals_lower("f")
583         && !name.substr(1, 2).getAsInteger(10, intVal)
584         && intVal >= 32 && intVal <= 62 && (intVal % 2 == 0)) {
585       if (isDFP) {
586         RegNo = DoubleRegs[16 + intVal/2];
587       } else if (isQFP && (intVal % 4 == 0)) {
588         RegNo = QuadFPRegs[8 + intVal/4];
589       } else {
590         return false;
591       }
592       return true;
593     }
594
595     // %r0 - %r31
596     if (name.substr(0, 1).equals_lower("r")
597         && !name.substr(1, 2).getAsInteger(10, intVal) && intVal < 31) {
598       RegNo = IntRegs[intVal];
599       return true;
600     }
601   }
602   return false;
603 }
604
605
606
607 extern "C" void LLVMInitializeSparcAsmParser() {
608   RegisterMCAsmParser<SparcAsmParser> A(TheSparcTarget);
609   RegisterMCAsmParser<SparcAsmParser> B(TheSparcV9Target);
610 }
611
612 #define GET_REGISTER_MATCHER
613 #define GET_MATCHER_IMPLEMENTATION
614 #include "SparcGenAsmMatcher.inc"