1 //===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
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 tablegen backend is responsible for emitting a description of the target
11 // instruction set for the code generator.
13 //===----------------------------------------------------------------------===//
16 #include "CodeGenDAGPatterns.h"
17 #include "CodeGenSchedule.h"
18 #include "CodeGenTarget.h"
19 #include "SequenceToOffsetTable.h"
20 #include "TableGenBackends.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/TableGen/Error.h"
23 #include "llvm/TableGen/Record.h"
24 #include "llvm/TableGen/TableGenBackend.h"
32 class InstrInfoEmitter {
33 RecordKeeper &Records;
34 CodeGenDAGPatterns CDP;
35 const CodeGenSchedModels &SchedModels;
38 InstrInfoEmitter(RecordKeeper &R):
39 Records(R), CDP(R), SchedModels(CDP.getTargetInfo().getSchedModels()) {}
41 // run - Output the instruction set description.
42 void run(raw_ostream &OS);
45 void emitEnums(raw_ostream &OS);
47 typedef std::map<std::vector<std::string>, unsigned> OperandInfoMapTy;
49 /// The keys of this map are maps which have OpName enum values as their keys
50 /// and instruction operand indices as their values. The values of this map
51 /// are lists of instruction names.
52 typedef std::map<std::map<unsigned, unsigned>,
53 std::vector<std::string> > OpNameMapTy;
54 typedef std::map<std::string, unsigned>::iterator StrUintMapIter;
55 void emitRecord(const CodeGenInstruction &Inst, unsigned Num,
57 std::map<std::vector<Record*>, unsigned> &EL,
58 const OperandInfoMapTy &OpInfo,
60 void initOperandMapData(
61 const std::vector<const CodeGenInstruction *> NumberedInstructions,
62 const std::string &Namespace,
63 std::map<std::string, unsigned> &Operands,
64 OpNameMapTy &OperandMap);
65 void emitOperandNameMappings(raw_ostream &OS, const CodeGenTarget &Target,
66 const std::vector<const CodeGenInstruction*> &NumberedInstructions);
68 // Operand information.
69 void EmitOperandInfo(raw_ostream &OS, OperandInfoMapTy &OperandInfoIDs);
70 std::vector<std::string> GetOperandInfo(const CodeGenInstruction &Inst);
72 } // End anonymous namespace
74 static void PrintDefList(const std::vector<Record*> &Uses,
75 unsigned Num, raw_ostream &OS) {
76 OS << "static const uint16_t ImplicitList" << Num << "[] = { ";
77 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
78 OS << getQualifiedName(Uses[i]) << ", ";
82 //===----------------------------------------------------------------------===//
83 // Operand Info Emission.
84 //===----------------------------------------------------------------------===//
86 std::vector<std::string>
87 InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
88 std::vector<std::string> Result;
90 for (unsigned i = 0, e = Inst.Operands.size(); i != e; ++i) {
91 // Handle aggregate operands and normal operands the same way by expanding
92 // either case into a list of operands for this op.
93 std::vector<CGIOperandList::OperandInfo> OperandList;
95 // This might be a multiple operand thing. Targets like X86 have
96 // registers in their multi-operand operands. It may also be an anonymous
97 // operand, which has a single operand, but no declared class for the
99 DagInit *MIOI = Inst.Operands[i].MIOperandInfo;
101 if (!MIOI || MIOI->getNumArgs() == 0) {
102 // Single, anonymous, operand.
103 OperandList.push_back(Inst.Operands[i]);
105 for (unsigned j = 0, e = Inst.Operands[i].MINumOperands; j != e; ++j) {
106 OperandList.push_back(Inst.Operands[i]);
108 Record *OpR = cast<DefInit>(MIOI->getArg(j))->getDef();
109 OperandList.back().Rec = OpR;
113 for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
114 Record *OpR = OperandList[j].Rec;
117 if (OpR->isSubClassOf("RegisterOperand"))
118 OpR = OpR->getValueAsDef("RegClass");
119 if (OpR->isSubClassOf("RegisterClass"))
120 Res += getQualifiedName(OpR) + "RegClassID, ";
121 else if (OpR->isSubClassOf("PointerLikeRegClass"))
122 Res += utostr(OpR->getValueAsInt("RegClassKind")) + ", ";
124 // -1 means the operand does not have a fixed register class.
127 // Fill in applicable flags.
130 // Ptr value whose register class is resolved via callback.
131 if (OpR->isSubClassOf("PointerLikeRegClass"))
132 Res += "|(1<<MCOI::LookupPtrRegClass)";
134 // Predicate operands. Check to see if the original unexpanded operand
135 // was of type PredicateOp.
136 if (Inst.Operands[i].Rec->isSubClassOf("PredicateOp"))
137 Res += "|(1<<MCOI::Predicate)";
139 // Optional def operands. Check to see if the original unexpanded operand
140 // was of type OptionalDefOperand.
141 if (Inst.Operands[i].Rec->isSubClassOf("OptionalDefOperand"))
142 Res += "|(1<<MCOI::OptionalDef)";
144 // Fill in operand type.
146 assert(!Inst.Operands[i].OperandType.empty() && "Invalid operand type.");
147 Res += Inst.Operands[i].OperandType;
149 // Fill in constraint info.
152 const CGIOperandList::ConstraintInfo &Constraint =
153 Inst.Operands[i].Constraints[j];
154 if (Constraint.isNone())
156 else if (Constraint.isEarlyClobber())
157 Res += "(1 << MCOI::EARLY_CLOBBER)";
159 assert(Constraint.isTied());
160 Res += "((" + utostr(Constraint.getTiedOperand()) +
161 " << 16) | (1 << MCOI::TIED_TO))";
164 Result.push_back(Res);
171 void InstrInfoEmitter::EmitOperandInfo(raw_ostream &OS,
172 OperandInfoMapTy &OperandInfoIDs) {
173 // ID #0 is for no operand info.
174 unsigned OperandListNum = 0;
175 OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
178 const CodeGenTarget &Target = CDP.getTargetInfo();
179 for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
180 E = Target.inst_end(); II != E; ++II) {
181 std::vector<std::string> OperandInfo = GetOperandInfo(**II);
182 unsigned &N = OperandInfoIDs[OperandInfo];
183 if (N != 0) continue;
185 N = ++OperandListNum;
186 OS << "static const MCOperandInfo OperandInfo" << N << "[] = { ";
187 for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
188 OS << "{ " << OperandInfo[i] << " }, ";
194 /// Initialize data structures for generating operand name mappings.
196 /// \param Operands [out] A map used to generate the OpName enum with operand
197 /// names as its keys and operand enum values as its values.
198 /// \param OperandMap [out] A map for representing the operand name mappings for
199 /// each instructions. This is used to generate the OperandMap table as
200 /// well as the getNamedOperandIdx() function.
201 void InstrInfoEmitter::initOperandMapData(
202 const std::vector<const CodeGenInstruction *> NumberedInstructions,
203 const std::string &Namespace,
204 std::map<std::string, unsigned> &Operands,
205 OpNameMapTy &OperandMap) {
207 unsigned NumOperands = 0;
208 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
209 const CodeGenInstruction *Inst = NumberedInstructions[i];
210 if (!Inst->TheDef->getValueAsBit("UseNamedOperandTable")) {
213 std::map<unsigned, unsigned> OpList;
214 for (unsigned j = 0, je = Inst->Operands.size(); j != je; ++j) {
215 const CGIOperandList::OperandInfo &Info = Inst->Operands[j];
216 StrUintMapIter I = Operands.find(Info.Name);
218 if (I == Operands.end()) {
219 I = Operands.insert(Operands.begin(),
220 std::pair<std::string, unsigned>(Info.Name, NumOperands++));
222 OpList[I->second] = Info.MIOperandNo;
224 OperandMap[OpList].push_back(Namespace + "::" + Inst->TheDef->getName());
228 /// Generate a table and function for looking up the indices of operands by
231 /// This code generates:
232 /// - An enum in the llvm::TargetNamespace::OpName namespace, with one entry
233 /// for each operand name.
234 /// - A 2-dimensional table called OperandMap for mapping OpName enum values to
236 /// - A function called getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx)
237 /// for looking up the operand index for an instruction, given a value from
239 void InstrInfoEmitter::emitOperandNameMappings(raw_ostream &OS,
240 const CodeGenTarget &Target,
241 const std::vector<const CodeGenInstruction*> &NumberedInstructions) {
243 const std::string &Namespace = Target.getInstNamespace();
244 std::string OpNameNS = "OpName";
245 // Map of operand names to their enumeration value. This will be used to
246 // generate the OpName enum.
247 std::map<std::string, unsigned> Operands;
248 OpNameMapTy OperandMap;
250 initOperandMapData(NumberedInstructions, Namespace, Operands, OperandMap);
252 OS << "#ifdef GET_INSTRINFO_OPERAND_ENUM\n";
253 OS << "#undef GET_INSTRINFO_OPERAND_ENUM\n";
254 OS << "namespace llvm {";
255 OS << "namespace " << Namespace << " {\n";
256 OS << "namespace " << OpNameNS << " { \n";
258 for (StrUintMapIter i = Operands.begin(), e = Operands.end(); i != e; ++i)
259 OS << " " << i->first << " = " << i->second << ",\n";
261 OS << "OPERAND_LAST";
263 OS << "} // End namespace OpName\n";
264 OS << "} // End namespace " << Namespace << "\n";
265 OS << "} // End namespace llvm\n";
266 OS << "#endif //GET_INSTRINFO_OPERAND_ENUM\n";
268 OS << "#ifdef GET_INSTRINFO_NAMED_OPS\n";
269 OS << "#undef GET_INSTRINFO_NAMED_OPS\n";
270 OS << "namespace llvm {";
271 OS << "namespace " << Namespace << " {\n";
272 OS << "int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx) {\n";
273 if (!Operands.empty()) {
274 OS << " static const int16_t OperandMap [][" << Operands.size()
276 for (OpNameMapTy::iterator i = OperandMap.begin(), e = OperandMap.end();
278 const std::map<unsigned, unsigned> &OpList = i->first;
281 // Emit a row of the OperandMap table
282 for (unsigned ii = 0, ie = Operands.size(); ii != ie; ++ii)
283 OS << (OpList.count(ii) == 0 ? -1 : (int)OpList.find(ii)->second)
290 OS << " switch(Opcode) {\n";
291 unsigned TableIndex = 0;
292 for (OpNameMapTy::iterator i = OperandMap.begin(), e = OperandMap.end();
294 std::vector<std::string> &OpcodeList = i->second;
296 for (unsigned ii = 0, ie = OpcodeList.size(); ii != ie; ++ii)
297 OS << " case " << OpcodeList[ii] << ":\n";
299 OS << " return OperandMap[" << TableIndex++ << "][NamedIdx];\n";
301 OS << " default: return -1;\n";
304 // There are no operands, so no need to emit anything
305 OS << " return -1;\n";
308 OS << "} // End namespace " << Namespace << "\n";
309 OS << "} // End namespace llvm\n";
310 OS << "#endif //GET_INSTRINFO_NAMED_OPS\n";
314 //===----------------------------------------------------------------------===//
316 //===----------------------------------------------------------------------===//
318 // run - Emit the main instruction description records for the target...
319 void InstrInfoEmitter::run(raw_ostream &OS) {
320 emitSourceFileHeader("Target Instruction Enum Values", OS);
323 emitSourceFileHeader("Target Instruction Descriptors", OS);
325 OS << "\n#ifdef GET_INSTRINFO_MC_DESC\n";
326 OS << "#undef GET_INSTRINFO_MC_DESC\n";
328 OS << "namespace llvm {\n\n";
330 CodeGenTarget &Target = CDP.getTargetInfo();
331 const std::string &TargetName = Target.getName();
332 Record *InstrInfo = Target.getInstructionSet();
334 // Keep track of all of the def lists we have emitted already.
335 std::map<std::vector<Record*>, unsigned> EmittedLists;
336 unsigned ListNumber = 0;
338 // Emit all of the instruction's implicit uses and defs.
339 for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
340 E = Target.inst_end(); II != E; ++II) {
341 Record *Inst = (*II)->TheDef;
342 std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
344 unsigned &IL = EmittedLists[Uses];
345 if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
347 std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
349 unsigned &IL = EmittedLists[Defs];
350 if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
354 OperandInfoMapTy OperandInfoIDs;
356 // Emit all of the operand info records.
357 EmitOperandInfo(OS, OperandInfoIDs);
359 // Emit all of the MCInstrDesc records in their ENUM ordering.
361 OS << "\nextern const MCInstrDesc " << TargetName << "Insts[] = {\n";
362 const std::vector<const CodeGenInstruction*> &NumberedInstructions =
363 Target.getInstructionsByEnumValue();
365 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
366 emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
370 // Build an array of instruction names
371 SequenceToOffsetTable<std::string> InstrNames;
372 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
373 const CodeGenInstruction *Instr = NumberedInstructions[i];
374 InstrNames.add(Instr->TheDef->getName());
378 OS << "extern const char " << TargetName << "InstrNameData[] = {\n";
379 InstrNames.emit(OS, printChar);
382 OS << "extern const unsigned " << TargetName <<"InstrNameIndices[] = {";
383 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
386 const CodeGenInstruction *Instr = NumberedInstructions[i];
387 OS << InstrNames.get(Instr->TheDef->getName()) << "U, ";
392 // MCInstrInfo initialization routine.
393 OS << "static inline void Init" << TargetName
394 << "MCInstrInfo(MCInstrInfo *II) {\n";
395 OS << " II->InitMCInstrInfo(" << TargetName << "Insts, "
396 << TargetName << "InstrNameIndices, " << TargetName << "InstrNameData, "
397 << NumberedInstructions.size() << ");\n}\n\n";
399 OS << "} // End llvm namespace \n";
401 OS << "#endif // GET_INSTRINFO_MC_DESC\n\n";
403 // Create a TargetInstrInfo subclass to hide the MC layer initialization.
404 OS << "\n#ifdef GET_INSTRINFO_HEADER\n";
405 OS << "#undef GET_INSTRINFO_HEADER\n";
407 std::string ClassName = TargetName + "GenInstrInfo";
408 OS << "namespace llvm {\n";
409 OS << "struct " << ClassName << " : public TargetInstrInfo {\n"
410 << " explicit " << ClassName << "(int SO = -1, int DO = -1);\n"
412 OS << "} // End llvm namespace \n";
414 OS << "#endif // GET_INSTRINFO_HEADER\n\n";
416 OS << "\n#ifdef GET_INSTRINFO_CTOR\n";
417 OS << "#undef GET_INSTRINFO_CTOR\n";
419 OS << "namespace llvm {\n";
420 OS << "extern const MCInstrDesc " << TargetName << "Insts[];\n";
421 OS << "extern const unsigned " << TargetName << "InstrNameIndices[];\n";
422 OS << "extern const char " << TargetName << "InstrNameData[];\n";
423 OS << ClassName << "::" << ClassName << "(int SO, int DO)\n"
424 << " : TargetInstrInfo(SO, DO) {\n"
425 << " InitMCInstrInfo(" << TargetName << "Insts, "
426 << TargetName << "InstrNameIndices, " << TargetName << "InstrNameData, "
427 << NumberedInstructions.size() << ");\n}\n";
428 OS << "} // End llvm namespace \n";
430 OS << "#endif // GET_INSTRINFO_CTOR\n\n";
432 emitOperandNameMappings(OS, Target, NumberedInstructions);
435 void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
437 std::map<std::vector<Record*>, unsigned> &EmittedLists,
438 const OperandInfoMapTy &OpInfo,
441 if (!Inst.Operands.empty())
442 // Each logical operand can be multiple MI operands.
443 MinOperands = Inst.Operands.back().MIOperandNo +
444 Inst.Operands.back().MINumOperands;
447 OS << Num << ",\t" << MinOperands << ",\t"
448 << Inst.Operands.NumDefs << ",\t"
449 << SchedModels.getSchedClassIdx(Inst) << ",\t"
450 << Inst.TheDef->getValueAsInt("Size") << ",\t0";
452 // Emit all of the target indepedent flags...
453 if (Inst.isPseudo) OS << "|(1<<MCID::Pseudo)";
454 if (Inst.isReturn) OS << "|(1<<MCID::Return)";
455 if (Inst.isBranch) OS << "|(1<<MCID::Branch)";
456 if (Inst.isIndirectBranch) OS << "|(1<<MCID::IndirectBranch)";
457 if (Inst.isCompare) OS << "|(1<<MCID::Compare)";
458 if (Inst.isMoveImm) OS << "|(1<<MCID::MoveImm)";
459 if (Inst.isBitcast) OS << "|(1<<MCID::Bitcast)";
460 if (Inst.isSelect) OS << "|(1<<MCID::Select)";
461 if (Inst.isBarrier) OS << "|(1<<MCID::Barrier)";
462 if (Inst.hasDelaySlot) OS << "|(1<<MCID::DelaySlot)";
463 if (Inst.isCall) OS << "|(1<<MCID::Call)";
464 if (Inst.canFoldAsLoad) OS << "|(1<<MCID::FoldableAsLoad)";
465 if (Inst.mayLoad) OS << "|(1<<MCID::MayLoad)";
466 if (Inst.mayStore) OS << "|(1<<MCID::MayStore)";
467 if (Inst.isPredicable) OS << "|(1<<MCID::Predicable)";
468 if (Inst.isConvertibleToThreeAddress) OS << "|(1<<MCID::ConvertibleTo3Addr)";
469 if (Inst.isCommutable) OS << "|(1<<MCID::Commutable)";
470 if (Inst.isTerminator) OS << "|(1<<MCID::Terminator)";
471 if (Inst.isReMaterializable) OS << "|(1<<MCID::Rematerializable)";
472 if (Inst.isNotDuplicable) OS << "|(1<<MCID::NotDuplicable)";
473 if (Inst.Operands.hasOptionalDef) OS << "|(1<<MCID::HasOptionalDef)";
474 if (Inst.usesCustomInserter) OS << "|(1<<MCID::UsesCustomInserter)";
475 if (Inst.hasPostISelHook) OS << "|(1<<MCID::HasPostISelHook)";
476 if (Inst.Operands.isVariadic)OS << "|(1<<MCID::Variadic)";
477 if (Inst.hasSideEffects) OS << "|(1<<MCID::UnmodeledSideEffects)";
478 if (Inst.isAsCheapAsAMove) OS << "|(1<<MCID::CheapAsAMove)";
479 if (Inst.hasExtraSrcRegAllocReq) OS << "|(1<<MCID::ExtraSrcRegAllocReq)";
480 if (Inst.hasExtraDefRegAllocReq) OS << "|(1<<MCID::ExtraDefRegAllocReq)";
482 // Emit all of the target-specific flags...
483 BitsInit *TSF = Inst.TheDef->getValueAsBitsInit("TSFlags");
485 PrintFatalError("no TSFlags?");
487 for (unsigned i = 0, e = TSF->getNumBits(); i != e; ++i) {
488 if (BitInit *Bit = dyn_cast<BitInit>(TSF->getBit(i)))
489 Value |= uint64_t(Bit->getValue()) << i;
491 PrintFatalError("Invalid TSFlags bit in " + Inst.TheDef->getName());
497 // Emit the implicit uses and defs lists...
498 std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
502 OS << "ImplicitList" << EmittedLists[UseList] << ", ";
504 std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
508 OS << "ImplicitList" << EmittedLists[DefList] << ", ";
510 // Emit the operand info.
511 std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
512 if (OperandInfo.empty())
515 OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
517 CodeGenTarget &Target = CDP.getTargetInfo();
518 if (Inst.HasComplexDeprecationPredicate)
519 // Emit a function pointer to the complex predicate method.
521 << ",&get" << Inst.DeprecatedReason << "DeprecationInfo";
522 else if (!Inst.DeprecatedReason.empty())
523 // Emit the Subtarget feature.
524 OS << "," << Target.getInstNamespace() << "::" << Inst.DeprecatedReason
527 // Instruction isn't deprecated.
530 OS << " }, // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
533 // emitEnums - Print out enum values for all of the instructions.
534 void InstrInfoEmitter::emitEnums(raw_ostream &OS) {
536 OS << "\n#ifdef GET_INSTRINFO_ENUM\n";
537 OS << "#undef GET_INSTRINFO_ENUM\n";
539 OS << "namespace llvm {\n\n";
541 CodeGenTarget Target(Records);
543 // We must emit the PHI opcode first...
544 std::string Namespace = Target.getInstNamespace();
546 if (Namespace.empty()) {
547 fprintf(stderr, "No instructions defined!\n");
551 const std::vector<const CodeGenInstruction*> &NumberedInstructions =
552 Target.getInstructionsByEnumValue();
554 OS << "namespace " << Namespace << " {\n";
556 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
557 OS << " " << NumberedInstructions[i]->TheDef->getName()
558 << "\t= " << i << ",\n";
560 OS << " INSTRUCTION_LIST_END = " << NumberedInstructions.size() << "\n";
562 OS << "namespace Sched {\n";
564 for (unsigned i = 0, e = SchedModels.numInstrSchedClasses(); i != e; ++i) {
565 OS << " " << SchedModels.getSchedClass(i).Name
566 << "\t= " << i << ",\n";
568 OS << " SCHED_LIST_END = " << SchedModels.numInstrSchedClasses() << "\n";
570 OS << "} // End llvm namespace \n";
572 OS << "#endif // GET_INSTRINFO_ENUM\n\n";
577 void EmitInstrInfo(RecordKeeper &RK, raw_ostream &OS) {
578 InstrInfoEmitter(RK).run(OS);
579 EmitMapTable(RK, OS);
582 } // End llvm namespace