1 //===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. --*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This tablegen backend is responsible for emitting a description of the target
10 // instruction set for the code generator.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenDAGPatterns.h"
15 #include "CodeGenInstruction.h"
16 #include "CodeGenSchedule.h"
17 #include "CodeGenTarget.h"
18 #include "PredicateExpander.h"
19 #include "SequenceToOffsetTable.h"
20 #include "TableGenBackends.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/Support/Casting.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/TableGen/Error.h"
26 #include "llvm/TableGen/Record.h"
27 #include "llvm/TableGen/TableGenBackend.h"
28 #include <cassert>
29 #include <cstdint>
30 #include <map>
31 #include <string>
32 #include <utility>
33 #include <vector>
34 
35 using namespace llvm;
36 
37 namespace {
38 
39 class InstrInfoEmitter {
40   RecordKeeper &Records;
41   CodeGenDAGPatterns CDP;
42   const CodeGenSchedModels &SchedModels;
43 
44 public:
45   InstrInfoEmitter(RecordKeeper &R):
46     Records(R), CDP(R), SchedModels(CDP.getTargetInfo().getSchedModels()) {}
47 
48   // run - Output the instruction set description.
49   void run(raw_ostream &OS);
50 
51 private:
52   void emitEnums(raw_ostream &OS);
53 
54   typedef std::map<std::vector<std::string>, unsigned> OperandInfoMapTy;
55 
56   /// The keys of this map are maps which have OpName enum values as their keys
57   /// and instruction operand indices as their values.  The values of this map
58   /// are lists of instruction names.
59   typedef std::map<std::map<unsigned, unsigned>,
60                    std::vector<std::string>> OpNameMapTy;
61   typedef std::map<std::string, unsigned>::iterator StrUintMapIter;
62 
63   /// Generate member functions in the target-specific GenInstrInfo class.
64   ///
65   /// This method is used to custom expand TIIPredicate definitions.
66   /// See file llvm/Target/TargetInstPredicates.td for a description of what is
67   /// a TIIPredicate and how to use it.
68   void emitTIIHelperMethods(raw_ostream &OS, StringRef TargetName,
69                             bool ExpandDefinition = true);
70 
71   /// Expand TIIPredicate definitions to functions that accept a const MCInst
72   /// reference.
73   void emitMCIIHelperMethods(raw_ostream &OS, StringRef TargetName);
74   void emitRecord(const CodeGenInstruction &Inst, unsigned Num,
75                   Record *InstrInfo,
76                   std::map<std::vector<Record*>, unsigned> &EL,
77                   const OperandInfoMapTy &OpInfo,
78                   raw_ostream &OS);
79   void emitOperandTypeMappings(
80       raw_ostream &OS, const CodeGenTarget &Target,
81       ArrayRef<const CodeGenInstruction *> NumberedInstructions);
82   void initOperandMapData(
83             ArrayRef<const CodeGenInstruction *> NumberedInstructions,
84             StringRef Namespace,
85             std::map<std::string, unsigned> &Operands,
86             OpNameMapTy &OperandMap);
87   void emitOperandNameMappings(raw_ostream &OS, const CodeGenTarget &Target,
88             ArrayRef<const CodeGenInstruction*> NumberedInstructions);
89 
90   // Operand information.
91   void EmitOperandInfo(raw_ostream &OS, OperandInfoMapTy &OperandInfoIDs);
92   std::vector<std::string> GetOperandInfo(const CodeGenInstruction &Inst);
93 };
94 
95 } // end anonymous namespace
96 
97 static void PrintDefList(const std::vector<Record*> &Uses,
98                          unsigned Num, raw_ostream &OS) {
99   OS << "static const MCPhysReg ImplicitList" << Num << "[] = { ";
100   for (Record *U : Uses)
101     OS << getQualifiedName(U) << ", ";
102   OS << "0 };\n";
103 }
104 
105 //===----------------------------------------------------------------------===//
106 // Operand Info Emission.
107 //===----------------------------------------------------------------------===//
108 
109 std::vector<std::string>
110 InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
111   std::vector<std::string> Result;
112 
113   for (auto &Op : Inst.Operands) {
114     // Handle aggregate operands and normal operands the same way by expanding
115     // either case into a list of operands for this op.
116     std::vector<CGIOperandList::OperandInfo> OperandList;
117 
118     // This might be a multiple operand thing.  Targets like X86 have
119     // registers in their multi-operand operands.  It may also be an anonymous
120     // operand, which has a single operand, but no declared class for the
121     // operand.
122     DagInit *MIOI = Op.MIOperandInfo;
123 
124     if (!MIOI || MIOI->getNumArgs() == 0) {
125       // Single, anonymous, operand.
126       OperandList.push_back(Op);
127     } else {
128       for (unsigned j = 0, e = Op.MINumOperands; j != e; ++j) {
129         OperandList.push_back(Op);
130 
131         auto *OpR = cast<DefInit>(MIOI->getArg(j))->getDef();
132         OperandList.back().Rec = OpR;
133       }
134     }
135 
136     for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
137       Record *OpR = OperandList[j].Rec;
138       std::string Res;
139 
140       if (OpR->isSubClassOf("RegisterOperand"))
141         OpR = OpR->getValueAsDef("RegClass");
142       if (OpR->isSubClassOf("RegisterClass"))
143         Res += getQualifiedName(OpR) + "RegClassID, ";
144       else if (OpR->isSubClassOf("PointerLikeRegClass"))
145         Res += utostr(OpR->getValueAsInt("RegClassKind")) + ", ";
146       else
147         // -1 means the operand does not have a fixed register class.
148         Res += "-1, ";
149 
150       // Fill in applicable flags.
151       Res += "0";
152 
153       // Ptr value whose register class is resolved via callback.
154       if (OpR->isSubClassOf("PointerLikeRegClass"))
155         Res += "|(1<<MCOI::LookupPtrRegClass)";
156 
157       // Predicate operands.  Check to see if the original unexpanded operand
158       // was of type PredicateOp.
159       if (Op.Rec->isSubClassOf("PredicateOp"))
160         Res += "|(1<<MCOI::Predicate)";
161 
162       // Optional def operands.  Check to see if the original unexpanded operand
163       // was of type OptionalDefOperand.
164       if (Op.Rec->isSubClassOf("OptionalDefOperand"))
165         Res += "|(1<<MCOI::OptionalDef)";
166 
167       // Branch target operands.  Check to see if the original unexpanded
168       // operand was of type BranchTargetOperand.
169       if (Op.Rec->isSubClassOf("BranchTargetOperand"))
170         Res += "|(1<<MCOI::BranchTarget)";
171 
172       // Fill in operand type.
173       Res += ", ";
174       assert(!Op.OperandType.empty() && "Invalid operand type.");
175       Res += Op.OperandType;
176 
177       // Fill in constraint info.
178       Res += ", ";
179 
180       const CGIOperandList::ConstraintInfo &Constraint =
181         Op.Constraints[j];
182       if (Constraint.isNone())
183         Res += "0";
184       else if (Constraint.isEarlyClobber())
185         Res += "(1 << MCOI::EARLY_CLOBBER)";
186       else {
187         assert(Constraint.isTied());
188         Res += "((" + utostr(Constraint.getTiedOperand()) +
189                     " << 16) | (1 << MCOI::TIED_TO))";
190       }
191 
192       Result.push_back(Res);
193     }
194   }
195 
196   return Result;
197 }
198 
199 void InstrInfoEmitter::EmitOperandInfo(raw_ostream &OS,
200                                        OperandInfoMapTy &OperandInfoIDs) {
201   // ID #0 is for no operand info.
202   unsigned OperandListNum = 0;
203   OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
204 
205   OS << "\n";
206   const CodeGenTarget &Target = CDP.getTargetInfo();
207   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
208     std::vector<std::string> OperandInfo = GetOperandInfo(*Inst);
209     unsigned &N = OperandInfoIDs[OperandInfo];
210     if (N != 0) continue;
211 
212     N = ++OperandListNum;
213     OS << "static const MCOperandInfo OperandInfo" << N << "[] = { ";
214     for (const std::string &Info : OperandInfo)
215       OS << "{ " << Info << " }, ";
216     OS << "};\n";
217   }
218 }
219 
220 /// Initialize data structures for generating operand name mappings.
221 ///
222 /// \param Operands [out] A map used to generate the OpName enum with operand
223 ///        names as its keys and operand enum values as its values.
224 /// \param OperandMap [out] A map for representing the operand name mappings for
225 ///        each instructions.  This is used to generate the OperandMap table as
226 ///        well as the getNamedOperandIdx() function.
227 void InstrInfoEmitter::initOperandMapData(
228         ArrayRef<const CodeGenInstruction *> NumberedInstructions,
229         StringRef Namespace,
230         std::map<std::string, unsigned> &Operands,
231         OpNameMapTy &OperandMap) {
232   unsigned NumOperands = 0;
233   for (const CodeGenInstruction *Inst : NumberedInstructions) {
234     if (!Inst->TheDef->getValueAsBit("UseNamedOperandTable"))
235       continue;
236     std::map<unsigned, unsigned> OpList;
237     for (const auto &Info : Inst->Operands) {
238       StrUintMapIter I = Operands.find(Info.Name);
239 
240       if (I == Operands.end()) {
241         I = Operands.insert(Operands.begin(),
242                     std::pair<std::string, unsigned>(Info.Name, NumOperands++));
243       }
244       OpList[I->second] = Info.MIOperandNo;
245     }
246     OperandMap[OpList].push_back(Namespace.str() + "::" +
247                                  Inst->TheDef->getName().str());
248   }
249 }
250 
251 /// Generate a table and function for looking up the indices of operands by
252 /// name.
253 ///
254 /// This code generates:
255 /// - An enum in the llvm::TargetNamespace::OpName namespace, with one entry
256 ///   for each operand name.
257 /// - A 2-dimensional table called OperandMap for mapping OpName enum values to
258 ///   operand indices.
259 /// - A function called getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx)
260 ///   for looking up the operand index for an instruction, given a value from
261 ///   OpName enum
262 void InstrInfoEmitter::emitOperandNameMappings(raw_ostream &OS,
263            const CodeGenTarget &Target,
264            ArrayRef<const CodeGenInstruction*> NumberedInstructions) {
265   StringRef Namespace = Target.getInstNamespace();
266   std::string OpNameNS = "OpName";
267   // Map of operand names to their enumeration value.  This will be used to
268   // generate the OpName enum.
269   std::map<std::string, unsigned> Operands;
270   OpNameMapTy OperandMap;
271 
272   initOperandMapData(NumberedInstructions, Namespace, Operands, OperandMap);
273 
274   OS << "#ifdef GET_INSTRINFO_OPERAND_ENUM\n";
275   OS << "#undef GET_INSTRINFO_OPERAND_ENUM\n";
276   OS << "namespace llvm {\n";
277   OS << "namespace " << Namespace << " {\n";
278   OS << "namespace " << OpNameNS << " {\n";
279   OS << "enum {\n";
280   for (const auto &Op : Operands)
281     OS << "  " << Op.first << " = " << Op.second << ",\n";
282 
283   OS << "  OPERAND_LAST";
284   OS << "\n};\n";
285   OS << "} // end namespace OpName\n";
286   OS << "} // end namespace " << Namespace << "\n";
287   OS << "} // end namespace llvm\n";
288   OS << "#endif //GET_INSTRINFO_OPERAND_ENUM\n\n";
289 
290   OS << "#ifdef GET_INSTRINFO_NAMED_OPS\n";
291   OS << "#undef GET_INSTRINFO_NAMED_OPS\n";
292   OS << "namespace llvm {\n";
293   OS << "namespace " << Namespace << " {\n";
294   OS << "LLVM_READONLY\n";
295   OS << "int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx) {\n";
296   if (!Operands.empty()) {
297     OS << "  static const int16_t OperandMap [][" << Operands.size()
298        << "] = {\n";
299     for (const auto &Entry : OperandMap) {
300       const std::map<unsigned, unsigned> &OpList = Entry.first;
301       OS << "{";
302 
303       // Emit a row of the OperandMap table
304       for (unsigned i = 0, e = Operands.size(); i != e; ++i)
305         OS << (OpList.count(i) == 0 ? -1 : (int)OpList.find(i)->second) << ", ";
306 
307       OS << "},\n";
308     }
309     OS << "};\n";
310 
311     OS << "  switch(Opcode) {\n";
312     unsigned TableIndex = 0;
313     for (const auto &Entry : OperandMap) {
314       for (const std::string &Name : Entry.second)
315         OS << "  case " << Name << ":\n";
316 
317       OS << "    return OperandMap[" << TableIndex++ << "][NamedIdx];\n";
318     }
319     OS << "  default: return -1;\n";
320     OS << "  }\n";
321   } else {
322     // There are no operands, so no need to emit anything
323     OS << "  return -1;\n";
324   }
325   OS << "}\n";
326   OS << "} // end namespace " << Namespace << "\n";
327   OS << "} // end namespace llvm\n";
328   OS << "#endif //GET_INSTRINFO_NAMED_OPS\n\n";
329 }
330 
331 /// Generate an enum for all the operand types for this target, under the
332 /// llvm::TargetNamespace::OpTypes namespace.
333 /// Operand types are all definitions derived of the Operand Target.td class.
334 void InstrInfoEmitter::emitOperandTypeMappings(
335     raw_ostream &OS, const CodeGenTarget &Target,
336     ArrayRef<const CodeGenInstruction *> NumberedInstructions) {
337 
338   StringRef Namespace = Target.getInstNamespace();
339   std::vector<Record *> Operands = Records.getAllDerivedDefinitions("Operand");
340   std::vector<Record *> RegisterOperands =
341       Records.getAllDerivedDefinitions("RegisterOperand");
342   std::vector<Record *> RegisterClasses =
343       Records.getAllDerivedDefinitions("RegisterClass");
344 
345   OS << "#ifdef GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
346   OS << "#undef GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
347   OS << "namespace llvm {\n";
348   OS << "namespace " << Namespace << " {\n";
349   OS << "namespace OpTypes {\n";
350   OS << "enum OperandType {\n";
351 
352   unsigned EnumVal = 0;
353   for (const std::vector<Record *> *RecordsToAdd :
354        {&Operands, &RegisterOperands, &RegisterClasses}) {
355     for (const Record *Op : *RecordsToAdd) {
356       if (!Op->isAnonymous())
357         OS << "  " << Op->getName() << " = " << EnumVal << ",\n";
358       ++EnumVal;
359     }
360   }
361 
362   OS << "  OPERAND_TYPE_LIST_END" << "\n};\n";
363   OS << "} // end namespace OpTypes\n";
364   OS << "} // end namespace " << Namespace << "\n";
365   OS << "} // end namespace llvm\n";
366   OS << "#endif // GET_INSTRINFO_OPERAND_TYPES_ENUM\n\n";
367 
368   OS << "#ifdef GET_INSTRINFO_OPERAND_TYPE\n";
369   OS << "#undef GET_INSTRINFO_OPERAND_TYPE\n";
370   OS << "namespace llvm {\n";
371   OS << "namespace " << Namespace << " {\n";
372   OS << "LLVM_READONLY\n";
373   OS << "static int getOperandType(uint16_t Opcode, uint16_t OpIdx) {\n";
374   // TODO: Factor out duplicate operand lists to compress the tables.
375   if (!NumberedInstructions.empty()) {
376     std::vector<int> OperandOffsets;
377     std::vector<Record *> OperandRecords;
378     int CurrentOffset = 0;
379     for (const CodeGenInstruction *Inst : NumberedInstructions) {
380       OperandOffsets.push_back(CurrentOffset);
381       for (const auto &Op : Inst->Operands) {
382         const DagInit *MIOI = Op.MIOperandInfo;
383         if (!MIOI || MIOI->getNumArgs() == 0) {
384           // Single, anonymous, operand.
385           OperandRecords.push_back(Op.Rec);
386           ++CurrentOffset;
387         } else {
388           for (Init *Arg : make_range(MIOI->arg_begin(), MIOI->arg_end())) {
389             OperandRecords.push_back(cast<DefInit>(Arg)->getDef());
390             ++CurrentOffset;
391           }
392         }
393       }
394     }
395 
396     // Emit the table of offsets (indexes) into the operand type table.
397     // Size the unsigned integer offset to save space.
398     assert(OperandRecords.size() <= UINT32_MAX &&
399            "Too many operands for offset table");
400     OS << ((OperandRecords.size() <= UINT16_MAX) ? "  const uint16_t"
401                                                  : "  const uint32_t");
402     OS << " Offsets[] = {\n";
403     for (int I = 0, E = OperandOffsets.size(); I != E; ++I)
404       OS << "    " << OperandOffsets[I] << ",\n";
405     OS << "  };\n";
406 
407     // Add an entry for the end so that we don't need to special case it below.
408     OperandOffsets.push_back(OperandRecords.size());
409 
410     // Emit the actual operand types in a flat table.
411     // Size the signed integer operand type to save space.
412     assert(EnumVal <= INT16_MAX &&
413            "Too many operand types for operand types table");
414     OS << ((EnumVal <= INT8_MAX) ? "  const int8_t" : "  const int16_t");
415     OS << " OpcodeOperandTypes[] = {\n    ";
416     for (int I = 0, E = OperandRecords.size(), CurOffset = 1; I != E; ++I) {
417       // We print each Opcode's operands in its own row.
418       if (I == OperandOffsets[CurOffset]) {
419         OS << "\n    ";
420         // If there are empty rows, mark them with an empty comment.
421         while (OperandOffsets[++CurOffset] == I)
422           OS << "/**/\n    ";
423       }
424       Record *OpR = OperandRecords[I];
425       if ((OpR->isSubClassOf("Operand") ||
426            OpR->isSubClassOf("RegisterOperand") ||
427            OpR->isSubClassOf("RegisterClass")) &&
428           !OpR->isAnonymous())
429         OS << "OpTypes::" << OpR->getName();
430       else
431         OS << -1;
432       OS << ", ";
433     }
434     OS << "\n  };\n";
435 
436     OS << "  return OpcodeOperandTypes[Offsets[Opcode] + OpIdx];\n";
437   } else {
438     OS << "  llvm_unreachable(\"No instructions defined\");\n";
439   }
440   OS << "}\n";
441   OS << "} // end namespace " << Namespace << "\n";
442   OS << "} // end namespace llvm\n";
443   OS << "#endif // GET_INSTRINFO_OPERAND_TYPE\n\n";
444 }
445 
446 void InstrInfoEmitter::emitMCIIHelperMethods(raw_ostream &OS,
447                                              StringRef TargetName) {
448   RecVec TIIPredicates = Records.getAllDerivedDefinitions("TIIPredicate");
449   if (TIIPredicates.empty())
450     return;
451 
452   OS << "#ifdef GET_INSTRINFO_MC_HELPER_DECLS\n";
453   OS << "#undef GET_INSTRINFO_MC_HELPER_DECLS\n\n";
454 
455   OS << "namespace llvm {\n";
456   OS << "class MCInst;\n\n";
457 
458   OS << "namespace " << TargetName << "_MC {\n\n";
459 
460   for (const Record *Rec : TIIPredicates) {
461     OS << "bool " << Rec->getValueAsString("FunctionName")
462         << "(const MCInst &MI);\n";
463   }
464 
465   OS << "\n} // end namespace " << TargetName << "_MC\n";
466   OS << "} // end namespace llvm\n\n";
467 
468   OS << "#endif // GET_INSTRINFO_MC_HELPER_DECLS\n\n";
469 
470   OS << "#ifdef GET_INSTRINFO_MC_HELPERS\n";
471   OS << "#undef GET_INSTRINFO_MC_HELPERS\n\n";
472 
473   OS << "namespace llvm {\n";
474   OS << "namespace " << TargetName << "_MC {\n\n";
475 
476   PredicateExpander PE(TargetName);
477   PE.setExpandForMC(true);
478 
479   for (const Record *Rec : TIIPredicates) {
480     OS << "bool " << Rec->getValueAsString("FunctionName");
481     OS << "(const MCInst &MI) {\n";
482 
483     OS.indent(PE.getIndentLevel() * 2);
484     PE.expandStatement(OS, Rec->getValueAsDef("Body"));
485     OS << "\n}\n\n";
486   }
487 
488   OS << "} // end namespace " << TargetName << "_MC\n";
489   OS << "} // end namespace llvm\n\n";
490 
491   OS << "#endif // GET_GENISTRINFO_MC_HELPERS\n";
492 }
493 
494 void InstrInfoEmitter::emitTIIHelperMethods(raw_ostream &OS,
495                                             StringRef TargetName,
496                                             bool ExpandDefinition) {
497   RecVec TIIPredicates = Records.getAllDerivedDefinitions("TIIPredicate");
498   if (TIIPredicates.empty())
499     return;
500 
501   PredicateExpander PE(TargetName);
502   PE.setExpandForMC(false);
503 
504   for (const Record *Rec : TIIPredicates) {
505     OS << (ExpandDefinition ? "" : "static ") << "bool ";
506     if (ExpandDefinition)
507       OS << TargetName << "InstrInfo::";
508     OS << Rec->getValueAsString("FunctionName");
509     OS << "(const MachineInstr &MI)";
510     if (!ExpandDefinition) {
511       OS << ";\n";
512       continue;
513     }
514 
515     OS << " {\n";
516     OS.indent(PE.getIndentLevel() * 2);
517     PE.expandStatement(OS, Rec->getValueAsDef("Body"));
518     OS << "\n}\n\n";
519   }
520 }
521 
522 //===----------------------------------------------------------------------===//
523 // Main Output.
524 //===----------------------------------------------------------------------===//
525 
526 // run - Emit the main instruction description records for the target...
527 void InstrInfoEmitter::run(raw_ostream &OS) {
528   emitSourceFileHeader("Target Instruction Enum Values and Descriptors", OS);
529   emitEnums(OS);
530 
531   OS << "#ifdef GET_INSTRINFO_MC_DESC\n";
532   OS << "#undef GET_INSTRINFO_MC_DESC\n";
533 
534   OS << "namespace llvm {\n\n";
535 
536   CodeGenTarget &Target = CDP.getTargetInfo();
537   const std::string &TargetName = std::string(Target.getName());
538   Record *InstrInfo = Target.getInstructionSet();
539 
540   // Keep track of all of the def lists we have emitted already.
541   std::map<std::vector<Record*>, unsigned> EmittedLists;
542   unsigned ListNumber = 0;
543 
544   // Emit all of the instruction's implicit uses and defs.
545   Records.startTimer("Emit uses/defs");
546   for (const CodeGenInstruction *II : Target.getInstructionsByEnumValue()) {
547     Record *Inst = II->TheDef;
548     std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
549     if (!Uses.empty()) {
550       unsigned &IL = EmittedLists[Uses];
551       if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
552     }
553     std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
554     if (!Defs.empty()) {
555       unsigned &IL = EmittedLists[Defs];
556       if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
557     }
558   }
559 
560   OperandInfoMapTy OperandInfoIDs;
561 
562   // Emit all of the operand info records.
563   Records.startTimer("Emit operand info");
564   EmitOperandInfo(OS, OperandInfoIDs);
565 
566   // Emit all of the MCInstrDesc records in their ENUM ordering.
567   //
568   Records.startTimer("Emit InstrDesc records");
569   OS << "\nextern const MCInstrDesc " << TargetName << "Insts[] = {\n";
570   ArrayRef<const CodeGenInstruction*> NumberedInstructions =
571     Target.getInstructionsByEnumValue();
572 
573   SequenceToOffsetTable<std::string> InstrNames;
574   unsigned Num = 0;
575   for (const CodeGenInstruction *Inst : NumberedInstructions) {
576     // Keep a list of the instruction names.
577     InstrNames.add(std::string(Inst->TheDef->getName()));
578     // Emit the record into the table.
579     emitRecord(*Inst, Num++, InstrInfo, EmittedLists, OperandInfoIDs, OS);
580   }
581   OS << "};\n\n";
582 
583   // Emit the array of instruction names.
584   Records.startTimer("Emit instruction names");
585   InstrNames.layout();
586   InstrNames.emitStringLiteralDef(OS, Twine("extern const char ") + TargetName +
587                                           "InstrNameData[]");
588 
589   OS << "extern const unsigned " << TargetName <<"InstrNameIndices[] = {";
590   Num = 0;
591   for (const CodeGenInstruction *Inst : NumberedInstructions) {
592     // Newline every eight entries.
593     if (Num % 8 == 0)
594       OS << "\n    ";
595     OS << InstrNames.get(std::string(Inst->TheDef->getName())) << "U, ";
596     ++Num;
597   }
598   OS << "\n};\n\n";
599 
600   bool HasDeprecationFeatures =
601       llvm::any_of(NumberedInstructions, [](const CodeGenInstruction *Inst) {
602         return !Inst->HasComplexDeprecationPredicate &&
603                !Inst->DeprecatedReason.empty();
604       });
605   if (HasDeprecationFeatures) {
606     OS << "extern const uint8_t " << TargetName
607        << "InstrDeprecationFeatures[] = {";
608     Num = 0;
609     for (const CodeGenInstruction *Inst : NumberedInstructions) {
610       if (Num % 8 == 0)
611         OS << "\n    ";
612       if (!Inst->HasComplexDeprecationPredicate &&
613           !Inst->DeprecatedReason.empty())
614         OS << Target.getInstNamespace() << "::" << Inst->DeprecatedReason
615            << ", ";
616       else
617         OS << "uint8_t(-1), ";
618       ++Num;
619     }
620     OS << "\n};\n\n";
621   }
622 
623   bool HasComplexDeprecationInfos =
624       llvm::any_of(NumberedInstructions, [](const CodeGenInstruction *Inst) {
625         return Inst->HasComplexDeprecationPredicate;
626       });
627   if (HasComplexDeprecationInfos) {
628     OS << "extern const MCInstrInfo::ComplexDeprecationPredicate " << TargetName
629        << "InstrComplexDeprecationInfos[] = {";
630     Num = 0;
631     for (const CodeGenInstruction *Inst : NumberedInstructions) {
632       if (Num % 8 == 0)
633         OS << "\n    ";
634       if (Inst->HasComplexDeprecationPredicate)
635         // Emit a function pointer to the complex predicate method.
636         OS << "&get" << Inst->DeprecatedReason << "DeprecationInfo, ";
637       else
638         OS << "nullptr, ";
639       ++Num;
640     }
641     OS << "\n};\n\n";
642   }
643 
644   // MCInstrInfo initialization routine.
645   Records.startTimer("Emit initialization routine");
646   OS << "static inline void Init" << TargetName
647      << "MCInstrInfo(MCInstrInfo *II) {\n";
648   OS << "  II->InitMCInstrInfo(" << TargetName << "Insts, " << TargetName
649      << "InstrNameIndices, " << TargetName << "InstrNameData, ";
650   if (HasDeprecationFeatures)
651     OS << TargetName << "InstrDeprecationFeatures, ";
652   else
653     OS << "nullptr, ";
654   if (HasComplexDeprecationInfos)
655     OS << TargetName << "InstrComplexDeprecationInfos, ";
656   else
657     OS << "nullptr, ";
658   OS << NumberedInstructions.size() << ");\n}\n\n";
659 
660   OS << "} // end namespace llvm\n";
661 
662   OS << "#endif // GET_INSTRINFO_MC_DESC\n\n";
663 
664   // Create a TargetInstrInfo subclass to hide the MC layer initialization.
665   OS << "#ifdef GET_INSTRINFO_HEADER\n";
666   OS << "#undef GET_INSTRINFO_HEADER\n";
667 
668   std::string ClassName = TargetName + "GenInstrInfo";
669   OS << "namespace llvm {\n";
670   OS << "struct " << ClassName << " : public TargetInstrInfo {\n"
671      << "  explicit " << ClassName
672      << "(int CFSetupOpcode = -1, int CFDestroyOpcode = -1, int CatchRetOpcode = -1, int ReturnOpcode = -1);\n"
673      << "  ~" << ClassName << "() override = default;\n";
674 
675 
676   OS << "\n};\n} // end namespace llvm\n";
677 
678   OS << "#endif // GET_INSTRINFO_HEADER\n\n";
679 
680   OS << "#ifdef GET_INSTRINFO_HELPER_DECLS\n";
681   OS << "#undef GET_INSTRINFO_HELPER_DECLS\n\n";
682   emitTIIHelperMethods(OS, TargetName, /* ExpandDefintion = */false);
683   OS << "\n";
684   OS << "#endif // GET_INSTRINFO_HELPER_DECLS\n\n";
685 
686   OS << "#ifdef GET_INSTRINFO_HELPERS\n";
687   OS << "#undef GET_INSTRINFO_HELPERS\n\n";
688   emitTIIHelperMethods(OS, TargetName, /* ExpandDefintion = */true);
689   OS << "#endif // GET_INSTRINFO_HELPERS\n\n";
690 
691   OS << "#ifdef GET_INSTRINFO_CTOR_DTOR\n";
692   OS << "#undef GET_INSTRINFO_CTOR_DTOR\n";
693 
694   OS << "namespace llvm {\n";
695   OS << "extern const MCInstrDesc " << TargetName << "Insts[];\n";
696   OS << "extern const unsigned " << TargetName << "InstrNameIndices[];\n";
697   OS << "extern const char " << TargetName << "InstrNameData[];\n";
698   if (HasDeprecationFeatures)
699     OS << "extern const uint8_t " << TargetName
700        << "InstrDeprecationFeatures[];\n";
701   if (HasComplexDeprecationInfos)
702     OS << "extern const MCInstrInfo::ComplexDeprecationPredicate " << TargetName
703        << "InstrComplexDeprecationInfos[];\n";
704   OS << ClassName << "::" << ClassName
705      << "(int CFSetupOpcode, int CFDestroyOpcode, int CatchRetOpcode, int "
706         "ReturnOpcode)\n"
707      << "  : TargetInstrInfo(CFSetupOpcode, CFDestroyOpcode, CatchRetOpcode, "
708         "ReturnOpcode) {\n"
709      << "  InitMCInstrInfo(" << TargetName << "Insts, " << TargetName
710      << "InstrNameIndices, " << TargetName << "InstrNameData, ";
711   if (HasDeprecationFeatures)
712     OS << TargetName << "InstrDeprecationFeatures, ";
713   else
714     OS << "nullptr, ";
715   if (HasComplexDeprecationInfos)
716     OS << TargetName << "InstrComplexDeprecationInfos, ";
717   else
718     OS << "nullptr, ";
719   OS << NumberedInstructions.size() << ");\n}\n";
720   OS << "} // end namespace llvm\n";
721 
722   OS << "#endif // GET_INSTRINFO_CTOR_DTOR\n\n";
723 
724   Records.startTimer("Emit operand name mappings");
725   emitOperandNameMappings(OS, Target, NumberedInstructions);
726 
727   Records.startTimer("Emit operand type mappings");
728   emitOperandTypeMappings(OS, Target, NumberedInstructions);
729 
730   Records.startTimer("Emit helper methods");
731   emitMCIIHelperMethods(OS, TargetName);
732 }
733 
734 void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
735                                   Record *InstrInfo,
736                          std::map<std::vector<Record*>, unsigned> &EmittedLists,
737                                   const OperandInfoMapTy &OpInfo,
738                                   raw_ostream &OS) {
739   int MinOperands = 0;
740   if (!Inst.Operands.empty())
741     // Each logical operand can be multiple MI operands.
742     MinOperands = Inst.Operands.back().MIOperandNo +
743                   Inst.Operands.back().MINumOperands;
744 
745   OS << "  { ";
746   OS << Num << ",\t" << MinOperands << ",\t"
747      << Inst.Operands.NumDefs << ",\t"
748      << Inst.TheDef->getValueAsInt("Size") << ",\t"
749      << SchedModels.getSchedClassIdx(Inst) << ",\t0";
750 
751   CodeGenTarget &Target = CDP.getTargetInfo();
752 
753   // Emit all of the target independent flags...
754   if (Inst.isPreISelOpcode)    OS << "|(1ULL<<MCID::PreISelOpcode)";
755   if (Inst.isPseudo)           OS << "|(1ULL<<MCID::Pseudo)";
756   if (Inst.isReturn)           OS << "|(1ULL<<MCID::Return)";
757   if (Inst.isEHScopeReturn)    OS << "|(1ULL<<MCID::EHScopeReturn)";
758   if (Inst.isBranch)           OS << "|(1ULL<<MCID::Branch)";
759   if (Inst.isIndirectBranch)   OS << "|(1ULL<<MCID::IndirectBranch)";
760   if (Inst.isCompare)          OS << "|(1ULL<<MCID::Compare)";
761   if (Inst.isMoveImm)          OS << "|(1ULL<<MCID::MoveImm)";
762   if (Inst.isMoveReg)          OS << "|(1ULL<<MCID::MoveReg)";
763   if (Inst.isBitcast)          OS << "|(1ULL<<MCID::Bitcast)";
764   if (Inst.isAdd)              OS << "|(1ULL<<MCID::Add)";
765   if (Inst.isTrap)             OS << "|(1ULL<<MCID::Trap)";
766   if (Inst.isSelect)           OS << "|(1ULL<<MCID::Select)";
767   if (Inst.isBarrier)          OS << "|(1ULL<<MCID::Barrier)";
768   if (Inst.hasDelaySlot)       OS << "|(1ULL<<MCID::DelaySlot)";
769   if (Inst.isCall)             OS << "|(1ULL<<MCID::Call)";
770   if (Inst.canFoldAsLoad)      OS << "|(1ULL<<MCID::FoldableAsLoad)";
771   if (Inst.mayLoad)            OS << "|(1ULL<<MCID::MayLoad)";
772   if (Inst.mayStore)           OS << "|(1ULL<<MCID::MayStore)";
773   if (Inst.mayRaiseFPException) OS << "|(1ULL<<MCID::MayRaiseFPException)";
774   if (Inst.isPredicable)       OS << "|(1ULL<<MCID::Predicable)";
775   if (Inst.isConvertibleToThreeAddress) OS << "|(1ULL<<MCID::ConvertibleTo3Addr)";
776   if (Inst.isCommutable)       OS << "|(1ULL<<MCID::Commutable)";
777   if (Inst.isTerminator)       OS << "|(1ULL<<MCID::Terminator)";
778   if (Inst.isReMaterializable) OS << "|(1ULL<<MCID::Rematerializable)";
779   if (Inst.isNotDuplicable)    OS << "|(1ULL<<MCID::NotDuplicable)";
780   if (Inst.Operands.hasOptionalDef) OS << "|(1ULL<<MCID::HasOptionalDef)";
781   if (Inst.usesCustomInserter) OS << "|(1ULL<<MCID::UsesCustomInserter)";
782   if (Inst.hasPostISelHook)    OS << "|(1ULL<<MCID::HasPostISelHook)";
783   if (Inst.Operands.isVariadic)OS << "|(1ULL<<MCID::Variadic)";
784   if (Inst.hasSideEffects)     OS << "|(1ULL<<MCID::UnmodeledSideEffects)";
785   if (Inst.isAsCheapAsAMove)   OS << "|(1ULL<<MCID::CheapAsAMove)";
786   if (!Target.getAllowRegisterRenaming() || Inst.hasExtraSrcRegAllocReq)
787     OS << "|(1ULL<<MCID::ExtraSrcRegAllocReq)";
788   if (!Target.getAllowRegisterRenaming() || Inst.hasExtraDefRegAllocReq)
789     OS << "|(1ULL<<MCID::ExtraDefRegAllocReq)";
790   if (Inst.isRegSequence) OS << "|(1ULL<<MCID::RegSequence)";
791   if (Inst.isExtractSubreg) OS << "|(1ULL<<MCID::ExtractSubreg)";
792   if (Inst.isInsertSubreg) OS << "|(1ULL<<MCID::InsertSubreg)";
793   if (Inst.isConvergent) OS << "|(1ULL<<MCID::Convergent)";
794   if (Inst.variadicOpsAreDefs) OS << "|(1ULL<<MCID::VariadicOpsAreDefs)";
795   if (Inst.isAuthenticated) OS << "|(1ULL<<MCID::Authenticated)";
796 
797   // Emit all of the target-specific flags...
798   BitsInit *TSF = Inst.TheDef->getValueAsBitsInit("TSFlags");
799   if (!TSF)
800     PrintFatalError(Inst.TheDef->getLoc(), "no TSFlags?");
801   uint64_t Value = 0;
802   for (unsigned i = 0, e = TSF->getNumBits(); i != e; ++i) {
803     if (const auto *Bit = dyn_cast<BitInit>(TSF->getBit(i)))
804       Value |= uint64_t(Bit->getValue()) << i;
805     else
806       PrintFatalError(Inst.TheDef->getLoc(),
807                       "Invalid TSFlags bit in " + Inst.TheDef->getName());
808   }
809   OS << ", 0x";
810   OS.write_hex(Value);
811   OS << "ULL, ";
812 
813   // Emit the implicit uses and defs lists...
814   std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
815   if (UseList.empty())
816     OS << "nullptr, ";
817   else
818     OS << "ImplicitList" << EmittedLists[UseList] << ", ";
819 
820   std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
821   if (DefList.empty())
822     OS << "nullptr, ";
823   else
824     OS << "ImplicitList" << EmittedLists[DefList] << ", ";
825 
826   // Emit the operand info.
827   std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
828   if (OperandInfo.empty())
829     OS << "nullptr";
830   else
831     OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
832 
833   OS << " },  // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
834 }
835 
836 // emitEnums - Print out enum values for all of the instructions.
837 void InstrInfoEmitter::emitEnums(raw_ostream &OS) {
838   OS << "#ifdef GET_INSTRINFO_ENUM\n";
839   OS << "#undef GET_INSTRINFO_ENUM\n";
840 
841   OS << "namespace llvm {\n\n";
842 
843   const CodeGenTarget &Target = CDP.getTargetInfo();
844 
845   // We must emit the PHI opcode first...
846   StringRef Namespace = Target.getInstNamespace();
847 
848   if (Namespace.empty())
849     PrintFatalError("No instructions defined!");
850 
851   OS << "namespace " << Namespace << " {\n";
852   OS << "  enum {\n";
853   unsigned Num = 0;
854   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue())
855     OS << "    " << Inst->TheDef->getName() << "\t= " << Num++ << ",\n";
856   OS << "    INSTRUCTION_LIST_END = " << Num << "\n";
857   OS << "  };\n\n";
858   OS << "} // end namespace " << Namespace << "\n";
859   OS << "} // end namespace llvm\n";
860   OS << "#endif // GET_INSTRINFO_ENUM\n\n";
861 
862   OS << "#ifdef GET_INSTRINFO_SCHED_ENUM\n";
863   OS << "#undef GET_INSTRINFO_SCHED_ENUM\n";
864   OS << "namespace llvm {\n\n";
865   OS << "namespace " << Namespace << " {\n";
866   OS << "namespace Sched {\n";
867   OS << "  enum {\n";
868   Num = 0;
869   for (const auto &Class : SchedModels.explicit_classes())
870     OS << "    " << Class.Name << "\t= " << Num++ << ",\n";
871   OS << "    SCHED_LIST_END = " << Num << "\n";
872   OS << "  };\n";
873   OS << "} // end namespace Sched\n";
874   OS << "} // end namespace " << Namespace << "\n";
875   OS << "} // end namespace llvm\n";
876 
877   OS << "#endif // GET_INSTRINFO_SCHED_ENUM\n\n";
878 }
879 
880 namespace llvm {
881 
882 void EmitInstrInfo(RecordKeeper &RK, raw_ostream &OS) {
883   RK.startTimer("Analyze DAG patterns");
884   InstrInfoEmitter(RK).run(OS);
885   RK.startTimer("Emit map table");
886   EmitMapTable(RK, OS);
887 }
888 
889 } // end namespace llvm
890