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"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Support/CommandLine.h"
26 static cl::opt<unsigned>
27 AsmParserNum("asmparsernum", cl::init(0),
28 cl::desc("Make -gen-asm-parser emit assembly parser #N"));
30 static cl::opt<unsigned>
31 AsmWriterNum("asmwriternum", cl::init(0),
32 cl::desc("Make -gen-asm-writer emit assembly writer #N"));
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");
40 std::string llvm::getName(MVT::SimpleValueType 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);
49 std::string llvm::getEnumName(MVT::SimpleValueType 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 "";
97 /// getQualifiedName - Return the name of the specified record, with a
98 /// namespace qualifier if the record contains one.
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();
109 /// getTarget - Return the current instance of the Target class.
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];
122 const std::string &CodeGenTarget::getName() const {
123 return TargetRec->getName();
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;
137 Record *CodeGenTarget::getInstructionSet() const {
138 return TargetRec->getValueAsDef("InstructionSet");
142 /// getAsmParser - Return the AssemblyParser definition for this target.
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];
151 /// getAsmWriter - Return the AssemblyWriter definition for this target.
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];
160 CodeGenRegBank &CodeGenTarget::getRegBank() const {
162 RegBank = new CodeGenRegBank(Records);
166 /// getRegisterByName - If there is a register with the specific AsmName,
168 const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
169 const std::vector<CodeGenRegister> &Regs = getRegBank().getRegisters();
170 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
171 const CodeGenRegister &Reg = Regs[i];
172 if (Reg.TheDef->getValueAsString("AsmName") == Name)
179 std::vector<MVT::SimpleValueType> CodeGenTarget::
180 getRegisterVTs(Record *R) const {
181 const CodeGenRegister *Reg = getRegBank().getReg(R);
182 std::vector<MVT::SimpleValueType> Result;
183 const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
184 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
185 const CodeGenRegisterClass &RC = RCs[i];
186 if (RC.contains(Reg)) {
187 const std::vector<MVT::SimpleValueType> &InVTs = RC.getValueTypes();
188 Result.insert(Result.end(), InVTs.begin(), InVTs.end());
192 // Remove duplicates.
193 array_pod_sort(Result.begin(), Result.end());
194 Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
199 void CodeGenTarget::ReadLegalValueTypes() const {
200 const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
201 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
202 for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)
203 LegalValueTypes.push_back(RCs[i].VTs[ri]);
205 // Remove duplicates.
206 std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
207 LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
208 LegalValueTypes.end()),
209 LegalValueTypes.end());
213 void CodeGenTarget::ReadInstructions() const {
214 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
215 if (Insts.size() <= 2)
216 throw std::string("No 'Instruction' subclasses defined!");
218 // Parse the instructions defined in the .td file.
219 for (unsigned i = 0, e = Insts.size(); i != e; ++i)
220 Instructions[Insts[i]] = new CodeGenInstruction(Insts[i]);
223 static const CodeGenInstruction *
224 GetInstByName(const char *Name,
225 const DenseMap<const Record*, CodeGenInstruction*> &Insts,
226 RecordKeeper &Records) {
227 const Record *Rec = Records.getDef(Name);
229 DenseMap<const Record*, CodeGenInstruction*>::const_iterator
231 if (Rec == 0 || I == Insts.end())
232 throw std::string("Could not find '") + Name + "' instruction!";
237 /// SortInstByName - Sorting predicate to sort instructions by name.
239 struct SortInstByName {
240 bool operator()(const CodeGenInstruction *Rec1,
241 const CodeGenInstruction *Rec2) const {
242 return Rec1->TheDef->getName() < Rec2->TheDef->getName();
247 /// getInstructionsByEnumValue - Return all of the instructions defined by the
248 /// target, ordered by their enum value.
249 void CodeGenTarget::ComputeInstrsByEnum() const {
250 // The ordering here must match the ordering in TargetOpcodes.h.
251 const char *const FixedInstrs[] = {
268 const DenseMap<const Record*, CodeGenInstruction*> &Insts = getInstructions();
269 for (const char *const *p = FixedInstrs; *p; ++p) {
270 const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
271 assert(Instr && "Missing target independent instruction");
272 assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
273 InstrsByEnum.push_back(Instr);
275 unsigned EndOfPredefines = InstrsByEnum.size();
277 for (DenseMap<const Record*, CodeGenInstruction*>::const_iterator
278 I = Insts.begin(), E = Insts.end(); I != E; ++I) {
279 const CodeGenInstruction *CGI = I->second;
280 if (CGI->Namespace != "TargetOpcode")
281 InstrsByEnum.push_back(CGI);
284 assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
286 // All of the instructions are now in random order based on the map iteration.
287 // Sort them by name.
288 std::sort(InstrsByEnum.begin()+EndOfPredefines, InstrsByEnum.end(),
293 /// isLittleEndianEncoding - Return whether this target encodes its instruction
294 /// in little-endian format, i.e. bits laid out in the order [0..n]
296 bool CodeGenTarget::isLittleEndianEncoding() const {
297 return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
300 //===----------------------------------------------------------------------===//
301 // ComplexPattern implementation
303 ComplexPattern::ComplexPattern(Record *R) {
304 Ty = ::getValueType(R->getValueAsDef("Ty"));
305 NumOperands = R->getValueAsInt("NumOperands");
306 SelectFunc = R->getValueAsString("SelectFunc");
307 RootNodes = R->getValueAsListOfDefs("RootNodes");
309 // Parse the properties.
311 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
312 for (unsigned i = 0, e = PropList.size(); i != e; ++i)
313 if (PropList[i]->getName() == "SDNPHasChain") {
314 Properties |= 1 << SDNPHasChain;
315 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
316 Properties |= 1 << SDNPOptInGlue;
317 } else if (PropList[i]->getName() == "SDNPMayStore") {
318 Properties |= 1 << SDNPMayStore;
319 } else if (PropList[i]->getName() == "SDNPMayLoad") {
320 Properties |= 1 << SDNPMayLoad;
321 } else if (PropList[i]->getName() == "SDNPSideEffect") {
322 Properties |= 1 << SDNPSideEffect;
323 } else if (PropList[i]->getName() == "SDNPMemOperand") {
324 Properties |= 1 << SDNPMemOperand;
325 } else if (PropList[i]->getName() == "SDNPVariadic") {
326 Properties |= 1 << SDNPVariadic;
327 } else if (PropList[i]->getName() == "SDNPWantRoot") {
328 Properties |= 1 << SDNPWantRoot;
329 } else if (PropList[i]->getName() == "SDNPWantParent") {
330 Properties |= 1 << SDNPWantParent;
332 errs() << "Unsupported SD Node property '" << PropList[i]->getName()
333 << "' on ComplexPattern '" << R->getName() << "'!\n";
338 //===----------------------------------------------------------------------===//
339 // CodeGenIntrinsic Implementation
340 //===----------------------------------------------------------------------===//
342 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC,
344 std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
346 std::vector<CodeGenIntrinsic> Result;
348 for (unsigned i = 0, e = I.size(); i != e; ++i) {
349 bool isTarget = I[i]->getValueAsBit("isTarget");
350 if (isTarget == TargetOnly)
351 Result.push_back(CodeGenIntrinsic(I[i]));
356 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
358 std::string DefName = R->getName();
359 ModRef = ReadWriteMem;
360 isOverloaded = false;
361 isCommutative = false;
364 if (DefName.size() <= 4 ||
365 std::string(DefName.begin(), DefName.begin() + 4) != "int_")
366 throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
368 EnumName = std::string(DefName.begin()+4, DefName.end());
370 if (R->getValue("GCCBuiltinName")) // Ignore a missing GCCBuiltinName field.
371 GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
373 TargetPrefix = R->getValueAsString("TargetPrefix");
374 Name = R->getValueAsString("LLVMName");
377 // If an explicit name isn't specified, derive one from the DefName.
380 for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
381 Name += (EnumName[i] == '_') ? '.' : EnumName[i];
383 // Verify it starts with "llvm.".
384 if (Name.size() <= 5 ||
385 std::string(Name.begin(), Name.begin() + 5) != "llvm.")
386 throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
389 // If TargetPrefix is specified, make sure that Name starts with
390 // "llvm.<targetprefix>.".
391 if (!TargetPrefix.empty()) {
392 if (Name.size() < 6+TargetPrefix.size() ||
393 std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
394 != (TargetPrefix + "."))
395 throw "Intrinsic '" + DefName + "' does not start with 'llvm." +
396 TargetPrefix + ".'!";
399 // Parse the list of return types.
400 std::vector<MVT::SimpleValueType> OverloadedVTs;
401 ListInit *TypeList = R->getValueAsListInit("RetTypes");
402 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
403 Record *TyEl = TypeList->getElementAsRecord(i);
404 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
405 MVT::SimpleValueType VT;
406 if (TyEl->isSubClassOf("LLVMMatchType")) {
407 unsigned MatchTy = TyEl->getValueAsInt("Number");
408 assert(MatchTy < OverloadedVTs.size() &&
409 "Invalid matching number!");
410 VT = OverloadedVTs[MatchTy];
411 // It only makes sense to use the extended and truncated vector element
412 // variants with iAny types; otherwise, if the intrinsic is not
413 // overloaded, all the types can be specified directly.
414 assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
415 !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
416 VT == MVT::iAny || VT == MVT::vAny) &&
417 "Expected iAny or vAny type");
419 VT = getValueType(TyEl->getValueAsDef("VT"));
421 if (EVT(VT).isOverloaded()) {
422 OverloadedVTs.push_back(VT);
426 // Reject invalid types.
427 if (VT == MVT::isVoid)
428 throw "Intrinsic '" + DefName + " has void in result type list!";
430 IS.RetVTs.push_back(VT);
431 IS.RetTypeDefs.push_back(TyEl);
434 // Parse the list of parameter types.
435 TypeList = R->getValueAsListInit("ParamTypes");
436 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
437 Record *TyEl = TypeList->getElementAsRecord(i);
438 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
439 MVT::SimpleValueType VT;
440 if (TyEl->isSubClassOf("LLVMMatchType")) {
441 unsigned MatchTy = TyEl->getValueAsInt("Number");
442 assert(MatchTy < OverloadedVTs.size() &&
443 "Invalid matching number!");
444 VT = OverloadedVTs[MatchTy];
445 // It only makes sense to use the extended and truncated vector element
446 // variants with iAny types; otherwise, if the intrinsic is not
447 // overloaded, all the types can be specified directly.
448 assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
449 !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
450 VT == MVT::iAny || VT == MVT::vAny) &&
451 "Expected iAny or vAny type");
453 VT = getValueType(TyEl->getValueAsDef("VT"));
455 if (EVT(VT).isOverloaded()) {
456 OverloadedVTs.push_back(VT);
460 // Reject invalid types.
461 if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
462 throw "Intrinsic '" + DefName + " has void in result type list!";
464 IS.ParamVTs.push_back(VT);
465 IS.ParamTypeDefs.push_back(TyEl);
468 // Parse the intrinsic properties.
469 ListInit *PropList = R->getValueAsListInit("Properties");
470 for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
471 Record *Property = PropList->getElementAsRecord(i);
472 assert(Property->isSubClassOf("IntrinsicProperty") &&
473 "Expected a property!");
475 if (Property->getName() == "IntrNoMem")
477 else if (Property->getName() == "IntrReadArgMem")
479 else if (Property->getName() == "IntrReadMem")
481 else if (Property->getName() == "IntrReadWriteArgMem")
482 ModRef = ReadWriteArgMem;
483 else if (Property->getName() == "Commutative")
484 isCommutative = true;
485 else if (Property->getName() == "Throws")
487 else if (Property->isSubClassOf("NoCapture")) {
488 unsigned ArgNo = Property->getValueAsInt("ArgNo");
489 ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
491 assert(0 && "Unknown property!");
494 // Sort the argument attributes for later benefit.
495 std::sort(ArgumentAttributes.begin(), ArgumentAttributes.end());