InstrInfoEmitter.cpp revision 353358
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
35using namespace llvm;
36
37namespace {
38
39class InstrInfoEmitter {
40  RecordKeeper &Records;
41  CodeGenDAGPatterns CDP;
42  const CodeGenSchedModels &SchedModels;
43
44public:
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
51private:
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
97static 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
109std::vector<std::string>
110InstrInfoEmitter::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      // Fill in operand type.
168      Res += ", ";
169      assert(!Op.OperandType.empty() && "Invalid operand type.");
170      Res += Op.OperandType;
171
172      // Fill in constraint info.
173      Res += ", ";
174
175      const CGIOperandList::ConstraintInfo &Constraint =
176        Op.Constraints[j];
177      if (Constraint.isNone())
178        Res += "0";
179      else if (Constraint.isEarlyClobber())
180        Res += "(1 << MCOI::EARLY_CLOBBER)";
181      else {
182        assert(Constraint.isTied());
183        Res += "((" + utostr(Constraint.getTiedOperand()) +
184                    " << 16) | (1 << MCOI::TIED_TO))";
185      }
186
187      Result.push_back(Res);
188    }
189  }
190
191  return Result;
192}
193
194void InstrInfoEmitter::EmitOperandInfo(raw_ostream &OS,
195                                       OperandInfoMapTy &OperandInfoIDs) {
196  // ID #0 is for no operand info.
197  unsigned OperandListNum = 0;
198  OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
199
200  OS << "\n";
201  const CodeGenTarget &Target = CDP.getTargetInfo();
202  for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
203    std::vector<std::string> OperandInfo = GetOperandInfo(*Inst);
204    unsigned &N = OperandInfoIDs[OperandInfo];
205    if (N != 0) continue;
206
207    N = ++OperandListNum;
208    OS << "static const MCOperandInfo OperandInfo" << N << "[] = { ";
209    for (const std::string &Info : OperandInfo)
210      OS << "{ " << Info << " }, ";
211    OS << "};\n";
212  }
213}
214
215/// Initialize data structures for generating operand name mappings.
216///
217/// \param Operands [out] A map used to generate the OpName enum with operand
218///        names as its keys and operand enum values as its values.
219/// \param OperandMap [out] A map for representing the operand name mappings for
220///        each instructions.  This is used to generate the OperandMap table as
221///        well as the getNamedOperandIdx() function.
222void InstrInfoEmitter::initOperandMapData(
223        ArrayRef<const CodeGenInstruction *> NumberedInstructions,
224        StringRef Namespace,
225        std::map<std::string, unsigned> &Operands,
226        OpNameMapTy &OperandMap) {
227  unsigned NumOperands = 0;
228  for (const CodeGenInstruction *Inst : NumberedInstructions) {
229    if (!Inst->TheDef->getValueAsBit("UseNamedOperandTable"))
230      continue;
231    std::map<unsigned, unsigned> OpList;
232    for (const auto &Info : Inst->Operands) {
233      StrUintMapIter I = Operands.find(Info.Name);
234
235      if (I == Operands.end()) {
236        I = Operands.insert(Operands.begin(),
237                    std::pair<std::string, unsigned>(Info.Name, NumOperands++));
238      }
239      OpList[I->second] = Info.MIOperandNo;
240    }
241    OperandMap[OpList].push_back(Namespace.str() + "::" +
242                                 Inst->TheDef->getName().str());
243  }
244}
245
246/// Generate a table and function for looking up the indices of operands by
247/// name.
248///
249/// This code generates:
250/// - An enum in the llvm::TargetNamespace::OpName namespace, with one entry
251///   for each operand name.
252/// - A 2-dimensional table called OperandMap for mapping OpName enum values to
253///   operand indices.
254/// - A function called getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx)
255///   for looking up the operand index for an instruction, given a value from
256///   OpName enum
257void InstrInfoEmitter::emitOperandNameMappings(raw_ostream &OS,
258           const CodeGenTarget &Target,
259           ArrayRef<const CodeGenInstruction*> NumberedInstructions) {
260  StringRef Namespace = Target.getInstNamespace();
261  std::string OpNameNS = "OpName";
262  // Map of operand names to their enumeration value.  This will be used to
263  // generate the OpName enum.
264  std::map<std::string, unsigned> Operands;
265  OpNameMapTy OperandMap;
266
267  initOperandMapData(NumberedInstructions, Namespace, Operands, OperandMap);
268
269  OS << "#ifdef GET_INSTRINFO_OPERAND_ENUM\n";
270  OS << "#undef GET_INSTRINFO_OPERAND_ENUM\n";
271  OS << "namespace llvm {\n";
272  OS << "namespace " << Namespace << " {\n";
273  OS << "namespace " << OpNameNS << " {\n";
274  OS << "enum {\n";
275  for (const auto &Op : Operands)
276    OS << "  " << Op.first << " = " << Op.second << ",\n";
277
278  OS << "OPERAND_LAST";
279  OS << "\n};\n";
280  OS << "} // end namespace OpName\n";
281  OS << "} // end namespace " << Namespace << "\n";
282  OS << "} // end namespace llvm\n";
283  OS << "#endif //GET_INSTRINFO_OPERAND_ENUM\n\n";
284
285  OS << "#ifdef GET_INSTRINFO_NAMED_OPS\n";
286  OS << "#undef GET_INSTRINFO_NAMED_OPS\n";
287  OS << "namespace llvm {\n";
288  OS << "namespace " << Namespace << " {\n";
289  OS << "LLVM_READONLY\n";
290  OS << "int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx) {\n";
291  if (!Operands.empty()) {
292    OS << "  static const int16_t OperandMap [][" << Operands.size()
293       << "] = {\n";
294    for (const auto &Entry : OperandMap) {
295      const std::map<unsigned, unsigned> &OpList = Entry.first;
296      OS << "{";
297
298      // Emit a row of the OperandMap table
299      for (unsigned i = 0, e = Operands.size(); i != e; ++i)
300        OS << (OpList.count(i) == 0 ? -1 : (int)OpList.find(i)->second) << ", ";
301
302      OS << "},\n";
303    }
304    OS << "};\n";
305
306    OS << "  switch(Opcode) {\n";
307    unsigned TableIndex = 0;
308    for (const auto &Entry : OperandMap) {
309      for (const std::string &Name : Entry.second)
310        OS << "  case " << Name << ":\n";
311
312      OS << "    return OperandMap[" << TableIndex++ << "][NamedIdx];\n";
313    }
314    OS << "    default: return -1;\n";
315    OS << "  }\n";
316  } else {
317    // There are no operands, so no need to emit anything
318    OS << "  return -1;\n";
319  }
320  OS << "}\n";
321  OS << "} // end namespace " << Namespace << "\n";
322  OS << "} // end namespace llvm\n";
323  OS << "#endif //GET_INSTRINFO_NAMED_OPS\n\n";
324}
325
326/// Generate an enum for all the operand types for this target, under the
327/// llvm::TargetNamespace::OpTypes namespace.
328/// Operand types are all definitions derived of the Operand Target.td class.
329void InstrInfoEmitter::emitOperandTypeMappings(
330    raw_ostream &OS, const CodeGenTarget &Target,
331    ArrayRef<const CodeGenInstruction *> NumberedInstructions) {
332
333  StringRef Namespace = Target.getInstNamespace();
334  std::vector<Record *> Operands = Records.getAllDerivedDefinitions("Operand");
335
336  OS << "#ifdef GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
337  OS << "#undef GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
338  OS << "namespace llvm {\n";
339  OS << "namespace " << Namespace << " {\n";
340  OS << "namespace OpTypes {\n";
341  OS << "enum OperandType {\n";
342
343  unsigned EnumVal = 0;
344  for (const Record *Op : Operands) {
345    if (!Op->isAnonymous())
346      OS << "  " << Op->getName() << " = " << EnumVal << ",\n";
347    ++EnumVal;
348  }
349
350  OS << "  OPERAND_TYPE_LIST_END" << "\n};\n";
351  OS << "} // end namespace OpTypes\n";
352  OS << "} // end namespace " << Namespace << "\n";
353  OS << "} // end namespace llvm\n";
354  OS << "#endif // GET_INSTRINFO_OPERAND_TYPES_ENUM\n\n";
355
356  OS << "#ifdef GET_INSTRINFO_OPERAND_TYPE\n";
357  OS << "#undef GET_INSTRINFO_OPERAND_TYPE\n";
358  OS << "namespace llvm {\n";
359  OS << "namespace " << Namespace << " {\n";
360  OS << "LLVM_READONLY\n";
361  OS << "int getOperandType(uint16_t Opcode, uint16_t OpIdx) {\n";
362  if (!NumberedInstructions.empty()) {
363    std::vector<int> OperandOffsets;
364    std::vector<Record *> OperandRecords;
365    int CurrentOffset = 0;
366    for (const CodeGenInstruction *Inst : NumberedInstructions) {
367      OperandOffsets.push_back(CurrentOffset);
368      for (const auto &Op : Inst->Operands) {
369        const DagInit *MIOI = Op.MIOperandInfo;
370        if (!MIOI || MIOI->getNumArgs() == 0) {
371          // Single, anonymous, operand.
372          OperandRecords.push_back(Op.Rec);
373          ++CurrentOffset;
374        } else {
375          for (Init *Arg : make_range(MIOI->arg_begin(), MIOI->arg_end())) {
376            OperandRecords.push_back(cast<DefInit>(Arg)->getDef());
377            ++CurrentOffset;
378          }
379        }
380      }
381    }
382
383    // Emit the table of offsets for the opcode lookup.
384    OS << "  const int Offsets[] = {\n";
385    for (int I = 0, E = OperandOffsets.size(); I != E; ++I)
386      OS << "    " << OperandOffsets[I] << ",\n";
387    OS << "  };\n";
388
389    // Add an entry for the end so that we don't need to special case it below.
390    OperandOffsets.push_back(OperandRecords.size());
391    // Emit the actual operand types in a flat table.
392    OS << "  const int OpcodeOperandTypes[] = {\n    ";
393    for (int I = 0, E = OperandRecords.size(), CurOffset = 1; I != E; ++I) {
394      // We print each Opcode's operands in its own row.
395      if (I == OperandOffsets[CurOffset]) {
396        OS << "\n    ";
397        // If there are empty rows, mark them with an empty comment.
398        while (OperandOffsets[++CurOffset] == I)
399          OS << "/**/\n    ";
400      }
401      Record *OpR = OperandRecords[I];
402      if (OpR->isSubClassOf("Operand") && !OpR->isAnonymous())
403        OS << "OpTypes::" << OpR->getName();
404      else
405        OS << -1;
406      OS << ", ";
407    }
408    OS << "\n  };\n";
409
410    OS << "  return OpcodeOperandTypes[Offsets[Opcode] + OpIdx];\n";
411  } else {
412    OS << "  llvm_unreachable(\"No instructions defined\");\n";
413  }
414  OS << "}\n";
415  OS << "} // end namespace " << Namespace << "\n";
416  OS << "} // end namespace llvm\n";
417  OS << "#endif //GET_INSTRINFO_OPERAND_TYPE\n\n";
418}
419
420void InstrInfoEmitter::emitMCIIHelperMethods(raw_ostream &OS,
421                                             StringRef TargetName) {
422  RecVec TIIPredicates = Records.getAllDerivedDefinitions("TIIPredicate");
423  if (TIIPredicates.empty())
424    return;
425
426  OS << "#ifdef GET_INSTRINFO_MC_HELPER_DECLS\n";
427  OS << "#undef GET_INSTRINFO_MC_HELPER_DECLS\n\n";
428
429  OS << "namespace llvm {\n";
430  OS << "class MCInst;\n\n";
431
432  OS << "namespace " << TargetName << "_MC {\n\n";
433
434  for (const Record *Rec : TIIPredicates) {
435    OS << "bool " << Rec->getValueAsString("FunctionName")
436        << "(const MCInst &MI);\n";
437  }
438
439  OS << "\n} // end " << TargetName << "_MC namespace\n";
440  OS << "} // end llvm namespace\n\n";
441
442  OS << "#endif // GET_INSTRINFO_MC_HELPER_DECLS\n\n";
443
444  OS << "#ifdef GET_INSTRINFO_MC_HELPERS\n";
445  OS << "#undef GET_INSTRINFO_MC_HELPERS\n\n";
446
447  OS << "namespace llvm {\n";
448  OS << "namespace " << TargetName << "_MC {\n\n";
449
450  PredicateExpander PE(TargetName);
451  PE.setExpandForMC(true);
452
453  for (const Record *Rec : TIIPredicates) {
454    OS << "bool " << Rec->getValueAsString("FunctionName");
455    OS << "(const MCInst &MI) {\n";
456
457    OS.indent(PE.getIndentLevel() * 2);
458    PE.expandStatement(OS, Rec->getValueAsDef("Body"));
459    OS << "\n}\n\n";
460  }
461
462  OS << "} // end " << TargetName << "_MC namespace\n";
463  OS << "} // end llvm namespace\n\n";
464
465  OS << "#endif // GET_GENISTRINFO_MC_HELPERS\n";
466}
467
468void InstrInfoEmitter::emitTIIHelperMethods(raw_ostream &OS,
469                                            StringRef TargetName,
470                                            bool ExpandDefinition) {
471  RecVec TIIPredicates = Records.getAllDerivedDefinitions("TIIPredicate");
472  if (TIIPredicates.empty())
473    return;
474
475  PredicateExpander PE(TargetName);
476  PE.setExpandForMC(false);
477
478  for (const Record *Rec : TIIPredicates) {
479    OS << (ExpandDefinition ? "" : "static ") << "bool ";
480    if (ExpandDefinition)
481      OS << TargetName << "InstrInfo::";
482    OS << Rec->getValueAsString("FunctionName");
483    OS << "(const MachineInstr &MI)";
484    if (!ExpandDefinition) {
485      OS << ";\n";
486      continue;
487    }
488
489    OS << " {\n";
490    OS.indent(PE.getIndentLevel() * 2);
491    PE.expandStatement(OS, Rec->getValueAsDef("Body"));
492    OS << "\n}\n\n";
493  }
494}
495
496//===----------------------------------------------------------------------===//
497// Main Output.
498//===----------------------------------------------------------------------===//
499
500// run - Emit the main instruction description records for the target...
501void InstrInfoEmitter::run(raw_ostream &OS) {
502  emitSourceFileHeader("Target Instruction Enum Values and Descriptors", OS);
503  emitEnums(OS);
504
505  OS << "#ifdef GET_INSTRINFO_MC_DESC\n";
506  OS << "#undef GET_INSTRINFO_MC_DESC\n";
507
508  OS << "namespace llvm {\n\n";
509
510  CodeGenTarget &Target = CDP.getTargetInfo();
511  const std::string &TargetName = Target.getName();
512  Record *InstrInfo = Target.getInstructionSet();
513
514  // Keep track of all of the def lists we have emitted already.
515  std::map<std::vector<Record*>, unsigned> EmittedLists;
516  unsigned ListNumber = 0;
517
518  // Emit all of the instruction's implicit uses and defs.
519  for (const CodeGenInstruction *II : Target.getInstructionsByEnumValue()) {
520    Record *Inst = II->TheDef;
521    std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
522    if (!Uses.empty()) {
523      unsigned &IL = EmittedLists[Uses];
524      if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
525    }
526    std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
527    if (!Defs.empty()) {
528      unsigned &IL = EmittedLists[Defs];
529      if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
530    }
531  }
532
533  OperandInfoMapTy OperandInfoIDs;
534
535  // Emit all of the operand info records.
536  EmitOperandInfo(OS, OperandInfoIDs);
537
538  // Emit all of the MCInstrDesc records in their ENUM ordering.
539  //
540  OS << "\nextern const MCInstrDesc " << TargetName << "Insts[] = {\n";
541  ArrayRef<const CodeGenInstruction*> NumberedInstructions =
542    Target.getInstructionsByEnumValue();
543
544  SequenceToOffsetTable<std::string> InstrNames;
545  unsigned Num = 0;
546  for (const CodeGenInstruction *Inst : NumberedInstructions) {
547    // Keep a list of the instruction names.
548    InstrNames.add(Inst->TheDef->getName());
549    // Emit the record into the table.
550    emitRecord(*Inst, Num++, InstrInfo, EmittedLists, OperandInfoIDs, OS);
551  }
552  OS << "};\n\n";
553
554  // Emit the array of instruction names.
555  InstrNames.layout();
556  OS << "extern const char " << TargetName << "InstrNameData[] = {\n";
557  InstrNames.emit(OS, printChar);
558  OS << "};\n\n";
559
560  OS << "extern const unsigned " << TargetName <<"InstrNameIndices[] = {";
561  Num = 0;
562  for (const CodeGenInstruction *Inst : NumberedInstructions) {
563    // Newline every eight entries.
564    if (Num % 8 == 0)
565      OS << "\n    ";
566    OS << InstrNames.get(Inst->TheDef->getName()) << "U, ";
567    ++Num;
568  }
569
570  OS << "\n};\n\n";
571
572  // MCInstrInfo initialization routine.
573  OS << "static inline void Init" << TargetName
574     << "MCInstrInfo(MCInstrInfo *II) {\n";
575  OS << "  II->InitMCInstrInfo(" << TargetName << "Insts, "
576     << TargetName << "InstrNameIndices, " << TargetName << "InstrNameData, "
577     << NumberedInstructions.size() << ");\n}\n\n";
578
579  OS << "} // end llvm namespace\n";
580
581  OS << "#endif // GET_INSTRINFO_MC_DESC\n\n";
582
583  // Create a TargetInstrInfo subclass to hide the MC layer initialization.
584  OS << "#ifdef GET_INSTRINFO_HEADER\n";
585  OS << "#undef GET_INSTRINFO_HEADER\n";
586
587  std::string ClassName = TargetName + "GenInstrInfo";
588  OS << "namespace llvm {\n";
589  OS << "struct " << ClassName << " : public TargetInstrInfo {\n"
590     << "  explicit " << ClassName
591     << "(int CFSetupOpcode = -1, int CFDestroyOpcode = -1, int CatchRetOpcode = -1, int ReturnOpcode = -1);\n"
592     << "  ~" << ClassName << "() override = default;\n";
593
594
595  OS << "\n};\n} // end llvm namespace\n";
596
597  OS << "#endif // GET_INSTRINFO_HEADER\n\n";
598
599  OS << "#ifdef GET_INSTRINFO_HELPER_DECLS\n";
600  OS << "#undef GET_INSTRINFO_HELPER_DECLS\n\n";
601  emitTIIHelperMethods(OS, TargetName, /* ExpandDefintion = */false);
602  OS << "\n";
603  OS << "#endif // GET_INSTRINFO_HELPER_DECLS\n\n";
604
605  OS << "#ifdef GET_INSTRINFO_HELPERS\n";
606  OS << "#undef GET_INSTRINFO_HELPERS\n\n";
607  emitTIIHelperMethods(OS, TargetName, /* ExpandDefintion = */true);
608  OS << "#endif // GET_INSTRINFO_HELPERS\n\n";
609
610  OS << "#ifdef GET_INSTRINFO_CTOR_DTOR\n";
611  OS << "#undef GET_INSTRINFO_CTOR_DTOR\n";
612
613  OS << "namespace llvm {\n";
614  OS << "extern const MCInstrDesc " << TargetName << "Insts[];\n";
615  OS << "extern const unsigned " << TargetName << "InstrNameIndices[];\n";
616  OS << "extern const char " << TargetName << "InstrNameData[];\n";
617  OS << ClassName << "::" << ClassName
618     << "(int CFSetupOpcode, int CFDestroyOpcode, int CatchRetOpcode, int ReturnOpcode)\n"
619     << "  : TargetInstrInfo(CFSetupOpcode, CFDestroyOpcode, CatchRetOpcode, ReturnOpcode) {\n"
620     << "  InitMCInstrInfo(" << TargetName << "Insts, " << TargetName
621     << "InstrNameIndices, " << TargetName << "InstrNameData, "
622     << NumberedInstructions.size() << ");\n}\n";
623  OS << "} // end llvm namespace\n";
624
625  OS << "#endif // GET_INSTRINFO_CTOR_DTOR\n\n";
626
627  emitOperandNameMappings(OS, Target, NumberedInstructions);
628
629  emitOperandTypeMappings(OS, Target, NumberedInstructions);
630
631  emitMCIIHelperMethods(OS, TargetName);
632}
633
634void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
635                                  Record *InstrInfo,
636                         std::map<std::vector<Record*>, unsigned> &EmittedLists,
637                                  const OperandInfoMapTy &OpInfo,
638                                  raw_ostream &OS) {
639  int MinOperands = 0;
640  if (!Inst.Operands.empty())
641    // Each logical operand can be multiple MI operands.
642    MinOperands = Inst.Operands.back().MIOperandNo +
643                  Inst.Operands.back().MINumOperands;
644
645  OS << "  { ";
646  OS << Num << ",\t" << MinOperands << ",\t"
647     << Inst.Operands.NumDefs << ",\t"
648     << Inst.TheDef->getValueAsInt("Size") << ",\t"
649     << SchedModels.getSchedClassIdx(Inst) << ",\t0";
650
651  CodeGenTarget &Target = CDP.getTargetInfo();
652
653  // Emit all of the target independent flags...
654  if (Inst.isPseudo)           OS << "|(1ULL<<MCID::Pseudo)";
655  if (Inst.isReturn)           OS << "|(1ULL<<MCID::Return)";
656  if (Inst.isEHScopeReturn)    OS << "|(1ULL<<MCID::EHScopeReturn)";
657  if (Inst.isBranch)           OS << "|(1ULL<<MCID::Branch)";
658  if (Inst.isIndirectBranch)   OS << "|(1ULL<<MCID::IndirectBranch)";
659  if (Inst.isCompare)          OS << "|(1ULL<<MCID::Compare)";
660  if (Inst.isMoveImm)          OS << "|(1ULL<<MCID::MoveImm)";
661  if (Inst.isMoveReg)          OS << "|(1ULL<<MCID::MoveReg)";
662  if (Inst.isBitcast)          OS << "|(1ULL<<MCID::Bitcast)";
663  if (Inst.isAdd)              OS << "|(1ULL<<MCID::Add)";
664  if (Inst.isTrap)             OS << "|(1ULL<<MCID::Trap)";
665  if (Inst.isSelect)           OS << "|(1ULL<<MCID::Select)";
666  if (Inst.isBarrier)          OS << "|(1ULL<<MCID::Barrier)";
667  if (Inst.hasDelaySlot)       OS << "|(1ULL<<MCID::DelaySlot)";
668  if (Inst.isCall)             OS << "|(1ULL<<MCID::Call)";
669  if (Inst.canFoldAsLoad)      OS << "|(1ULL<<MCID::FoldableAsLoad)";
670  if (Inst.mayLoad)            OS << "|(1ULL<<MCID::MayLoad)";
671  if (Inst.mayStore)           OS << "|(1ULL<<MCID::MayStore)";
672  if (Inst.mayRaiseFPException) OS << "|(1ULL<<MCID::MayRaiseFPException)";
673  if (Inst.isPredicable)       OS << "|(1ULL<<MCID::Predicable)";
674  if (Inst.isConvertibleToThreeAddress) OS << "|(1ULL<<MCID::ConvertibleTo3Addr)";
675  if (Inst.isCommutable)       OS << "|(1ULL<<MCID::Commutable)";
676  if (Inst.isTerminator)       OS << "|(1ULL<<MCID::Terminator)";
677  if (Inst.isReMaterializable) OS << "|(1ULL<<MCID::Rematerializable)";
678  if (Inst.isNotDuplicable)    OS << "|(1ULL<<MCID::NotDuplicable)";
679  if (Inst.Operands.hasOptionalDef) OS << "|(1ULL<<MCID::HasOptionalDef)";
680  if (Inst.usesCustomInserter) OS << "|(1ULL<<MCID::UsesCustomInserter)";
681  if (Inst.hasPostISelHook)    OS << "|(1ULL<<MCID::HasPostISelHook)";
682  if (Inst.Operands.isVariadic)OS << "|(1ULL<<MCID::Variadic)";
683  if (Inst.hasSideEffects)     OS << "|(1ULL<<MCID::UnmodeledSideEffects)";
684  if (Inst.isAsCheapAsAMove)   OS << "|(1ULL<<MCID::CheapAsAMove)";
685  if (!Target.getAllowRegisterRenaming() || Inst.hasExtraSrcRegAllocReq)
686    OS << "|(1ULL<<MCID::ExtraSrcRegAllocReq)";
687  if (!Target.getAllowRegisterRenaming() || Inst.hasExtraDefRegAllocReq)
688    OS << "|(1ULL<<MCID::ExtraDefRegAllocReq)";
689  if (Inst.isRegSequence) OS << "|(1ULL<<MCID::RegSequence)";
690  if (Inst.isExtractSubreg) OS << "|(1ULL<<MCID::ExtractSubreg)";
691  if (Inst.isInsertSubreg) OS << "|(1ULL<<MCID::InsertSubreg)";
692  if (Inst.isConvergent) OS << "|(1ULL<<MCID::Convergent)";
693  if (Inst.variadicOpsAreDefs) OS << "|(1ULL<<MCID::VariadicOpsAreDefs)";
694
695  // Emit all of the target-specific flags...
696  BitsInit *TSF = Inst.TheDef->getValueAsBitsInit("TSFlags");
697  if (!TSF)
698    PrintFatalError(Inst.TheDef->getLoc(), "no TSFlags?");
699  uint64_t Value = 0;
700  for (unsigned i = 0, e = TSF->getNumBits(); i != e; ++i) {
701    if (const auto *Bit = dyn_cast<BitInit>(TSF->getBit(i)))
702      Value |= uint64_t(Bit->getValue()) << i;
703    else
704      PrintFatalError(Inst.TheDef->getLoc(),
705                      "Invalid TSFlags bit in " + Inst.TheDef->getName());
706  }
707  OS << ", 0x";
708  OS.write_hex(Value);
709  OS << "ULL, ";
710
711  // Emit the implicit uses and defs lists...
712  std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
713  if (UseList.empty())
714    OS << "nullptr, ";
715  else
716    OS << "ImplicitList" << EmittedLists[UseList] << ", ";
717
718  std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
719  if (DefList.empty())
720    OS << "nullptr, ";
721  else
722    OS << "ImplicitList" << EmittedLists[DefList] << ", ";
723
724  // Emit the operand info.
725  std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
726  if (OperandInfo.empty())
727    OS << "nullptr";
728  else
729    OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
730
731  if (Inst.HasComplexDeprecationPredicate)
732    // Emit a function pointer to the complex predicate method.
733    OS << ", -1 "
734       << ",&get" << Inst.DeprecatedReason << "DeprecationInfo";
735  else if (!Inst.DeprecatedReason.empty())
736    // Emit the Subtarget feature.
737    OS << ", " << Target.getInstNamespace() << "::" << Inst.DeprecatedReason
738       << " ,nullptr";
739  else
740    // Instruction isn't deprecated.
741    OS << ", -1 ,nullptr";
742
743  OS << " },  // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
744}
745
746// emitEnums - Print out enum values for all of the instructions.
747void InstrInfoEmitter::emitEnums(raw_ostream &OS) {
748  OS << "#ifdef GET_INSTRINFO_ENUM\n";
749  OS << "#undef GET_INSTRINFO_ENUM\n";
750
751  OS << "namespace llvm {\n\n";
752
753  CodeGenTarget Target(Records);
754
755  // We must emit the PHI opcode first...
756  StringRef Namespace = Target.getInstNamespace();
757
758  if (Namespace.empty())
759    PrintFatalError("No instructions defined!");
760
761  OS << "namespace " << Namespace << " {\n";
762  OS << "  enum {\n";
763  unsigned Num = 0;
764  for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue())
765    OS << "    " << Inst->TheDef->getName() << "\t= " << Num++ << ",\n";
766  OS << "    INSTRUCTION_LIST_END = " << Num << "\n";
767  OS << "  };\n\n";
768  OS << "} // end " << Namespace << " namespace\n";
769  OS << "} // end llvm namespace\n";
770  OS << "#endif // GET_INSTRINFO_ENUM\n\n";
771
772  OS << "#ifdef GET_INSTRINFO_SCHED_ENUM\n";
773  OS << "#undef GET_INSTRINFO_SCHED_ENUM\n";
774  OS << "namespace llvm {\n\n";
775  OS << "namespace " << Namespace << " {\n";
776  OS << "namespace Sched {\n";
777  OS << "  enum {\n";
778  Num = 0;
779  for (const auto &Class : SchedModels.explicit_classes())
780    OS << "    " << Class.Name << "\t= " << Num++ << ",\n";
781  OS << "    SCHED_LIST_END = " << Num << "\n";
782  OS << "  };\n";
783  OS << "} // end Sched namespace\n";
784  OS << "} // end " << Namespace << " namespace\n";
785  OS << "} // end llvm namespace\n";
786
787  OS << "#endif // GET_INSTRINFO_SCHED_ENUM\n\n";
788}
789
790namespace llvm {
791
792void EmitInstrInfo(RecordKeeper &RK, raw_ostream &OS) {
793  InstrInfoEmitter(RK).run(OS);
794  EmitMapTable(RK, OS);
795}
796
797} // end llvm namespace
798