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::v2i1: return "MVT::v2i1";
72 case MVT::v4i1: return "MVT::v4i1";
73 case MVT::v8i1: return "MVT::v8i1";
74 case MVT::v16i1: return "MVT::v16i1";
75 case MVT::v2i8: return "MVT::v2i8";
76 case MVT::v4i8: return "MVT::v4i8";
77 case MVT::v8i8: return "MVT::v8i8";
78 case MVT::v16i8: return "MVT::v16i8";
79 case MVT::v32i8: return "MVT::v32i8";
80 case MVT::v1i16: return "MVT::v1i16";
81 case MVT::v2i16: return "MVT::v2i16";
82 case MVT::v4i16: return "MVT::v4i16";
83 case MVT::v8i16: return "MVT::v8i16";
84 case MVT::v16i16: return "MVT::v16i16";
85 case MVT::v1i32: return "MVT::v1i32";
86 case MVT::v2i32: return "MVT::v2i32";
87 case MVT::v4i32: return "MVT::v4i32";
88 case MVT::v8i32: return "MVT::v8i32";
89 case MVT::v16i32: return "MVT::v16i32";
90 case MVT::v1i64: return "MVT::v1i64";
91 case MVT::v2i64: return "MVT::v2i64";
92 case MVT::v4i64: return "MVT::v4i64";
93 case MVT::v8i64: return "MVT::v8i64";
94 case MVT::v16i64: return "MVT::v16i64";
95 case MVT::v2f16: return "MVT::v2f16";
96 case MVT::v2f32: return "MVT::v2f32";
97 case MVT::v4f32: return "MVT::v4f32";
98 case MVT::v8f32: return "MVT::v8f32";
99 case MVT::v2f64: return "MVT::v2f64";
100 case MVT::v4f64: return "MVT::v4f64";
101 case MVT::Metadata: return "MVT::Metadata";
102 case MVT::iPTR: return "MVT::iPTR";
103 case MVT::iPTRAny: return "MVT::iPTRAny";
104 case MVT::Untyped: return "MVT::Untyped";
105 default: llvm_unreachable("ILLEGAL VALUE TYPE!");
109 /// getQualifiedName - Return the name of the specified record, with a
110 /// namespace qualifier if the record contains one.
112 std::string llvm::getQualifiedName(const Record *R) {
113 std::string Namespace;
114 if (R->getValue("Namespace"))
115 Namespace = R->getValueAsString("Namespace");
116 if (Namespace.empty()) return R->getName();
117 return Namespace + "::" + R->getName();
121 /// getTarget - Return the current instance of the Target class.
123 CodeGenTarget::CodeGenTarget(RecordKeeper &records)
124 : Records(records), RegBank(0), SchedModels(0) {
125 std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
126 if (Targets.size() == 0)
127 throw std::string("ERROR: No 'Target' subclasses defined!");
128 if (Targets.size() != 1)
129 throw std::string("ERROR: Multiple subclasses of Target defined!");
130 TargetRec = Targets[0];
133 CodeGenTarget::~CodeGenTarget() {
138 const std::string &CodeGenTarget::getName() const {
139 return TargetRec->getName();
142 std::string CodeGenTarget::getInstNamespace() const {
143 for (inst_iterator i = inst_begin(), e = inst_end(); i != e; ++i) {
144 // Make sure not to pick up "TargetOpcode" by accidentally getting
145 // the namespace off the PHI instruction or something.
146 if ((*i)->Namespace != "TargetOpcode")
147 return (*i)->Namespace;
153 Record *CodeGenTarget::getInstructionSet() const {
154 return TargetRec->getValueAsDef("InstructionSet");
158 /// getAsmParser - Return the AssemblyParser definition for this target.
160 Record *CodeGenTarget::getAsmParser() const {
161 std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
162 if (AsmParserNum >= LI.size())
163 throw "Target does not have an AsmParser #" + utostr(AsmParserNum) + "!";
164 return LI[AsmParserNum];
167 /// getAsmParserVariant - Return the AssmblyParserVariant definition for
170 Record *CodeGenTarget::getAsmParserVariant(unsigned i) const {
171 std::vector<Record*> LI =
172 TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
174 throw "Target does not have an AsmParserVariant #" + utostr(i) + "!";
178 /// getAsmParserVariantCount - Return the AssmblyParserVariant definition
179 /// available for this target.
181 unsigned CodeGenTarget::getAsmParserVariantCount() const {
182 std::vector<Record*> LI =
183 TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
187 /// getAsmWriter - Return the AssemblyWriter definition for this target.
189 Record *CodeGenTarget::getAsmWriter() const {
190 std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
191 if (AsmWriterNum >= LI.size())
192 throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
193 return LI[AsmWriterNum];
196 CodeGenRegBank &CodeGenTarget::getRegBank() const {
198 RegBank = new CodeGenRegBank(Records);
202 void CodeGenTarget::ReadRegAltNameIndices() const {
203 RegAltNameIndices = Records.getAllDerivedDefinitions("RegAltNameIndex");
204 std::sort(RegAltNameIndices.begin(), RegAltNameIndices.end(), LessRecord());
207 /// getRegisterByName - If there is a register with the specific AsmName,
209 const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
210 const StringMap<CodeGenRegister*> &Regs = getRegBank().getRegistersByName();
211 StringMap<CodeGenRegister*>::const_iterator I = Regs.find(Name);
217 std::vector<MVT::SimpleValueType> CodeGenTarget::
218 getRegisterVTs(Record *R) const {
219 const CodeGenRegister *Reg = getRegBank().getReg(R);
220 std::vector<MVT::SimpleValueType> Result;
221 ArrayRef<CodeGenRegisterClass*> RCs = getRegBank().getRegClasses();
222 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
223 const CodeGenRegisterClass &RC = *RCs[i];
224 if (RC.contains(Reg)) {
225 const std::vector<MVT::SimpleValueType> &InVTs = RC.getValueTypes();
226 Result.insert(Result.end(), InVTs.begin(), InVTs.end());
230 // Remove duplicates.
231 array_pod_sort(Result.begin(), Result.end());
232 Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
237 void CodeGenTarget::ReadLegalValueTypes() const {
238 ArrayRef<CodeGenRegisterClass*> RCs = getRegBank().getRegClasses();
239 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
240 for (unsigned ri = 0, re = RCs[i]->VTs.size(); ri != re; ++ri)
241 LegalValueTypes.push_back(RCs[i]->VTs[ri]);
243 // Remove duplicates.
244 std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
245 LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
246 LegalValueTypes.end()),
247 LegalValueTypes.end());
250 CodeGenSchedModels &CodeGenTarget::getSchedModels() const {
252 SchedModels = new CodeGenSchedModels(Records, *this);
256 void CodeGenTarget::ReadInstructions() const {
257 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
258 if (Insts.size() <= 2)
259 throw std::string("No 'Instruction' subclasses defined!");
261 // Parse the instructions defined in the .td file.
262 for (unsigned i = 0, e = Insts.size(); i != e; ++i)
263 Instructions[Insts[i]] = new CodeGenInstruction(Insts[i]);
266 static const CodeGenInstruction *
267 GetInstByName(const char *Name,
268 const DenseMap<const Record*, CodeGenInstruction*> &Insts,
269 RecordKeeper &Records) {
270 const Record *Rec = Records.getDef(Name);
272 DenseMap<const Record*, CodeGenInstruction*>::const_iterator
274 if (Rec == 0 || I == Insts.end())
275 throw std::string("Could not find '") + Name + "' instruction!";
280 /// SortInstByName - Sorting predicate to sort instructions by name.
282 struct SortInstByName {
283 bool operator()(const CodeGenInstruction *Rec1,
284 const CodeGenInstruction *Rec2) const {
285 return Rec1->TheDef->getName() < Rec2->TheDef->getName();
290 /// getInstructionsByEnumValue - Return all of the instructions defined by the
291 /// target, ordered by their enum value.
292 void CodeGenTarget::ComputeInstrsByEnum() const {
293 // The ordering here must match the ordering in TargetOpcodes.h.
294 const char *const FixedInstrs[] = {
314 const DenseMap<const Record*, CodeGenInstruction*> &Insts = getInstructions();
315 for (const char *const *p = FixedInstrs; *p; ++p) {
316 const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
317 assert(Instr && "Missing target independent instruction");
318 assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
319 InstrsByEnum.push_back(Instr);
321 unsigned EndOfPredefines = InstrsByEnum.size();
323 for (DenseMap<const Record*, CodeGenInstruction*>::const_iterator
324 I = Insts.begin(), E = Insts.end(); I != E; ++I) {
325 const CodeGenInstruction *CGI = I->second;
326 if (CGI->Namespace != "TargetOpcode")
327 InstrsByEnum.push_back(CGI);
330 assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
332 // All of the instructions are now in random order based on the map iteration.
333 // Sort them by name.
334 std::sort(InstrsByEnum.begin()+EndOfPredefines, InstrsByEnum.end(),
339 /// isLittleEndianEncoding - Return whether this target encodes its instruction
340 /// in little-endian format, i.e. bits laid out in the order [0..n]
342 bool CodeGenTarget::isLittleEndianEncoding() const {
343 return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
346 /// guessInstructionProperties - Return true if it's OK to guess instruction
347 /// properties instead of raising an error.
349 /// This is configurable as a temporary migration aid. It will eventually be
350 /// permanently false.
351 bool CodeGenTarget::guessInstructionProperties() const {
352 return getInstructionSet()->getValueAsBit("guessInstructionProperties");
355 //===----------------------------------------------------------------------===//
356 // ComplexPattern implementation
358 ComplexPattern::ComplexPattern(Record *R) {
359 Ty = ::getValueType(R->getValueAsDef("Ty"));
360 NumOperands = R->getValueAsInt("NumOperands");
361 SelectFunc = R->getValueAsString("SelectFunc");
362 RootNodes = R->getValueAsListOfDefs("RootNodes");
364 // Parse the properties.
366 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
367 for (unsigned i = 0, e = PropList.size(); i != e; ++i)
368 if (PropList[i]->getName() == "SDNPHasChain") {
369 Properties |= 1 << SDNPHasChain;
370 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
371 Properties |= 1 << SDNPOptInGlue;
372 } else if (PropList[i]->getName() == "SDNPMayStore") {
373 Properties |= 1 << SDNPMayStore;
374 } else if (PropList[i]->getName() == "SDNPMayLoad") {
375 Properties |= 1 << SDNPMayLoad;
376 } else if (PropList[i]->getName() == "SDNPSideEffect") {
377 Properties |= 1 << SDNPSideEffect;
378 } else if (PropList[i]->getName() == "SDNPMemOperand") {
379 Properties |= 1 << SDNPMemOperand;
380 } else if (PropList[i]->getName() == "SDNPVariadic") {
381 Properties |= 1 << SDNPVariadic;
382 } else if (PropList[i]->getName() == "SDNPWantRoot") {
383 Properties |= 1 << SDNPWantRoot;
384 } else if (PropList[i]->getName() == "SDNPWantParent") {
385 Properties |= 1 << SDNPWantParent;
387 errs() << "Unsupported SD Node property '" << PropList[i]->getName()
388 << "' on ComplexPattern '" << R->getName() << "'!\n";
393 //===----------------------------------------------------------------------===//
394 // CodeGenIntrinsic Implementation
395 //===----------------------------------------------------------------------===//
397 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC,
399 std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
401 std::vector<CodeGenIntrinsic> Result;
403 for (unsigned i = 0, e = I.size(); i != e; ++i) {
404 bool isTarget = I[i]->getValueAsBit("isTarget");
405 if (isTarget == TargetOnly)
406 Result.push_back(CodeGenIntrinsic(I[i]));
411 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
413 std::string DefName = R->getName();
414 ModRef = ReadWriteMem;
415 isOverloaded = false;
416 isCommutative = false;
420 if (DefName.size() <= 4 ||
421 std::string(DefName.begin(), DefName.begin() + 4) != "int_")
422 throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
424 EnumName = std::string(DefName.begin()+4, DefName.end());
426 if (R->getValue("GCCBuiltinName")) // Ignore a missing GCCBuiltinName field.
427 GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
429 TargetPrefix = R->getValueAsString("TargetPrefix");
430 Name = R->getValueAsString("LLVMName");
433 // If an explicit name isn't specified, derive one from the DefName.
436 for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
437 Name += (EnumName[i] == '_') ? '.' : EnumName[i];
439 // Verify it starts with "llvm.".
440 if (Name.size() <= 5 ||
441 std::string(Name.begin(), Name.begin() + 5) != "llvm.")
442 throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
445 // If TargetPrefix is specified, make sure that Name starts with
446 // "llvm.<targetprefix>.".
447 if (!TargetPrefix.empty()) {
448 if (Name.size() < 6+TargetPrefix.size() ||
449 std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
450 != (TargetPrefix + "."))
451 throw "Intrinsic '" + DefName + "' does not start with 'llvm." +
452 TargetPrefix + ".'!";
455 // Parse the list of return types.
456 std::vector<MVT::SimpleValueType> OverloadedVTs;
457 ListInit *TypeList = R->getValueAsListInit("RetTypes");
458 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
459 Record *TyEl = TypeList->getElementAsRecord(i);
460 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
461 MVT::SimpleValueType VT;
462 if (TyEl->isSubClassOf("LLVMMatchType")) {
463 unsigned MatchTy = TyEl->getValueAsInt("Number");
464 assert(MatchTy < OverloadedVTs.size() &&
465 "Invalid matching number!");
466 VT = OverloadedVTs[MatchTy];
467 // It only makes sense to use the extended and truncated vector element
468 // variants with iAny types; otherwise, if the intrinsic is not
469 // overloaded, all the types can be specified directly.
470 assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
471 !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
472 VT == MVT::iAny || VT == MVT::vAny) &&
473 "Expected iAny or vAny type");
475 VT = getValueType(TyEl->getValueAsDef("VT"));
477 if (EVT(VT).isOverloaded()) {
478 OverloadedVTs.push_back(VT);
482 // Reject invalid types.
483 if (VT == MVT::isVoid)
484 throw "Intrinsic '" + DefName + " has void in result type list!";
486 IS.RetVTs.push_back(VT);
487 IS.RetTypeDefs.push_back(TyEl);
490 // Parse the list of parameter types.
491 TypeList = R->getValueAsListInit("ParamTypes");
492 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
493 Record *TyEl = TypeList->getElementAsRecord(i);
494 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
495 MVT::SimpleValueType VT;
496 if (TyEl->isSubClassOf("LLVMMatchType")) {
497 unsigned MatchTy = TyEl->getValueAsInt("Number");
498 assert(MatchTy < OverloadedVTs.size() &&
499 "Invalid matching number!");
500 VT = OverloadedVTs[MatchTy];
501 // It only makes sense to use the extended and truncated vector element
502 // variants with iAny types; otherwise, if the intrinsic is not
503 // overloaded, all the types can be specified directly.
504 assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
505 !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
506 VT == MVT::iAny || VT == MVT::vAny) &&
507 "Expected iAny or vAny type");
509 VT = getValueType(TyEl->getValueAsDef("VT"));
511 if (EVT(VT).isOverloaded()) {
512 OverloadedVTs.push_back(VT);
516 // Reject invalid types.
517 if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
518 throw "Intrinsic '" + DefName + " has void in result type list!";
520 IS.ParamVTs.push_back(VT);
521 IS.ParamTypeDefs.push_back(TyEl);
524 // Parse the intrinsic properties.
525 ListInit *PropList = R->getValueAsListInit("Properties");
526 for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
527 Record *Property = PropList->getElementAsRecord(i);
528 assert(Property->isSubClassOf("IntrinsicProperty") &&
529 "Expected a property!");
531 if (Property->getName() == "IntrNoMem")
533 else if (Property->getName() == "IntrReadArgMem")
535 else if (Property->getName() == "IntrReadMem")
537 else if (Property->getName() == "IntrReadWriteArgMem")
538 ModRef = ReadWriteArgMem;
539 else if (Property->getName() == "Commutative")
540 isCommutative = true;
541 else if (Property->getName() == "Throws")
543 else if (Property->getName() == "IntrNoReturn")
545 else if (Property->isSubClassOf("NoCapture")) {
546 unsigned ArgNo = Property->getValueAsInt("ArgNo");
547 ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
549 llvm_unreachable("Unknown property!");
552 // Sort the argument attributes for later benefit.
553 std::sort(ArgumentAttributes.begin(), ArgumentAttributes.end());