Move some sub-register index calculations to CodeGenRegisters.cpp
[oota-llvm.git] / utils / TableGen / CodeGenTarget.cpp
1 //===- CodeGenTarget.cpp - CodeGen Target Class Wrapper -------------------===//
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 // This class wraps target description classes used by the various code
11 // generation TableGen backends.  This makes it easier to access the data and
12 // provides a single place that needs to check it for validity.  All of these
13 // classes throw exceptions on error conditions.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "CodeGenTarget.h"
18 #include "CodeGenIntrinsics.h"
19 #include "Record.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Support/CommandLine.h"
23 #include <algorithm>
24 using namespace llvm;
25
26 static cl::opt<unsigned>
27 AsmParserNum("asmparsernum", cl::init(0),
28              cl::desc("Make -gen-asm-parser emit assembly parser #N"));
29
30 static cl::opt<unsigned>
31 AsmWriterNum("asmwriternum", cl::init(0),
32              cl::desc("Make -gen-asm-writer emit assembly writer #N"));
33
34 /// getValueType - Return the MVT::SimpleValueType that the specified TableGen
35 /// record corresponds to.
36 MVT::SimpleValueType llvm::getValueType(Record *Rec) {
37   return (MVT::SimpleValueType)Rec->getValueAsInt("Value");
38 }
39
40 std::string llvm::getName(MVT::SimpleValueType T) {
41   switch (T) {
42   case MVT::Other:   return "UNKNOWN";
43   case MVT::iPTR:    return "TLI.getPointerTy()";
44   case MVT::iPTRAny: return "TLI.getPointerTy()";
45   default: return getEnumName(T);
46   }
47 }
48
49 std::string llvm::getEnumName(MVT::SimpleValueType T) {
50   switch (T) {
51   case MVT::Other:    return "MVT::Other";
52   case MVT::i1:       return "MVT::i1";
53   case MVT::i8:       return "MVT::i8";
54   case MVT::i16:      return "MVT::i16";
55   case MVT::i32:      return "MVT::i32";
56   case MVT::i64:      return "MVT::i64";
57   case MVT::i128:     return "MVT::i128";
58   case MVT::iAny:     return "MVT::iAny";
59   case MVT::fAny:     return "MVT::fAny";
60   case MVT::vAny:     return "MVT::vAny";
61   case MVT::f32:      return "MVT::f32";
62   case MVT::f64:      return "MVT::f64";
63   case MVT::f80:      return "MVT::f80";
64   case MVT::f128:     return "MVT::f128";
65   case MVT::ppcf128:  return "MVT::ppcf128";
66   case MVT::x86mmx:   return "MVT::x86mmx";
67   case MVT::Glue:     return "MVT::Glue";
68   case MVT::isVoid:   return "MVT::isVoid";
69   case MVT::v2i8:     return "MVT::v2i8";
70   case MVT::v4i8:     return "MVT::v4i8";
71   case MVT::v8i8:     return "MVT::v8i8";
72   case MVT::v16i8:    return "MVT::v16i8";
73   case MVT::v32i8:    return "MVT::v32i8";
74   case MVT::v2i16:    return "MVT::v2i16";
75   case MVT::v4i16:    return "MVT::v4i16";
76   case MVT::v8i16:    return "MVT::v8i16";
77   case MVT::v16i16:   return "MVT::v16i16";
78   case MVT::v2i32:    return "MVT::v2i32";
79   case MVT::v4i32:    return "MVT::v4i32";
80   case MVT::v8i32:    return "MVT::v8i32";
81   case MVT::v1i64:    return "MVT::v1i64";
82   case MVT::v2i64:    return "MVT::v2i64";
83   case MVT::v4i64:    return "MVT::v4i64";
84   case MVT::v8i64:    return "MVT::v8i64";
85   case MVT::v2f32:    return "MVT::v2f32";
86   case MVT::v4f32:    return "MVT::v4f32";
87   case MVT::v8f32:    return "MVT::v8f32";
88   case MVT::v2f64:    return "MVT::v2f64";
89   case MVT::v4f64:    return "MVT::v4f64";
90   case MVT::Metadata: return "MVT::Metadata";
91   case MVT::iPTR:     return "MVT::iPTR";
92   case MVT::iPTRAny:  return "MVT::iPTRAny";
93   default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
94   }
95 }
96
97 /// getQualifiedName - Return the name of the specified record, with a
98 /// namespace qualifier if the record contains one.
99 ///
100 std::string llvm::getQualifiedName(const Record *R) {
101   std::string Namespace;
102   if (R->getValue("Namespace"))
103      Namespace = R->getValueAsString("Namespace");
104   if (Namespace.empty()) return R->getName();
105   return Namespace + "::" + R->getName();
106 }
107
108
109 /// getTarget - Return the current instance of the Target class.
110 ///
111 CodeGenTarget::CodeGenTarget(RecordKeeper &records)
112   : Records(records), RegBank(0) {
113   std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
114   if (Targets.size() == 0)
115     throw std::string("ERROR: No 'Target' subclasses defined!");
116   if (Targets.size() != 1)
117     throw std::string("ERROR: Multiple subclasses of Target defined!");
118   TargetRec = Targets[0];
119 }
120
121
122 const std::string &CodeGenTarget::getName() const {
123   return TargetRec->getName();
124 }
125
126 std::string CodeGenTarget::getInstNamespace() const {
127   for (inst_iterator i = inst_begin(), e = inst_end(); i != e; ++i) {
128     // Make sure not to pick up "TargetOpcode" by accidentally getting
129     // the namespace off the PHI instruction or something.
130     if ((*i)->Namespace != "TargetOpcode")
131       return (*i)->Namespace;
132   }
133
134   return "";
135 }
136
137 Record *CodeGenTarget::getInstructionSet() const {
138   return TargetRec->getValueAsDef("InstructionSet");
139 }
140
141
142 /// getAsmParser - Return the AssemblyParser definition for this target.
143 ///
144 Record *CodeGenTarget::getAsmParser() const {
145   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
146   if (AsmParserNum >= LI.size())
147     throw "Target does not have an AsmParser #" + utostr(AsmParserNum) + "!";
148   return LI[AsmParserNum];
149 }
150
151 /// getAsmWriter - Return the AssemblyWriter definition for this target.
152 ///
153 Record *CodeGenTarget::getAsmWriter() const {
154   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
155   if (AsmWriterNum >= LI.size())
156     throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
157   return LI[AsmWriterNum];
158 }
159
160 CodeGenRegBank &CodeGenTarget::getRegBank() const {
161   if (!RegBank)
162     RegBank = new CodeGenRegBank(Records);
163   return *RegBank;
164 }
165
166 void CodeGenTarget::ReadRegisters() const {
167   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
168   if (Regs.empty())
169     throw std::string("No 'Register' subclasses defined!");
170   std::sort(Regs.begin(), Regs.end(), LessRecord());
171
172   Registers.reserve(Regs.size());
173   Registers.assign(Regs.begin(), Regs.end());
174   // Assign the enumeration values.
175   for (unsigned i = 0, e = Registers.size(); i != e; ++i)
176     Registers[i].EnumValue = i + 1;
177 }
178
179 void CodeGenTarget::ReadRegisterClasses() const {
180   std::vector<Record*> RegClasses =
181     Records.getAllDerivedDefinitions("RegisterClass");
182   if (RegClasses.empty())
183     throw std::string("No 'RegisterClass' subclasses defined!");
184
185   RegisterClasses.reserve(RegClasses.size());
186   RegisterClasses.assign(RegClasses.begin(), RegClasses.end());
187 }
188
189 /// getRegisterByName - If there is a register with the specific AsmName,
190 /// return it.
191 const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
192   const std::vector<CodeGenRegister> &Regs = getRegisters();
193   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
194     const CodeGenRegister &Reg = Regs[i];
195     if (Reg.TheDef->getValueAsString("AsmName") == Name)
196       return &Reg;
197   }
198
199   return 0;
200 }
201
202 std::vector<MVT::SimpleValueType> CodeGenTarget::
203 getRegisterVTs(Record *R) const {
204   std::vector<MVT::SimpleValueType> Result;
205   const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
206   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
207     const CodeGenRegisterClass &RC = RegisterClasses[i];
208     for (unsigned ei = 0, ee = RC.Elements.size(); ei != ee; ++ei) {
209       if (R == RC.Elements[ei]) {
210         const std::vector<MVT::SimpleValueType> &InVTs = RC.getValueTypes();
211         Result.insert(Result.end(), InVTs.begin(), InVTs.end());
212       }
213     }
214   }
215
216   // Remove duplicates.
217   array_pod_sort(Result.begin(), Result.end());
218   Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
219   return Result;
220 }
221
222
223 void CodeGenTarget::ReadLegalValueTypes() const {
224   const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
225   for (unsigned i = 0, e = RCs.size(); i != e; ++i)
226     for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)
227       LegalValueTypes.push_back(RCs[i].VTs[ri]);
228
229   // Remove duplicates.
230   std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
231   LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
232                                     LegalValueTypes.end()),
233                         LegalValueTypes.end());
234 }
235
236
237 void CodeGenTarget::ReadInstructions() const {
238   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
239   if (Insts.size() <= 2)
240     throw std::string("No 'Instruction' subclasses defined!");
241
242   // Parse the instructions defined in the .td file.
243   for (unsigned i = 0, e = Insts.size(); i != e; ++i)
244     Instructions[Insts[i]] = new CodeGenInstruction(Insts[i]);
245 }
246
247 static const CodeGenInstruction *
248 GetInstByName(const char *Name,
249               const DenseMap<const Record*, CodeGenInstruction*> &Insts,
250               RecordKeeper &Records) {
251   const Record *Rec = Records.getDef(Name);
252
253   DenseMap<const Record*, CodeGenInstruction*>::const_iterator
254     I = Insts.find(Rec);
255   if (Rec == 0 || I == Insts.end())
256     throw std::string("Could not find '") + Name + "' instruction!";
257   return I->second;
258 }
259
260 namespace {
261 /// SortInstByName - Sorting predicate to sort instructions by name.
262 ///
263 struct SortInstByName {
264   bool operator()(const CodeGenInstruction *Rec1,
265                   const CodeGenInstruction *Rec2) const {
266     return Rec1->TheDef->getName() < Rec2->TheDef->getName();
267   }
268 };
269 }
270
271 /// getInstructionsByEnumValue - Return all of the instructions defined by the
272 /// target, ordered by their enum value.
273 void CodeGenTarget::ComputeInstrsByEnum() const {
274   // The ordering here must match the ordering in TargetOpcodes.h.
275   const char *const FixedInstrs[] = {
276     "PHI",
277     "INLINEASM",
278     "PROLOG_LABEL",
279     "EH_LABEL",
280     "GC_LABEL",
281     "KILL",
282     "EXTRACT_SUBREG",
283     "INSERT_SUBREG",
284     "IMPLICIT_DEF",
285     "SUBREG_TO_REG",
286     "COPY_TO_REGCLASS",
287     "DBG_VALUE",
288     "REG_SEQUENCE",
289     "COPY",
290     0
291   };
292   const DenseMap<const Record*, CodeGenInstruction*> &Insts = getInstructions();
293   for (const char *const *p = FixedInstrs; *p; ++p) {
294     const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
295     assert(Instr && "Missing target independent instruction");
296     assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
297     InstrsByEnum.push_back(Instr);
298   }
299   unsigned EndOfPredefines = InstrsByEnum.size();
300
301   for (DenseMap<const Record*, CodeGenInstruction*>::const_iterator
302        I = Insts.begin(), E = Insts.end(); I != E; ++I) {
303     const CodeGenInstruction *CGI = I->second;
304     if (CGI->Namespace != "TargetOpcode")
305       InstrsByEnum.push_back(CGI);
306   }
307
308   assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
309
310   // All of the instructions are now in random order based on the map iteration.
311   // Sort them by name.
312   std::sort(InstrsByEnum.begin()+EndOfPredefines, InstrsByEnum.end(),
313             SortInstByName());
314 }
315
316
317 /// isLittleEndianEncoding - Return whether this target encodes its instruction
318 /// in little-endian format, i.e. bits laid out in the order [0..n]
319 ///
320 bool CodeGenTarget::isLittleEndianEncoding() const {
321   return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
322 }
323
324 //===----------------------------------------------------------------------===//
325 // ComplexPattern implementation
326 //
327 ComplexPattern::ComplexPattern(Record *R) {
328   Ty          = ::getValueType(R->getValueAsDef("Ty"));
329   NumOperands = R->getValueAsInt("NumOperands");
330   SelectFunc  = R->getValueAsString("SelectFunc");
331   RootNodes   = R->getValueAsListOfDefs("RootNodes");
332
333   // Parse the properties.
334   Properties = 0;
335   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
336   for (unsigned i = 0, e = PropList.size(); i != e; ++i)
337     if (PropList[i]->getName() == "SDNPHasChain") {
338       Properties |= 1 << SDNPHasChain;
339     } else if (PropList[i]->getName() == "SDNPOptInGlue") {
340       Properties |= 1 << SDNPOptInGlue;
341     } else if (PropList[i]->getName() == "SDNPMayStore") {
342       Properties |= 1 << SDNPMayStore;
343     } else if (PropList[i]->getName() == "SDNPMayLoad") {
344       Properties |= 1 << SDNPMayLoad;
345     } else if (PropList[i]->getName() == "SDNPSideEffect") {
346       Properties |= 1 << SDNPSideEffect;
347     } else if (PropList[i]->getName() == "SDNPMemOperand") {
348       Properties |= 1 << SDNPMemOperand;
349     } else if (PropList[i]->getName() == "SDNPVariadic") {
350       Properties |= 1 << SDNPVariadic;
351     } else if (PropList[i]->getName() == "SDNPWantRoot") {
352       Properties |= 1 << SDNPWantRoot;
353     } else if (PropList[i]->getName() == "SDNPWantParent") {
354       Properties |= 1 << SDNPWantParent;
355     } else {
356       errs() << "Unsupported SD Node property '" << PropList[i]->getName()
357              << "' on ComplexPattern '" << R->getName() << "'!\n";
358       exit(1);
359     }
360 }
361
362 //===----------------------------------------------------------------------===//
363 // CodeGenIntrinsic Implementation
364 //===----------------------------------------------------------------------===//
365
366 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC,
367                                                    bool TargetOnly) {
368   std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
369
370   std::vector<CodeGenIntrinsic> Result;
371
372   for (unsigned i = 0, e = I.size(); i != e; ++i) {
373     bool isTarget = I[i]->getValueAsBit("isTarget");
374     if (isTarget == TargetOnly)
375       Result.push_back(CodeGenIntrinsic(I[i]));
376   }
377   return Result;
378 }
379
380 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
381   TheDef = R;
382   std::string DefName = R->getName();
383   ModRef = ReadWriteMem;
384   isOverloaded = false;
385   isCommutative = false;
386   canThrow = false;
387
388   if (DefName.size() <= 4 ||
389       std::string(DefName.begin(), DefName.begin() + 4) != "int_")
390     throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
391
392   EnumName = std::string(DefName.begin()+4, DefName.end());
393
394   if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
395     GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
396
397   TargetPrefix = R->getValueAsString("TargetPrefix");
398   Name = R->getValueAsString("LLVMName");
399
400   if (Name == "") {
401     // If an explicit name isn't specified, derive one from the DefName.
402     Name = "llvm.";
403
404     for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
405       Name += (EnumName[i] == '_') ? '.' : EnumName[i];
406   } else {
407     // Verify it starts with "llvm.".
408     if (Name.size() <= 5 ||
409         std::string(Name.begin(), Name.begin() + 5) != "llvm.")
410       throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
411   }
412
413   // If TargetPrefix is specified, make sure that Name starts with
414   // "llvm.<targetprefix>.".
415   if (!TargetPrefix.empty()) {
416     if (Name.size() < 6+TargetPrefix.size() ||
417         std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
418         != (TargetPrefix + "."))
419       throw "Intrinsic '" + DefName + "' does not start with 'llvm." +
420         TargetPrefix + ".'!";
421   }
422
423   // Parse the list of return types.
424   std::vector<MVT::SimpleValueType> OverloadedVTs;
425   ListInit *TypeList = R->getValueAsListInit("RetTypes");
426   for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
427     Record *TyEl = TypeList->getElementAsRecord(i);
428     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
429     MVT::SimpleValueType VT;
430     if (TyEl->isSubClassOf("LLVMMatchType")) {
431       unsigned MatchTy = TyEl->getValueAsInt("Number");
432       assert(MatchTy < OverloadedVTs.size() &&
433              "Invalid matching number!");
434       VT = OverloadedVTs[MatchTy];
435       // It only makes sense to use the extended and truncated vector element
436       // variants with iAny types; otherwise, if the intrinsic is not
437       // overloaded, all the types can be specified directly.
438       assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
439                !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
440               VT == MVT::iAny || VT == MVT::vAny) &&
441              "Expected iAny or vAny type");
442     } else {
443       VT = getValueType(TyEl->getValueAsDef("VT"));
444     }
445     if (EVT(VT).isOverloaded()) {
446       OverloadedVTs.push_back(VT);
447       isOverloaded = true;
448     }
449
450     // Reject invalid types.
451     if (VT == MVT::isVoid)
452       throw "Intrinsic '" + DefName + " has void in result type list!";
453
454     IS.RetVTs.push_back(VT);
455     IS.RetTypeDefs.push_back(TyEl);
456   }
457
458   // Parse the list of parameter types.
459   TypeList = R->getValueAsListInit("ParamTypes");
460   for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
461     Record *TyEl = TypeList->getElementAsRecord(i);
462     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
463     MVT::SimpleValueType VT;
464     if (TyEl->isSubClassOf("LLVMMatchType")) {
465       unsigned MatchTy = TyEl->getValueAsInt("Number");
466       assert(MatchTy < OverloadedVTs.size() &&
467              "Invalid matching number!");
468       VT = OverloadedVTs[MatchTy];
469       // It only makes sense to use the extended and truncated vector element
470       // variants with iAny types; otherwise, if the intrinsic is not
471       // overloaded, all the types can be specified directly.
472       assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
473                !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
474               VT == MVT::iAny || VT == MVT::vAny) &&
475              "Expected iAny or vAny type");
476     } else
477       VT = getValueType(TyEl->getValueAsDef("VT"));
478
479     if (EVT(VT).isOverloaded()) {
480       OverloadedVTs.push_back(VT);
481       isOverloaded = true;
482     }
483
484     // Reject invalid types.
485     if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
486       throw "Intrinsic '" + DefName + " has void in result type list!";
487
488     IS.ParamVTs.push_back(VT);
489     IS.ParamTypeDefs.push_back(TyEl);
490   }
491
492   // Parse the intrinsic properties.
493   ListInit *PropList = R->getValueAsListInit("Properties");
494   for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
495     Record *Property = PropList->getElementAsRecord(i);
496     assert(Property->isSubClassOf("IntrinsicProperty") &&
497            "Expected a property!");
498
499     if (Property->getName() == "IntrNoMem")
500       ModRef = NoMem;
501     else if (Property->getName() == "IntrReadArgMem")
502       ModRef = ReadArgMem;
503     else if (Property->getName() == "IntrReadMem")
504       ModRef = ReadMem;
505     else if (Property->getName() == "IntrReadWriteArgMem")
506       ModRef = ReadWriteArgMem;
507     else if (Property->getName() == "Commutative")
508       isCommutative = true;
509     else if (Property->getName() == "Throws")
510       canThrow = true;
511     else if (Property->isSubClassOf("NoCapture")) {
512       unsigned ArgNo = Property->getValueAsInt("ArgNo");
513       ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
514     } else
515       assert(0 && "Unknown property!");
516   }
517
518   // Sort the argument attributes for later benefit.
519   std::sort(ArgumentAttributes.begin(), ArgumentAttributes.end());
520 }