1 //===- CodeGenTarget.cpp - CodeGen Target Class Wrapper -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
15 //===----------------------------------------------------------------------===//
17 #include "CodeGenTarget.h"
18 #include "CodeGenIntrinsics.h"
19 #include "CodeGenSchedule.h"
20 #include "llvm/TableGen/Record.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/CommandLine.h"
27 static cl::opt<unsigned>
28 AsmParserNum("asmparsernum", cl::init(0),
29 cl::desc("Make -gen-asm-parser emit assembly parser #N"));
31 static cl::opt<unsigned>
32 AsmWriterNum("asmwriternum", cl::init(0),
33 cl::desc("Make -gen-asm-writer emit assembly writer #N"));
35 /// getValueType - Return the MVT::SimpleValueType that the specified TableGen
36 /// record corresponds to.
37 MVT::SimpleValueType llvm::getValueType(Record *Rec) {
38 return (MVT::SimpleValueType)Rec->getValueAsInt("Value");
41 std::string llvm::getName(MVT::SimpleValueType T) {
43 case MVT::Other: return "UNKNOWN";
44 case MVT::iPTR: return "TLI.getPointerTy()";
45 case MVT::iPTRAny: return "TLI.getPointerTy()";
46 default: return getEnumName(T);
50 std::string llvm::getEnumName(MVT::SimpleValueType T) {
52 case MVT::Other: return "MVT::Other";
53 case MVT::i1: return "MVT::i1";
54 case MVT::i8: return "MVT::i8";
55 case MVT::i16: return "MVT::i16";
56 case MVT::i32: return "MVT::i32";
57 case MVT::i64: return "MVT::i64";
58 case MVT::i128: return "MVT::i128";
59 case MVT::iAny: return "MVT::iAny";
60 case MVT::fAny: return "MVT::fAny";
61 case MVT::vAny: return "MVT::vAny";
62 case MVT::f16: return "MVT::f16";
63 case MVT::f32: return "MVT::f32";
64 case MVT::f64: return "MVT::f64";
65 case MVT::f80: return "MVT::f80";
66 case MVT::f128: return "MVT::f128";
67 case MVT::ppcf128: return "MVT::ppcf128";
68 case MVT::x86mmx: return "MVT::x86mmx";
69 case MVT::Glue: return "MVT::Glue";
70 case MVT::isVoid: return "MVT::isVoid";
71 case MVT::v2i8: return "MVT::v2i8";
72 case MVT::v4i8: return "MVT::v4i8";
73 case MVT::v8i8: return "MVT::v8i8";
74 case MVT::v16i8: return "MVT::v16i8";
75 case MVT::v32i8: return "MVT::v32i8";
76 case MVT::v2i16: return "MVT::v2i16";
77 case MVT::v4i16: return "MVT::v4i16";
78 case MVT::v8i16: return "MVT::v8i16";
79 case MVT::v16i16: return "MVT::v16i16";
80 case MVT::v2i32: return "MVT::v2i32";
81 case MVT::v4i32: return "MVT::v4i32";
82 case MVT::v8i32: return "MVT::v8i32";
83 case MVT::v1i64: return "MVT::v1i64";
84 case MVT::v2i64: return "MVT::v2i64";
85 case MVT::v4i64: return "MVT::v4i64";
86 case MVT::v8i64: return "MVT::v8i64";
87 case MVT::v2f16: return "MVT::v2f16";
88 case MVT::v2f32: return "MVT::v2f32";
89 case MVT::v4f32: return "MVT::v4f32";
90 case MVT::v8f32: return "MVT::v8f32";
91 case MVT::v2f64: return "MVT::v2f64";
92 case MVT::v4f64: return "MVT::v4f64";
93 case MVT::Metadata: return "MVT::Metadata";
94 case MVT::iPTR: return "MVT::iPTR";
95 case MVT::iPTRAny: return "MVT::iPTRAny";
96 case MVT::Untyped: return "MVT::Untyped";
97 default: llvm_unreachable("ILLEGAL VALUE TYPE!");
101 /// getQualifiedName - Return the name of the specified record, with a
102 /// namespace qualifier if the record contains one.
104 std::string llvm::getQualifiedName(const Record *R) {
105 std::string Namespace;
106 if (R->getValue("Namespace"))
107 Namespace = R->getValueAsString("Namespace");
108 if (Namespace.empty()) return R->getName();
109 return Namespace + "::" + R->getName();
113 /// getTarget - Return the current instance of the Target class.
115 CodeGenTarget::CodeGenTarget(RecordKeeper &records)
116 : Records(records), RegBank(0), SchedModels(0) {
117 std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
118 if (Targets.size() == 0)
119 throw std::string("ERROR: No 'Target' subclasses defined!");
120 if (Targets.size() != 1)
121 throw std::string("ERROR: Multiple subclasses of Target defined!");
122 TargetRec = Targets[0];
125 CodeGenTarget::~CodeGenTarget() {
130 const std::string &CodeGenTarget::getName() const {
131 return TargetRec->getName();
134 std::string CodeGenTarget::getInstNamespace() const {
135 for (inst_iterator i = inst_begin(), e = inst_end(); i != e; ++i) {
136 // Make sure not to pick up "TargetOpcode" by accidentally getting
137 // the namespace off the PHI instruction or something.
138 if ((*i)->Namespace != "TargetOpcode")
139 return (*i)->Namespace;
145 Record *CodeGenTarget::getInstructionSet() const {
146 return TargetRec->getValueAsDef("InstructionSet");
150 /// getAsmParser - Return the AssemblyParser definition for this target.
152 Record *CodeGenTarget::getAsmParser() const {
153 std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
154 if (AsmParserNum >= LI.size())
155 throw "Target does not have an AsmParser #" + utostr(AsmParserNum) + "!";
156 return LI[AsmParserNum];
159 /// getAsmParserVariant - Return the AssmblyParserVariant definition for
162 Record *CodeGenTarget::getAsmParserVariant(unsigned i) const {
163 std::vector<Record*> LI =
164 TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
166 throw "Target does not have an AsmParserVariant #" + utostr(i) + "!";
170 /// getAsmParserVariantCount - Return the AssmblyParserVariant definition
171 /// available for this target.
173 unsigned CodeGenTarget::getAsmParserVariantCount() const {
174 std::vector<Record*> LI =
175 TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
179 /// getAsmWriter - Return the AssemblyWriter definition for this target.
181 Record *CodeGenTarget::getAsmWriter() const {
182 std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
183 if (AsmWriterNum >= LI.size())
184 throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
185 return LI[AsmWriterNum];
188 CodeGenRegBank &CodeGenTarget::getRegBank() const {
190 RegBank = new CodeGenRegBank(Records);
194 void CodeGenTarget::ReadRegAltNameIndices() const {
195 RegAltNameIndices = Records.getAllDerivedDefinitions("RegAltNameIndex");
196 std::sort(RegAltNameIndices.begin(), RegAltNameIndices.end(), LessRecord());
199 /// getRegisterByName - If there is a register with the specific AsmName,
201 const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
202 const std::vector<CodeGenRegister*> &Regs = getRegBank().getRegisters();
203 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
204 if (Regs[i]->TheDef->getValueAsString("AsmName") == Name)
210 std::vector<MVT::SimpleValueType> CodeGenTarget::
211 getRegisterVTs(Record *R) const {
212 const CodeGenRegister *Reg = getRegBank().getReg(R);
213 std::vector<MVT::SimpleValueType> Result;
214 ArrayRef<CodeGenRegisterClass*> RCs = getRegBank().getRegClasses();
215 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
216 const CodeGenRegisterClass &RC = *RCs[i];
217 if (RC.contains(Reg)) {
218 const std::vector<MVT::SimpleValueType> &InVTs = RC.getValueTypes();
219 Result.insert(Result.end(), InVTs.begin(), InVTs.end());
223 // Remove duplicates.
224 array_pod_sort(Result.begin(), Result.end());
225 Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
230 void CodeGenTarget::ReadLegalValueTypes() const {
231 ArrayRef<CodeGenRegisterClass*> RCs = getRegBank().getRegClasses();
232 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
233 for (unsigned ri = 0, re = RCs[i]->VTs.size(); ri != re; ++ri)
234 LegalValueTypes.push_back(RCs[i]->VTs[ri]);
236 // Remove duplicates.
237 std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
238 LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
239 LegalValueTypes.end()),
240 LegalValueTypes.end());
243 CodeGenSchedModels &CodeGenTarget::getSchedModels() const {
245 SchedModels = new CodeGenSchedModels(Records, *this);
249 void CodeGenTarget::ReadInstructions() const {
250 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
251 if (Insts.size() <= 2)
252 throw std::string("No 'Instruction' subclasses defined!");
254 // Parse the instructions defined in the .td file.
255 for (unsigned i = 0, e = Insts.size(); i != e; ++i)
256 Instructions[Insts[i]] = new CodeGenInstruction(Insts[i]);
259 static const CodeGenInstruction *
260 GetInstByName(const char *Name,
261 const DenseMap<const Record*, CodeGenInstruction*> &Insts,
262 RecordKeeper &Records) {
263 const Record *Rec = Records.getDef(Name);
265 DenseMap<const Record*, CodeGenInstruction*>::const_iterator
267 if (Rec == 0 || I == Insts.end())
268 throw std::string("Could not find '") + Name + "' instruction!";
273 /// SortInstByName - Sorting predicate to sort instructions by name.
275 struct SortInstByName {
276 bool operator()(const CodeGenInstruction *Rec1,
277 const CodeGenInstruction *Rec2) const {
278 return Rec1->TheDef->getName() < Rec2->TheDef->getName();
283 /// getInstructionsByEnumValue - Return all of the instructions defined by the
284 /// target, ordered by their enum value.
285 void CodeGenTarget::ComputeInstrsByEnum() const {
286 // The ordering here must match the ordering in TargetOpcodes.h.
287 const char *const FixedInstrs[] = {
305 const DenseMap<const Record*, CodeGenInstruction*> &Insts = getInstructions();
306 for (const char *const *p = FixedInstrs; *p; ++p) {
307 const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
308 assert(Instr && "Missing target independent instruction");
309 assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
310 InstrsByEnum.push_back(Instr);
312 unsigned EndOfPredefines = InstrsByEnum.size();
314 for (DenseMap<const Record*, CodeGenInstruction*>::const_iterator
315 I = Insts.begin(), E = Insts.end(); I != E; ++I) {
316 const CodeGenInstruction *CGI = I->second;
317 if (CGI->Namespace != "TargetOpcode")
318 InstrsByEnum.push_back(CGI);
321 assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
323 // All of the instructions are now in random order based on the map iteration.
324 // Sort them by name.
325 std::sort(InstrsByEnum.begin()+EndOfPredefines, InstrsByEnum.end(),
330 /// isLittleEndianEncoding - Return whether this target encodes its instruction
331 /// in little-endian format, i.e. bits laid out in the order [0..n]
333 bool CodeGenTarget::isLittleEndianEncoding() const {
334 return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
337 //===----------------------------------------------------------------------===//
338 // ComplexPattern implementation
340 ComplexPattern::ComplexPattern(Record *R) {
341 Ty = ::getValueType(R->getValueAsDef("Ty"));
342 NumOperands = R->getValueAsInt("NumOperands");
343 SelectFunc = R->getValueAsString("SelectFunc");
344 RootNodes = R->getValueAsListOfDefs("RootNodes");
346 // Parse the properties.
348 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
349 for (unsigned i = 0, e = PropList.size(); i != e; ++i)
350 if (PropList[i]->getName() == "SDNPHasChain") {
351 Properties |= 1 << SDNPHasChain;
352 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
353 Properties |= 1 << SDNPOptInGlue;
354 } else if (PropList[i]->getName() == "SDNPMayStore") {
355 Properties |= 1 << SDNPMayStore;
356 } else if (PropList[i]->getName() == "SDNPMayLoad") {
357 Properties |= 1 << SDNPMayLoad;
358 } else if (PropList[i]->getName() == "SDNPSideEffect") {
359 Properties |= 1 << SDNPSideEffect;
360 } else if (PropList[i]->getName() == "SDNPMemOperand") {
361 Properties |= 1 << SDNPMemOperand;
362 } else if (PropList[i]->getName() == "SDNPVariadic") {
363 Properties |= 1 << SDNPVariadic;
364 } else if (PropList[i]->getName() == "SDNPWantRoot") {
365 Properties |= 1 << SDNPWantRoot;
366 } else if (PropList[i]->getName() == "SDNPWantParent") {
367 Properties |= 1 << SDNPWantParent;
369 errs() << "Unsupported SD Node property '" << PropList[i]->getName()
370 << "' on ComplexPattern '" << R->getName() << "'!\n";
375 //===----------------------------------------------------------------------===//
376 // CodeGenIntrinsic Implementation
377 //===----------------------------------------------------------------------===//
379 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC,
381 std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
383 std::vector<CodeGenIntrinsic> Result;
385 for (unsigned i = 0, e = I.size(); i != e; ++i) {
386 bool isTarget = I[i]->getValueAsBit("isTarget");
387 if (isTarget == TargetOnly)
388 Result.push_back(CodeGenIntrinsic(I[i]));
393 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
395 std::string DefName = R->getName();
396 ModRef = ReadWriteMem;
397 isOverloaded = false;
398 isCommutative = false;
402 if (DefName.size() <= 4 ||
403 std::string(DefName.begin(), DefName.begin() + 4) != "int_")
404 throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
406 EnumName = std::string(DefName.begin()+4, DefName.end());
408 if (R->getValue("GCCBuiltinName")) // Ignore a missing GCCBuiltinName field.
409 GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
411 TargetPrefix = R->getValueAsString("TargetPrefix");
412 Name = R->getValueAsString("LLVMName");
415 // If an explicit name isn't specified, derive one from the DefName.
418 for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
419 Name += (EnumName[i] == '_') ? '.' : EnumName[i];
421 // Verify it starts with "llvm.".
422 if (Name.size() <= 5 ||
423 std::string(Name.begin(), Name.begin() + 5) != "llvm.")
424 throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
427 // If TargetPrefix is specified, make sure that Name starts with
428 // "llvm.<targetprefix>.".
429 if (!TargetPrefix.empty()) {
430 if (Name.size() < 6+TargetPrefix.size() ||
431 std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
432 != (TargetPrefix + "."))
433 throw "Intrinsic '" + DefName + "' does not start with 'llvm." +
434 TargetPrefix + ".'!";
437 // Parse the list of return types.
438 std::vector<MVT::SimpleValueType> OverloadedVTs;
439 ListInit *TypeList = R->getValueAsListInit("RetTypes");
440 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
441 Record *TyEl = TypeList->getElementAsRecord(i);
442 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
443 MVT::SimpleValueType VT;
444 if (TyEl->isSubClassOf("LLVMMatchType")) {
445 unsigned MatchTy = TyEl->getValueAsInt("Number");
446 assert(MatchTy < OverloadedVTs.size() &&
447 "Invalid matching number!");
448 VT = OverloadedVTs[MatchTy];
449 // It only makes sense to use the extended and truncated vector element
450 // variants with iAny types; otherwise, if the intrinsic is not
451 // overloaded, all the types can be specified directly.
452 assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
453 !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
454 VT == MVT::iAny || VT == MVT::vAny) &&
455 "Expected iAny or vAny type");
457 VT = getValueType(TyEl->getValueAsDef("VT"));
459 if (EVT(VT).isOverloaded()) {
460 OverloadedVTs.push_back(VT);
464 // Reject invalid types.
465 if (VT == MVT::isVoid)
466 throw "Intrinsic '" + DefName + " has void in result type list!";
468 IS.RetVTs.push_back(VT);
469 IS.RetTypeDefs.push_back(TyEl);
472 // Parse the list of parameter types.
473 TypeList = R->getValueAsListInit("ParamTypes");
474 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
475 Record *TyEl = TypeList->getElementAsRecord(i);
476 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
477 MVT::SimpleValueType VT;
478 if (TyEl->isSubClassOf("LLVMMatchType")) {
479 unsigned MatchTy = TyEl->getValueAsInt("Number");
480 assert(MatchTy < OverloadedVTs.size() &&
481 "Invalid matching number!");
482 VT = OverloadedVTs[MatchTy];
483 // It only makes sense to use the extended and truncated vector element
484 // variants with iAny types; otherwise, if the intrinsic is not
485 // overloaded, all the types can be specified directly.
486 assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
487 !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
488 VT == MVT::iAny || VT == MVT::vAny) &&
489 "Expected iAny or vAny type");
491 VT = getValueType(TyEl->getValueAsDef("VT"));
493 if (EVT(VT).isOverloaded()) {
494 OverloadedVTs.push_back(VT);
498 // Reject invalid types.
499 if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
500 throw "Intrinsic '" + DefName + " has void in result type list!";
502 IS.ParamVTs.push_back(VT);
503 IS.ParamTypeDefs.push_back(TyEl);
506 // Parse the intrinsic properties.
507 ListInit *PropList = R->getValueAsListInit("Properties");
508 for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
509 Record *Property = PropList->getElementAsRecord(i);
510 assert(Property->isSubClassOf("IntrinsicProperty") &&
511 "Expected a property!");
513 if (Property->getName() == "IntrNoMem")
515 else if (Property->getName() == "IntrReadArgMem")
517 else if (Property->getName() == "IntrReadMem")
519 else if (Property->getName() == "IntrReadWriteArgMem")
520 ModRef = ReadWriteArgMem;
521 else if (Property->getName() == "Commutative")
522 isCommutative = true;
523 else if (Property->getName() == "Throws")
525 else if (Property->getName() == "IntrNoReturn")
527 else if (Property->isSubClassOf("NoCapture")) {
528 unsigned ArgNo = Property->getValueAsInt("ArgNo");
529 ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
531 llvm_unreachable("Unknown property!");
534 // Sort the argument attributes for later benefit.
535 std::sort(ArgumentAttributes.begin(), ArgumentAttributes.end());