Add a new MVT::untyped. This will be used in future work for modelling ISA features...
[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   case MVT::untyped: return "MVT::untyped";
94   default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
95   }
96 }
97
98 /// getQualifiedName - Return the name of the specified record, with a
99 /// namespace qualifier if the record contains one.
100 ///
101 std::string llvm::getQualifiedName(const Record *R) {
102   std::string Namespace;
103   if (R->getValue("Namespace"))
104      Namespace = R->getValueAsString("Namespace");
105   if (Namespace.empty()) return R->getName();
106   return Namespace + "::" + R->getName();
107 }
108
109
110 /// getTarget - Return the current instance of the Target class.
111 ///
112 CodeGenTarget::CodeGenTarget(RecordKeeper &records)
113   : Records(records), RegBank(0) {
114   std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
115   if (Targets.size() == 0)
116     throw std::string("ERROR: No 'Target' subclasses defined!");
117   if (Targets.size() != 1)
118     throw std::string("ERROR: Multiple subclasses of Target defined!");
119   TargetRec = Targets[0];
120 }
121
122
123 const std::string &CodeGenTarget::getName() const {
124   return TargetRec->getName();
125 }
126
127 std::string CodeGenTarget::getInstNamespace() const {
128   for (inst_iterator i = inst_begin(), e = inst_end(); i != e; ++i) {
129     // Make sure not to pick up "TargetOpcode" by accidentally getting
130     // the namespace off the PHI instruction or something.
131     if ((*i)->Namespace != "TargetOpcode")
132       return (*i)->Namespace;
133   }
134
135   return "";
136 }
137
138 Record *CodeGenTarget::getInstructionSet() const {
139   return TargetRec->getValueAsDef("InstructionSet");
140 }
141
142
143 /// getAsmParser - Return the AssemblyParser definition for this target.
144 ///
145 Record *CodeGenTarget::getAsmParser() const {
146   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
147   if (AsmParserNum >= LI.size())
148     throw "Target does not have an AsmParser #" + utostr(AsmParserNum) + "!";
149   return LI[AsmParserNum];
150 }
151
152 /// getAsmWriter - Return the AssemblyWriter definition for this target.
153 ///
154 Record *CodeGenTarget::getAsmWriter() const {
155   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
156   if (AsmWriterNum >= LI.size())
157     throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
158   return LI[AsmWriterNum];
159 }
160
161 CodeGenRegBank &CodeGenTarget::getRegBank() const {
162   if (!RegBank)
163     RegBank = new CodeGenRegBank(Records);
164   return *RegBank;
165 }
166
167 /// getRegisterByName - If there is a register with the specific AsmName,
168 /// return it.
169 const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
170   const std::vector<CodeGenRegister> &Regs = getRegBank().getRegisters();
171   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
172     const CodeGenRegister &Reg = Regs[i];
173     if (Reg.TheDef->getValueAsString("AsmName") == Name)
174       return &Reg;
175   }
176
177   return 0;
178 }
179
180 std::vector<MVT::SimpleValueType> CodeGenTarget::
181 getRegisterVTs(Record *R) const {
182   const CodeGenRegister *Reg = getRegBank().getReg(R);
183   std::vector<MVT::SimpleValueType> Result;
184   const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
185   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
186     const CodeGenRegisterClass &RC = RCs[i];
187     if (RC.contains(Reg)) {
188       const std::vector<MVT::SimpleValueType> &InVTs = RC.getValueTypes();
189       Result.insert(Result.end(), InVTs.begin(), InVTs.end());
190     }
191   }
192
193   // Remove duplicates.
194   array_pod_sort(Result.begin(), Result.end());
195   Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
196   return Result;
197 }
198
199
200 void CodeGenTarget::ReadLegalValueTypes() const {
201   const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
202   for (unsigned i = 0, e = RCs.size(); i != e; ++i)
203     for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)
204       LegalValueTypes.push_back(RCs[i].VTs[ri]);
205
206   // Remove duplicates.
207   std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
208   LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
209                                     LegalValueTypes.end()),
210                         LegalValueTypes.end());
211 }
212
213
214 void CodeGenTarget::ReadInstructions() const {
215   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
216   if (Insts.size() <= 2)
217     throw std::string("No 'Instruction' subclasses defined!");
218
219   // Parse the instructions defined in the .td file.
220   for (unsigned i = 0, e = Insts.size(); i != e; ++i)
221     Instructions[Insts[i]] = new CodeGenInstruction(Insts[i]);
222 }
223
224 static const CodeGenInstruction *
225 GetInstByName(const char *Name,
226               const DenseMap<const Record*, CodeGenInstruction*> &Insts,
227               RecordKeeper &Records) {
228   const Record *Rec = Records.getDef(Name);
229
230   DenseMap<const Record*, CodeGenInstruction*>::const_iterator
231     I = Insts.find(Rec);
232   if (Rec == 0 || I == Insts.end())
233     throw std::string("Could not find '") + Name + "' instruction!";
234   return I->second;
235 }
236
237 namespace {
238 /// SortInstByName - Sorting predicate to sort instructions by name.
239 ///
240 struct SortInstByName {
241   bool operator()(const CodeGenInstruction *Rec1,
242                   const CodeGenInstruction *Rec2) const {
243     return Rec1->TheDef->getName() < Rec2->TheDef->getName();
244   }
245 };
246 }
247
248 /// getInstructionsByEnumValue - Return all of the instructions defined by the
249 /// target, ordered by their enum value.
250 void CodeGenTarget::ComputeInstrsByEnum() const {
251   // The ordering here must match the ordering in TargetOpcodes.h.
252   const char *const FixedInstrs[] = {
253     "PHI",
254     "INLINEASM",
255     "PROLOG_LABEL",
256     "EH_LABEL",
257     "GC_LABEL",
258     "KILL",
259     "EXTRACT_SUBREG",
260     "INSERT_SUBREG",
261     "IMPLICIT_DEF",
262     "SUBREG_TO_REG",
263     "COPY_TO_REGCLASS",
264     "DBG_VALUE",
265     "REG_SEQUENCE",
266     "COPY",
267     0
268   };
269   const DenseMap<const Record*, CodeGenInstruction*> &Insts = getInstructions();
270   for (const char *const *p = FixedInstrs; *p; ++p) {
271     const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
272     assert(Instr && "Missing target independent instruction");
273     assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
274     InstrsByEnum.push_back(Instr);
275   }
276   unsigned EndOfPredefines = InstrsByEnum.size();
277
278   for (DenseMap<const Record*, CodeGenInstruction*>::const_iterator
279        I = Insts.begin(), E = Insts.end(); I != E; ++I) {
280     const CodeGenInstruction *CGI = I->second;
281     if (CGI->Namespace != "TargetOpcode")
282       InstrsByEnum.push_back(CGI);
283   }
284
285   assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
286
287   // All of the instructions are now in random order based on the map iteration.
288   // Sort them by name.
289   std::sort(InstrsByEnum.begin()+EndOfPredefines, InstrsByEnum.end(),
290             SortInstByName());
291 }
292
293
294 /// isLittleEndianEncoding - Return whether this target encodes its instruction
295 /// in little-endian format, i.e. bits laid out in the order [0..n]
296 ///
297 bool CodeGenTarget::isLittleEndianEncoding() const {
298   return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
299 }
300
301 //===----------------------------------------------------------------------===//
302 // ComplexPattern implementation
303 //
304 ComplexPattern::ComplexPattern(Record *R) {
305   Ty          = ::getValueType(R->getValueAsDef("Ty"));
306   NumOperands = R->getValueAsInt("NumOperands");
307   SelectFunc  = R->getValueAsString("SelectFunc");
308   RootNodes   = R->getValueAsListOfDefs("RootNodes");
309
310   // Parse the properties.
311   Properties = 0;
312   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
313   for (unsigned i = 0, e = PropList.size(); i != e; ++i)
314     if (PropList[i]->getName() == "SDNPHasChain") {
315       Properties |= 1 << SDNPHasChain;
316     } else if (PropList[i]->getName() == "SDNPOptInGlue") {
317       Properties |= 1 << SDNPOptInGlue;
318     } else if (PropList[i]->getName() == "SDNPMayStore") {
319       Properties |= 1 << SDNPMayStore;
320     } else if (PropList[i]->getName() == "SDNPMayLoad") {
321       Properties |= 1 << SDNPMayLoad;
322     } else if (PropList[i]->getName() == "SDNPSideEffect") {
323       Properties |= 1 << SDNPSideEffect;
324     } else if (PropList[i]->getName() == "SDNPMemOperand") {
325       Properties |= 1 << SDNPMemOperand;
326     } else if (PropList[i]->getName() == "SDNPVariadic") {
327       Properties |= 1 << SDNPVariadic;
328     } else if (PropList[i]->getName() == "SDNPWantRoot") {
329       Properties |= 1 << SDNPWantRoot;
330     } else if (PropList[i]->getName() == "SDNPWantParent") {
331       Properties |= 1 << SDNPWantParent;
332     } else {
333       errs() << "Unsupported SD Node property '" << PropList[i]->getName()
334              << "' on ComplexPattern '" << R->getName() << "'!\n";
335       exit(1);
336     }
337 }
338
339 //===----------------------------------------------------------------------===//
340 // CodeGenIntrinsic Implementation
341 //===----------------------------------------------------------------------===//
342
343 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC,
344                                                    bool TargetOnly) {
345   std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
346
347   std::vector<CodeGenIntrinsic> Result;
348
349   for (unsigned i = 0, e = I.size(); i != e; ++i) {
350     bool isTarget = I[i]->getValueAsBit("isTarget");
351     if (isTarget == TargetOnly)
352       Result.push_back(CodeGenIntrinsic(I[i]));
353   }
354   return Result;
355 }
356
357 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
358   TheDef = R;
359   std::string DefName = R->getName();
360   ModRef = ReadWriteMem;
361   isOverloaded = false;
362   isCommutative = false;
363   canThrow = false;
364
365   if (DefName.size() <= 4 ||
366       std::string(DefName.begin(), DefName.begin() + 4) != "int_")
367     throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
368
369   EnumName = std::string(DefName.begin()+4, DefName.end());
370
371   if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
372     GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
373
374   TargetPrefix = R->getValueAsString("TargetPrefix");
375   Name = R->getValueAsString("LLVMName");
376
377   if (Name == "") {
378     // If an explicit name isn't specified, derive one from the DefName.
379     Name = "llvm.";
380
381     for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
382       Name += (EnumName[i] == '_') ? '.' : EnumName[i];
383   } else {
384     // Verify it starts with "llvm.".
385     if (Name.size() <= 5 ||
386         std::string(Name.begin(), Name.begin() + 5) != "llvm.")
387       throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
388   }
389
390   // If TargetPrefix is specified, make sure that Name starts with
391   // "llvm.<targetprefix>.".
392   if (!TargetPrefix.empty()) {
393     if (Name.size() < 6+TargetPrefix.size() ||
394         std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
395         != (TargetPrefix + "."))
396       throw "Intrinsic '" + DefName + "' does not start with 'llvm." +
397         TargetPrefix + ".'!";
398   }
399
400   // Parse the list of return types.
401   std::vector<MVT::SimpleValueType> OverloadedVTs;
402   ListInit *TypeList = R->getValueAsListInit("RetTypes");
403   for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
404     Record *TyEl = TypeList->getElementAsRecord(i);
405     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
406     MVT::SimpleValueType VT;
407     if (TyEl->isSubClassOf("LLVMMatchType")) {
408       unsigned MatchTy = TyEl->getValueAsInt("Number");
409       assert(MatchTy < OverloadedVTs.size() &&
410              "Invalid matching number!");
411       VT = OverloadedVTs[MatchTy];
412       // It only makes sense to use the extended and truncated vector element
413       // variants with iAny types; otherwise, if the intrinsic is not
414       // overloaded, all the types can be specified directly.
415       assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
416                !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
417               VT == MVT::iAny || VT == MVT::vAny) &&
418              "Expected iAny or vAny type");
419     } else {
420       VT = getValueType(TyEl->getValueAsDef("VT"));
421     }
422     if (EVT(VT).isOverloaded()) {
423       OverloadedVTs.push_back(VT);
424       isOverloaded = true;
425     }
426
427     // Reject invalid types.
428     if (VT == MVT::isVoid)
429       throw "Intrinsic '" + DefName + " has void in result type list!";
430
431     IS.RetVTs.push_back(VT);
432     IS.RetTypeDefs.push_back(TyEl);
433   }
434
435   // Parse the list of parameter types.
436   TypeList = R->getValueAsListInit("ParamTypes");
437   for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
438     Record *TyEl = TypeList->getElementAsRecord(i);
439     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
440     MVT::SimpleValueType VT;
441     if (TyEl->isSubClassOf("LLVMMatchType")) {
442       unsigned MatchTy = TyEl->getValueAsInt("Number");
443       assert(MatchTy < OverloadedVTs.size() &&
444              "Invalid matching number!");
445       VT = OverloadedVTs[MatchTy];
446       // It only makes sense to use the extended and truncated vector element
447       // variants with iAny types; otherwise, if the intrinsic is not
448       // overloaded, all the types can be specified directly.
449       assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
450                !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
451               VT == MVT::iAny || VT == MVT::vAny) &&
452              "Expected iAny or vAny type");
453     } else
454       VT = getValueType(TyEl->getValueAsDef("VT"));
455
456     if (EVT(VT).isOverloaded()) {
457       OverloadedVTs.push_back(VT);
458       isOverloaded = true;
459     }
460
461     // Reject invalid types.
462     if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
463       throw "Intrinsic '" + DefName + " has void in result type list!";
464
465     IS.ParamVTs.push_back(VT);
466     IS.ParamTypeDefs.push_back(TyEl);
467   }
468
469   // Parse the intrinsic properties.
470   ListInit *PropList = R->getValueAsListInit("Properties");
471   for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
472     Record *Property = PropList->getElementAsRecord(i);
473     assert(Property->isSubClassOf("IntrinsicProperty") &&
474            "Expected a property!");
475
476     if (Property->getName() == "IntrNoMem")
477       ModRef = NoMem;
478     else if (Property->getName() == "IntrReadArgMem")
479       ModRef = ReadArgMem;
480     else if (Property->getName() == "IntrReadMem")
481       ModRef = ReadMem;
482     else if (Property->getName() == "IntrReadWriteArgMem")
483       ModRef = ReadWriteArgMem;
484     else if (Property->getName() == "Commutative")
485       isCommutative = true;
486     else if (Property->getName() == "Throws")
487       canThrow = true;
488     else if (Property->isSubClassOf("NoCapture")) {
489       unsigned ArgNo = Property->getValueAsInt("ArgNo");
490       ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
491     } else
492       assert(0 && "Unknown property!");
493   }
494
495   // Sort the argument attributes for later benefit.
496   std::sort(ArgumentAttributes.begin(), ArgumentAttributes.end());
497 }