1 //===- CodeGenTarget.cpp - CodeGen Target Class Wrapper ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class wrap 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/Support/CommandLine.h"
22 #include "llvm/Target/TargetInstrInfo.h"
27 static cl::opt<unsigned>
28 AsmWriterNum("asmwriternum", cl::init(0),
29 cl::desc("Make -gen-asm-writer emit assembly writer #N"));
31 /// getValueType - Return the MCV::ValueType that the specified TableGen record
33 MVT::ValueType llvm::getValueType(Record *Rec, const CodeGenTarget *CGT) {
34 return (MVT::ValueType)Rec->getValueAsInt("Value");
37 std::string llvm::getName(MVT::ValueType T) {
39 case MVT::Other: return "UNKNOWN";
40 case MVT::i1: return "MVT::i1";
41 case MVT::i8: return "MVT::i8";
42 case MVT::i16: return "MVT::i16";
43 case MVT::i32: return "MVT::i32";
44 case MVT::i64: return "MVT::i64";
45 case MVT::i128: return "MVT::i128";
46 case MVT::f32: return "MVT::f32";
47 case MVT::f64: return "MVT::f64";
48 case MVT::f80: return "MVT::f80";
49 case MVT::f128: return "MVT::f128";
50 case MVT::Flag: return "MVT::Flag";
51 case MVT::isVoid:return "MVT::void";
52 case MVT::v8i8: return "MVT::v8i8";
53 case MVT::v4i16: return "MVT::v4i16";
54 case MVT::v2i32: return "MVT::v2i32";
55 case MVT::v16i8: return "MVT::v16i8";
56 case MVT::v8i16: return "MVT::v8i16";
57 case MVT::v4i32: return "MVT::v4i32";
58 case MVT::v2i64: return "MVT::v2i64";
59 case MVT::v2f32: return "MVT::v2f32";
60 case MVT::v4f32: return "MVT::v4f32";
61 case MVT::v2f64: return "MVT::v2f64";
62 case MVT::iPTR: return "TLI.getPointerTy()";
63 default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
67 std::string llvm::getEnumName(MVT::ValueType T) {
69 case MVT::Other: return "MVT::Other";
70 case MVT::i1: return "MVT::i1";
71 case MVT::i8: return "MVT::i8";
72 case MVT::i16: return "MVT::i16";
73 case MVT::i32: return "MVT::i32";
74 case MVT::i64: return "MVT::i64";
75 case MVT::i128: return "MVT::i128";
76 case MVT::f32: return "MVT::f32";
77 case MVT::f64: return "MVT::f64";
78 case MVT::f80: return "MVT::f80";
79 case MVT::f128: return "MVT::f128";
80 case MVT::Flag: return "MVT::Flag";
81 case MVT::isVoid:return "MVT::isVoid";
82 case MVT::v8i8: return "MVT::v8i8";
83 case MVT::v4i16: return "MVT::v4i16";
84 case MVT::v2i32: return "MVT::v2i32";
85 case MVT::v16i8: return "MVT::v16i8";
86 case MVT::v8i16: return "MVT::v8i16";
87 case MVT::v4i32: return "MVT::v4i32";
88 case MVT::v2i64: return "MVT::v2i64";
89 case MVT::v2f32: return "MVT::v2f32";
90 case MVT::v4f32: return "MVT::v4f32";
91 case MVT::v2f64: return "MVT::v2f64";
92 case MVT::iPTR: return "TLI.getPointerTy()";
93 default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
98 std::ostream &llvm::operator<<(std::ostream &OS, MVT::ValueType T) {
99 return OS << getName(T);
103 /// getTarget - Return the current instance of the Target class.
105 CodeGenTarget::CodeGenTarget() {
106 std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
107 if (Targets.size() == 0)
108 throw std::string("ERROR: No 'Target' subclasses defined!");
109 if (Targets.size() != 1)
110 throw std::string("ERROR: Multiple subclasses of Target defined!");
111 TargetRec = Targets[0];
115 const std::string &CodeGenTarget::getName() const {
116 return TargetRec->getName();
119 Record *CodeGenTarget::getInstructionSet() const {
120 return TargetRec->getValueAsDef("InstructionSet");
123 /// getAsmWriter - Return the AssemblyWriter definition for this target.
125 Record *CodeGenTarget::getAsmWriter() const {
126 std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
127 if (AsmWriterNum >= LI.size())
128 throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
129 return LI[AsmWriterNum];
132 void CodeGenTarget::ReadRegisters() const {
133 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
135 throw std::string("No 'Register' subclasses defined!");
137 Registers.reserve(Regs.size());
138 Registers.assign(Regs.begin(), Regs.end());
141 CodeGenRegister::CodeGenRegister(Record *R) : TheDef(R) {
142 DeclaredSpillSize = R->getValueAsInt("SpillSize");
143 DeclaredSpillAlignment = R->getValueAsInt("SpillAlignment");
146 const std::string &CodeGenRegister::getName() const {
147 return TheDef->getName();
150 void CodeGenTarget::ReadRegisterClasses() const {
151 std::vector<Record*> RegClasses =
152 Records.getAllDerivedDefinitions("RegisterClass");
153 if (RegClasses.empty())
154 throw std::string("No 'RegisterClass' subclasses defined!");
156 RegisterClasses.reserve(RegClasses.size());
157 RegisterClasses.assign(RegClasses.begin(), RegClasses.end());
160 std::vector<unsigned char> CodeGenTarget::getRegisterVTs(Record *R) const {
161 std::vector<unsigned char> Result;
162 const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
163 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
164 const CodeGenRegisterClass &RC = RegisterClasses[i];
165 for (unsigned ei = 0, ee = RC.Elements.size(); ei != ee; ++ei) {
166 if (R == RC.Elements[ei]) {
167 const std::vector<MVT::ValueType> &InVTs = RC.getValueTypes();
168 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
169 Result.push_back(InVTs[i]);
177 CodeGenRegisterClass::CodeGenRegisterClass(Record *R) : TheDef(R) {
178 // Rename anonymous register classes.
179 if (R->getName().size() > 9 && R->getName()[9] == '.') {
180 static unsigned AnonCounter = 0;
181 R->setName("AnonRegClass_"+utostr(AnonCounter++));
184 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
185 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
186 Record *Type = TypeList[i];
187 if (!Type->isSubClassOf("ValueType"))
188 throw "RegTypes list member '" + Type->getName() +
189 "' does not derive from the ValueType class!";
190 VTs.push_back(getValueType(Type));
192 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
194 std::vector<Record*> RegList = R->getValueAsListOfDefs("MemberList");
195 for (unsigned i = 0, e = RegList.size(); i != e; ++i) {
196 Record *Reg = RegList[i];
197 if (!Reg->isSubClassOf("Register"))
198 throw "Register Class member '" + Reg->getName() +
199 "' does not derive from the Register class!";
200 Elements.push_back(Reg);
203 // Allow targets to override the size in bits of the RegisterClass.
204 unsigned Size = R->getValueAsInt("Size");
206 Namespace = R->getValueAsString("Namespace");
207 SpillSize = Size ? Size : MVT::getSizeInBits(VTs[0]);
208 SpillAlignment = R->getValueAsInt("Alignment");
209 MethodBodies = R->getValueAsCode("MethodBodies");
210 MethodProtos = R->getValueAsCode("MethodProtos");
213 const std::string &CodeGenRegisterClass::getName() const {
214 return TheDef->getName();
217 void CodeGenTarget::ReadLegalValueTypes() const {
218 const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
219 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
220 for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)
221 LegalValueTypes.push_back(RCs[i].VTs[ri]);
223 // Remove duplicates.
224 std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
225 LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
226 LegalValueTypes.end()),
227 LegalValueTypes.end());
231 void CodeGenTarget::ReadInstructions() const {
232 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
233 if (Insts.size() <= 2)
234 throw std::string("No 'Instruction' subclasses defined!");
236 // Parse the instructions defined in the .td file.
237 std::string InstFormatName =
238 getAsmWriter()->getValueAsString("InstFormatName");
240 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
241 std::string AsmStr = Insts[i]->getValueAsString(InstFormatName);
242 Instructions.insert(std::make_pair(Insts[i]->getName(),
243 CodeGenInstruction(Insts[i], AsmStr)));
247 /// getInstructionsByEnumValue - Return all of the instructions defined by the
248 /// target, ordered by their enum value.
250 getInstructionsByEnumValue(std::vector<const CodeGenInstruction*>
251 &NumberedInstructions) {
252 std::map<std::string, CodeGenInstruction>::const_iterator I;
253 I = getInstructions().find("PHI");
254 if (I == Instructions.end()) throw "Could not find 'PHI' instruction!";
255 const CodeGenInstruction *PHI = &I->second;
257 I = getInstructions().find("INLINEASM");
258 if (I == Instructions.end()) throw "Could not find 'INLINEASM' instruction!";
259 const CodeGenInstruction *INLINEASM = &I->second;
261 // Print out the rest of the instructions now.
262 NumberedInstructions.push_back(PHI);
263 NumberedInstructions.push_back(INLINEASM);
264 for (inst_iterator II = inst_begin(), E = inst_end(); II != E; ++II)
265 if (&II->second != PHI &&&II->second != INLINEASM)
266 NumberedInstructions.push_back(&II->second);
270 /// isLittleEndianEncoding - Return whether this target encodes its instruction
271 /// in little-endian format, i.e. bits laid out in the order [0..n]
273 bool CodeGenTarget::isLittleEndianEncoding() const {
274 return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
277 static std::pair<unsigned, unsigned> parseConstraint(const std::string &CStr,
278 CodeGenInstruction *I) {
279 const std::string ops("="); // FIXME: Only supports TIED_TO for now.
280 std::string::size_type pos = CStr.find_first_of(ops);
281 assert(pos != std::string::npos && "Unrecognized constraint");
282 std::string Name = CStr.substr(1, pos); // Skip '$'
284 // TIED_TO: $src1 = $dst
285 const std::string delims(" \t");
286 std::string::size_type wpos = Name.find_first_of(delims);
287 if (wpos != std::string::npos)
288 Name = Name.substr(0, wpos);
289 unsigned FIdx = I->getOperandNamed(Name);
291 Name = CStr.substr(pos+1);
292 wpos = Name.find_first_not_of(delims);
293 if (wpos != std::string::npos)
294 Name = Name.substr(wpos+1);
295 unsigned TIdx = I->getOperandNamed(Name);
297 throw "Illegal tied-to operand constraint '" + CStr + "'";
298 return std::make_pair(FIdx, (TIdx << 16) |
299 (1 << (unsigned)TargetInstrInfo::TIED_TO));
302 static std::vector<unsigned> parseConstraints(const std::string &CStr,
303 CodeGenInstruction *I) {
304 unsigned NumOps = I->OperandList.size();
305 std::vector<unsigned> Res(NumOps, 0);
309 const std::string delims(",");
310 std::string::size_type bidx, eidx;
312 bidx = CStr.find_first_not_of(delims);
313 while (bidx != std::string::npos) {
314 eidx = CStr.find_first_of(delims, bidx);
315 if (eidx == std::string::npos)
316 eidx = CStr.length();
317 std::pair<unsigned, unsigned> C =
318 parseConstraint(CStr.substr(bidx, eidx), I);
319 Res[C.first] = C.second;
320 bidx = CStr.find_first_not_of(delims, eidx);
326 CodeGenInstruction::CodeGenInstruction(Record *R, const std::string &AsmStr)
327 : TheDef(R), AsmString(AsmStr) {
328 Name = R->getValueAsString("Name");
329 Namespace = R->getValueAsString("Namespace");
331 isReturn = R->getValueAsBit("isReturn");
332 isBranch = R->getValueAsBit("isBranch");
333 isBarrier = R->getValueAsBit("isBarrier");
334 isCall = R->getValueAsBit("isCall");
335 isLoad = R->getValueAsBit("isLoad");
336 isStore = R->getValueAsBit("isStore");
337 isTwoAddress = R->getValueAsBit("isTwoAddress");
338 isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
339 isCommutable = R->getValueAsBit("isCommutable");
340 isTerminator = R->getValueAsBit("isTerminator");
341 hasDelaySlot = R->getValueAsBit("hasDelaySlot");
342 usesCustomDAGSchedInserter = R->getValueAsBit("usesCustomDAGSchedInserter");
343 hasCtrlDep = R->getValueAsBit("hasCtrlDep");
344 noResults = R->getValueAsBit("noResults");
345 hasVariableNumberOfOperands = false;
349 DI = R->getValueAsDag("OperandList");
351 // Error getting operand list, just ignore it (sparcv9).
357 unsigned MIOperandNo = 0;
358 std::set<std::string> OperandNames;
359 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
360 DefInit *Arg = dynamic_cast<DefInit*>(DI->getArg(i));
362 throw "Illegal operand for the '" + R->getName() + "' instruction!";
364 Record *Rec = Arg->getDef();
365 std::string PrintMethod = "printOperand";
367 DagInit *MIOpInfo = 0;
368 if (Rec->isSubClassOf("Operand")) {
369 PrintMethod = Rec->getValueAsString("PrintMethod");
370 MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
372 // Verify that MIOpInfo has an 'ops' root value.
373 if (!dynamic_cast<DefInit*>(MIOpInfo->getOperator()) ||
374 dynamic_cast<DefInit*>(MIOpInfo->getOperator())
375 ->getDef()->getName() != "ops")
376 throw "Bad value for MIOperandInfo in operand '" + Rec->getName() +
379 // If we have MIOpInfo, then we have #operands equal to number of entries
381 if (unsigned NumArgs = MIOpInfo->getNumArgs())
384 } else if (Rec->getName() == "variable_ops") {
385 hasVariableNumberOfOperands = true;
387 } else if (!Rec->isSubClassOf("RegisterClass"))
388 throw "Unknown operand class '" + Rec->getName() +
389 "' in instruction '" + R->getName() + "' instruction!";
391 // Check that the operand has a name and that it's unique.
392 if (DI->getArgName(i).empty())
393 throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
395 if (!OperandNames.insert(DI->getArgName(i)).second)
396 throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
397 " has the same name as a previous operand!";
399 OperandList.push_back(OperandInfo(Rec, DI->getArgName(i), PrintMethod,
400 MIOperandNo, NumOps, MIOpInfo));
401 MIOperandNo += NumOps;
404 ConstraintStr = R->getValueAsString("Constraints");
405 ConstraintsList = parseConstraints(ConstraintStr, this);
410 /// getOperandNamed - Return the index of the operand with the specified
411 /// non-empty name. If the instruction does not have an operand with the
412 /// specified name, throw an exception.
414 unsigned CodeGenInstruction::getOperandNamed(const std::string &Name) const {
415 assert(!Name.empty() && "Cannot search for operand with no name!");
416 for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
417 if (OperandList[i].Name == Name) return i;
418 throw "Instruction '" + TheDef->getName() +
419 "' does not have an operand named '$" + Name + "'!";
422 //===----------------------------------------------------------------------===//
423 // ComplexPattern implementation
425 ComplexPattern::ComplexPattern(Record *R) {
426 Ty = ::getValueType(R->getValueAsDef("Ty"));
427 NumOperands = R->getValueAsInt("NumOperands");
428 SelectFunc = R->getValueAsString("SelectFunc");
429 RootNodes = R->getValueAsListOfDefs("RootNodes");
431 // Parse the properties.
433 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
434 for (unsigned i = 0, e = PropList.size(); i != e; ++i)
435 if (PropList[i]->getName() == "SDNPHasChain") {
436 Properties |= 1 << SDNPHasChain;
437 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
438 Properties |= 1 << SDNPOptInFlag;
440 std::cerr << "Unsupported SD Node property '" << PropList[i]->getName()
441 << "' on ComplexPattern '" << R->getName() << "'!\n";
446 //===----------------------------------------------------------------------===//
447 // CodeGenIntrinsic Implementation
448 //===----------------------------------------------------------------------===//
450 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC) {
451 std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
453 std::vector<CodeGenIntrinsic> Result;
455 // If we are in the context of a target .td file, get the target info so that
456 // we can decode the current intptr_t.
457 CodeGenTarget *CGT = 0;
458 if (Records.getClass("Target") &&
459 Records.getAllDerivedDefinitions("Target").size() == 1)
460 CGT = new CodeGenTarget();
462 for (unsigned i = 0, e = I.size(); i != e; ++i)
463 Result.push_back(CodeGenIntrinsic(I[i], CGT));
468 CodeGenIntrinsic::CodeGenIntrinsic(Record *R, CodeGenTarget *CGT) {
470 std::string DefName = R->getName();
473 if (DefName.size() <= 4 ||
474 std::string(DefName.begin(), DefName.begin()+4) != "int_")
475 throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
476 EnumName = std::string(DefName.begin()+4, DefName.end());
477 if (R->getValue("GCCBuiltinName")) // Ignore a missing GCCBuiltinName field.
478 GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
479 TargetPrefix = R->getValueAsString("TargetPrefix");
480 Name = R->getValueAsString("LLVMName");
482 // If an explicit name isn't specified, derive one from the DefName.
484 for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
485 if (EnumName[i] == '_')
490 // Verify it starts with "llvm.".
491 if (Name.size() <= 5 ||
492 std::string(Name.begin(), Name.begin()+5) != "llvm.")
493 throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
496 // If TargetPrefix is specified, make sure that Name starts with
497 // "llvm.<targetprefix>.".
498 if (!TargetPrefix.empty()) {
499 if (Name.size() < 6+TargetPrefix.size() ||
500 std::string(Name.begin()+5, Name.begin()+6+TargetPrefix.size())
501 != (TargetPrefix+"."))
502 throw "Intrinsic '" + DefName + "' does not start with 'llvm." +
503 TargetPrefix + ".'!";
506 // Parse the list of argument types.
507 ListInit *TypeList = R->getValueAsListInit("Types");
508 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
509 DefInit *DI = dynamic_cast<DefInit*>(TypeList->getElement(i));
510 assert(DI && "Invalid list type!");
511 Record *TyEl = DI->getDef();
512 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
513 ArgTypes.push_back(TyEl->getValueAsString("TypeVal"));
516 ArgVTs.push_back(getValueType(TyEl->getValueAsDef("VT"), CGT));
517 ArgTypeDefs.push_back(TyEl);
519 if (ArgTypes.size() == 0)
520 throw "Intrinsic '"+DefName+"' needs at least a type for the ret value!";
522 // Parse the intrinsic properties.
523 ListInit *PropList = R->getValueAsListInit("Properties");
524 for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
525 DefInit *DI = dynamic_cast<DefInit*>(PropList->getElement(i));
526 assert(DI && "Invalid list type!");
527 Record *Property = DI->getDef();
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() == "IntrWriteArgMem")
538 ModRef = WriteArgMem;
539 else if (Property->getName() == "IntrWriteMem")
542 assert(0 && "Unknown property!");