InstrInfoEmitter.cpp revision becdf4d7cd0d5a3079339b6e177066b143d2f84c
1//===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend is responsible for emitting a description of the target
11// instruction set for the code generator.
12//
13//===----------------------------------------------------------------------===//
14
15
16#include "CodeGenDAGPatterns.h"
17#include "CodeGenSchedule.h"
18#include "CodeGenTarget.h"
19#include "TableGenBackends.h"
20#include "SequenceToOffsetTable.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/TableGen/Record.h"
23#include "llvm/TableGen/TableGenBackend.h"
24#include <algorithm>
25#include <cstdio>
26#include <map>
27#include <vector>
28using namespace llvm;
29
30namespace {
31class InstrInfoEmitter {
32  RecordKeeper &Records;
33  CodeGenDAGPatterns CDP;
34  const CodeGenSchedModels &SchedModels;
35
36public:
37  InstrInfoEmitter(RecordKeeper &R):
38    Records(R), CDP(R), SchedModels(CDP.getTargetInfo().getSchedModels()) {}
39
40  // run - Output the instruction set description.
41  void run(raw_ostream &OS);
42
43private:
44  void emitEnums(raw_ostream &OS);
45
46  typedef std::map<std::vector<std::string>, unsigned> OperandInfoMapTy;
47  void emitRecord(const CodeGenInstruction &Inst, unsigned Num,
48                  Record *InstrInfo,
49                  std::map<std::vector<Record*>, unsigned> &EL,
50                  const OperandInfoMapTy &OpInfo,
51                  raw_ostream &OS);
52
53  // Operand information.
54  void EmitOperandInfo(raw_ostream &OS, OperandInfoMapTy &OperandInfoIDs);
55  std::vector<std::string> GetOperandInfo(const CodeGenInstruction &Inst);
56};
57} // End anonymous namespace
58
59static void PrintDefList(const std::vector<Record*> &Uses,
60                         unsigned Num, raw_ostream &OS) {
61  OS << "static const uint16_t ImplicitList" << Num << "[] = { ";
62  for (unsigned i = 0, e = Uses.size(); i != e; ++i)
63    OS << getQualifiedName(Uses[i]) << ", ";
64  OS << "0 };\n";
65}
66
67//===----------------------------------------------------------------------===//
68// Operand Info Emission.
69//===----------------------------------------------------------------------===//
70
71std::vector<std::string>
72InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
73  std::vector<std::string> Result;
74
75  for (unsigned i = 0, e = Inst.Operands.size(); i != e; ++i) {
76    // Handle aggregate operands and normal operands the same way by expanding
77    // either case into a list of operands for this op.
78    std::vector<CGIOperandList::OperandInfo> OperandList;
79
80    // This might be a multiple operand thing.  Targets like X86 have
81    // registers in their multi-operand operands.  It may also be an anonymous
82    // operand, which has a single operand, but no declared class for the
83    // operand.
84    DagInit *MIOI = Inst.Operands[i].MIOperandInfo;
85
86    if (!MIOI || MIOI->getNumArgs() == 0) {
87      // Single, anonymous, operand.
88      OperandList.push_back(Inst.Operands[i]);
89    } else {
90      for (unsigned j = 0, e = Inst.Operands[i].MINumOperands; j != e; ++j) {
91        OperandList.push_back(Inst.Operands[i]);
92
93        Record *OpR = cast<DefInit>(MIOI->getArg(j))->getDef();
94        OperandList.back().Rec = OpR;
95      }
96    }
97
98    for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
99      Record *OpR = OperandList[j].Rec;
100      std::string Res;
101
102      if (OpR->isSubClassOf("RegisterOperand"))
103        OpR = OpR->getValueAsDef("RegClass");
104      if (OpR->isSubClassOf("RegisterClass"))
105        Res += getQualifiedName(OpR) + "RegClassID, ";
106      else if (OpR->isSubClassOf("PointerLikeRegClass"))
107        Res += utostr(OpR->getValueAsInt("RegClassKind")) + ", ";
108      else
109        // -1 means the operand does not have a fixed register class.
110        Res += "-1, ";
111
112      // Fill in applicable flags.
113      Res += "0";
114
115      // Ptr value whose register class is resolved via callback.
116      if (OpR->isSubClassOf("PointerLikeRegClass"))
117        Res += "|(1<<MCOI::LookupPtrRegClass)";
118
119      // Predicate operands.  Check to see if the original unexpanded operand
120      // was of type PredicateOperand.
121      if (Inst.Operands[i].Rec->isSubClassOf("PredicateOperand"))
122        Res += "|(1<<MCOI::Predicate)";
123
124      // Optional def operands.  Check to see if the original unexpanded operand
125      // was of type OptionalDefOperand.
126      if (Inst.Operands[i].Rec->isSubClassOf("OptionalDefOperand"))
127        Res += "|(1<<MCOI::OptionalDef)";
128
129      // Fill in operand type.
130      Res += ", MCOI::";
131      assert(!Inst.Operands[i].OperandType.empty() && "Invalid operand type.");
132      Res += Inst.Operands[i].OperandType;
133
134      // Fill in constraint info.
135      Res += ", ";
136
137      const CGIOperandList::ConstraintInfo &Constraint =
138        Inst.Operands[i].Constraints[j];
139      if (Constraint.isNone())
140        Res += "0";
141      else if (Constraint.isEarlyClobber())
142        Res += "(1 << MCOI::EARLY_CLOBBER)";
143      else {
144        assert(Constraint.isTied());
145        Res += "((" + utostr(Constraint.getTiedOperand()) +
146                    " << 16) | (1 << MCOI::TIED_TO))";
147      }
148
149      Result.push_back(Res);
150    }
151  }
152
153  return Result;
154}
155
156void InstrInfoEmitter::EmitOperandInfo(raw_ostream &OS,
157                                       OperandInfoMapTy &OperandInfoIDs) {
158  // ID #0 is for no operand info.
159  unsigned OperandListNum = 0;
160  OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
161
162  OS << "\n";
163  const CodeGenTarget &Target = CDP.getTargetInfo();
164  for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
165       E = Target.inst_end(); II != E; ++II) {
166    std::vector<std::string> OperandInfo = GetOperandInfo(**II);
167    unsigned &N = OperandInfoIDs[OperandInfo];
168    if (N != 0) continue;
169
170    N = ++OperandListNum;
171    OS << "static const MCOperandInfo OperandInfo" << N << "[] = { ";
172    for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
173      OS << "{ " << OperandInfo[i] << " }, ";
174    OS << "};\n";
175  }
176}
177
178//===----------------------------------------------------------------------===//
179// Main Output.
180//===----------------------------------------------------------------------===//
181
182// run - Emit the main instruction description records for the target...
183void InstrInfoEmitter::run(raw_ostream &OS) {
184  emitSourceFileHeader("Target Instruction Enum Values", OS);
185  emitEnums(OS);
186
187  emitSourceFileHeader("Target Instruction Descriptors", OS);
188
189  OS << "\n#ifdef GET_INSTRINFO_MC_DESC\n";
190  OS << "#undef GET_INSTRINFO_MC_DESC\n";
191
192  OS << "namespace llvm {\n\n";
193
194  CodeGenTarget &Target = CDP.getTargetInfo();
195  const std::string &TargetName = Target.getName();
196  Record *InstrInfo = Target.getInstructionSet();
197
198  // Keep track of all of the def lists we have emitted already.
199  std::map<std::vector<Record*>, unsigned> EmittedLists;
200  unsigned ListNumber = 0;
201
202  // Emit all of the instruction's implicit uses and defs.
203  for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
204         E = Target.inst_end(); II != E; ++II) {
205    Record *Inst = (*II)->TheDef;
206    std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
207    if (!Uses.empty()) {
208      unsigned &IL = EmittedLists[Uses];
209      if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
210    }
211    std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
212    if (!Defs.empty()) {
213      unsigned &IL = EmittedLists[Defs];
214      if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
215    }
216  }
217
218  OperandInfoMapTy OperandInfoIDs;
219
220  // Emit all of the operand info records.
221  EmitOperandInfo(OS, OperandInfoIDs);
222
223  // Emit all of the MCInstrDesc records in their ENUM ordering.
224  //
225  OS << "\nextern const MCInstrDesc " << TargetName << "Insts[] = {\n";
226  const std::vector<const CodeGenInstruction*> &NumberedInstructions =
227    Target.getInstructionsByEnumValue();
228
229  for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
230    emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
231               OperandInfoIDs, OS);
232  OS << "};\n\n";
233
234  // Build an array of instruction names
235  SequenceToOffsetTable<std::string> InstrNames;
236  for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
237    const CodeGenInstruction *Instr = NumberedInstructions[i];
238    InstrNames.add(Instr->TheDef->getName());
239  }
240
241  InstrNames.layout();
242  OS << "extern const char " << TargetName << "InstrNameData[] = {\n";
243  InstrNames.emit(OS, printChar);
244  OS << "};\n\n";
245
246  OS << "extern const unsigned " << TargetName <<"InstrNameIndices[] = {";
247  for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
248    if (i % 8 == 0)
249      OS << "\n    ";
250    const CodeGenInstruction *Instr = NumberedInstructions[i];
251    OS << InstrNames.get(Instr->TheDef->getName()) << "U, ";
252  }
253
254  OS << "\n};\n\n";
255
256  // MCInstrInfo initialization routine.
257  OS << "static inline void Init" << TargetName
258     << "MCInstrInfo(MCInstrInfo *II) {\n";
259  OS << "  II->InitMCInstrInfo(" << TargetName << "Insts, "
260     << TargetName << "InstrNameIndices, " << TargetName << "InstrNameData, "
261     << NumberedInstructions.size() << ");\n}\n\n";
262
263  OS << "} // End llvm namespace \n";
264
265  OS << "#endif // GET_INSTRINFO_MC_DESC\n\n";
266
267  // Create a TargetInstrInfo subclass to hide the MC layer initialization.
268  OS << "\n#ifdef GET_INSTRINFO_HEADER\n";
269  OS << "#undef GET_INSTRINFO_HEADER\n";
270
271  std::string ClassName = TargetName + "GenInstrInfo";
272  OS << "namespace llvm {\n";
273  OS << "struct " << ClassName << " : public TargetInstrInfoImpl {\n"
274     << "  explicit " << ClassName << "(int SO = -1, int DO = -1);\n"
275     << "};\n";
276  OS << "} // End llvm namespace \n";
277
278  OS << "#endif // GET_INSTRINFO_HEADER\n\n";
279
280  OS << "\n#ifdef GET_INSTRINFO_CTOR\n";
281  OS << "#undef GET_INSTRINFO_CTOR\n";
282
283  OS << "namespace llvm {\n";
284  OS << "extern const MCInstrDesc " << TargetName << "Insts[];\n";
285  OS << "extern const unsigned " << TargetName << "InstrNameIndices[];\n";
286  OS << "extern const char " << TargetName << "InstrNameData[];\n";
287  OS << ClassName << "::" << ClassName << "(int SO, int DO)\n"
288     << "  : TargetInstrInfoImpl(SO, DO) {\n"
289     << "  InitMCInstrInfo(" << TargetName << "Insts, "
290     << TargetName << "InstrNameIndices, " << TargetName << "InstrNameData, "
291     << NumberedInstructions.size() << ");\n}\n";
292  OS << "} // End llvm namespace \n";
293
294  OS << "#endif // GET_INSTRINFO_CTOR\n\n";
295}
296
297void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
298                                  Record *InstrInfo,
299                         std::map<std::vector<Record*>, unsigned> &EmittedLists,
300                                  const OperandInfoMapTy &OpInfo,
301                                  raw_ostream &OS) {
302  int MinOperands = 0;
303  if (!Inst.Operands.empty())
304    // Each logical operand can be multiple MI operands.
305    MinOperands = Inst.Operands.back().MIOperandNo +
306                  Inst.Operands.back().MINumOperands;
307
308  OS << "  { ";
309  OS << Num << ",\t" << MinOperands << ",\t"
310     << Inst.Operands.NumDefs << ",\t"
311     << SchedModels.getSchedClassIdx(Inst) << ",\t"
312     << Inst.TheDef->getValueAsInt("Size") << ",\t0";
313
314  // Emit all of the target indepedent flags...
315  if (Inst.isPseudo)           OS << "|(1<<MCID::Pseudo)";
316  if (Inst.isReturn)           OS << "|(1<<MCID::Return)";
317  if (Inst.isBranch)           OS << "|(1<<MCID::Branch)";
318  if (Inst.isIndirectBranch)   OS << "|(1<<MCID::IndirectBranch)";
319  if (Inst.isCompare)          OS << "|(1<<MCID::Compare)";
320  if (Inst.isMoveImm)          OS << "|(1<<MCID::MoveImm)";
321  if (Inst.isBitcast)          OS << "|(1<<MCID::Bitcast)";
322  if (Inst.isSelect)           OS << "|(1<<MCID::Select)";
323  if (Inst.isBarrier)          OS << "|(1<<MCID::Barrier)";
324  if (Inst.hasDelaySlot)       OS << "|(1<<MCID::DelaySlot)";
325  if (Inst.isCall)             OS << "|(1<<MCID::Call)";
326  if (Inst.canFoldAsLoad)      OS << "|(1<<MCID::FoldableAsLoad)";
327  if (Inst.mayLoad)            OS << "|(1<<MCID::MayLoad)";
328  if (Inst.mayStore)           OS << "|(1<<MCID::MayStore)";
329  if (Inst.isPredicable)       OS << "|(1<<MCID::Predicable)";
330  if (Inst.isConvertibleToThreeAddress) OS << "|(1<<MCID::ConvertibleTo3Addr)";
331  if (Inst.isCommutable)       OS << "|(1<<MCID::Commutable)";
332  if (Inst.isTerminator)       OS << "|(1<<MCID::Terminator)";
333  if (Inst.isReMaterializable) OS << "|(1<<MCID::Rematerializable)";
334  if (Inst.isNotDuplicable)    OS << "|(1<<MCID::NotDuplicable)";
335  if (Inst.Operands.hasOptionalDef) OS << "|(1<<MCID::HasOptionalDef)";
336  if (Inst.usesCustomInserter) OS << "|(1<<MCID::UsesCustomInserter)";
337  if (Inst.hasPostISelHook)    OS << "|(1<<MCID::HasPostISelHook)";
338  if (Inst.Operands.isVariadic)OS << "|(1<<MCID::Variadic)";
339  if (Inst.hasSideEffects)     OS << "|(1<<MCID::UnmodeledSideEffects)";
340  if (Inst.isAsCheapAsAMove)   OS << "|(1<<MCID::CheapAsAMove)";
341  if (Inst.hasExtraSrcRegAllocReq) OS << "|(1<<MCID::ExtraSrcRegAllocReq)";
342  if (Inst.hasExtraDefRegAllocReq) OS << "|(1<<MCID::ExtraDefRegAllocReq)";
343
344  // Emit all of the target-specific flags...
345  BitsInit *TSF = Inst.TheDef->getValueAsBitsInit("TSFlags");
346  if (!TSF) throw "no TSFlags?";
347  uint64_t Value = 0;
348  for (unsigned i = 0, e = TSF->getNumBits(); i != e; ++i) {
349    if (BitInit *Bit = dyn_cast<BitInit>(TSF->getBit(i)))
350      Value |= uint64_t(Bit->getValue()) << i;
351    else
352      throw "Invalid TSFlags bit in " + Inst.TheDef->getName();
353  }
354  OS << ", 0x";
355  OS.write_hex(Value);
356  OS << "ULL, ";
357
358  // Emit the implicit uses and defs lists...
359  std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
360  if (UseList.empty())
361    OS << "NULL, ";
362  else
363    OS << "ImplicitList" << EmittedLists[UseList] << ", ";
364
365  std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
366  if (DefList.empty())
367    OS << "NULL, ";
368  else
369    OS << "ImplicitList" << EmittedLists[DefList] << ", ";
370
371  // Emit the operand info.
372  std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
373  if (OperandInfo.empty())
374    OS << "0";
375  else
376    OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
377
378  OS << " },  // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
379}
380
381// emitEnums - Print out enum values for all of the instructions.
382void InstrInfoEmitter::emitEnums(raw_ostream &OS) {
383
384  OS << "\n#ifdef GET_INSTRINFO_ENUM\n";
385  OS << "#undef GET_INSTRINFO_ENUM\n";
386
387  OS << "namespace llvm {\n\n";
388
389  CodeGenTarget Target(Records);
390
391  // We must emit the PHI opcode first...
392  std::string Namespace = Target.getInstNamespace();
393
394  if (Namespace.empty()) {
395    fprintf(stderr, "No instructions defined!\n");
396    exit(1);
397  }
398
399  const std::vector<const CodeGenInstruction*> &NumberedInstructions =
400    Target.getInstructionsByEnumValue();
401
402  OS << "namespace " << Namespace << " {\n";
403  OS << "  enum {\n";
404  for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
405    OS << "    " << NumberedInstructions[i]->TheDef->getName()
406       << "\t= " << i << ",\n";
407  }
408  OS << "    INSTRUCTION_LIST_END = " << NumberedInstructions.size() << "\n";
409  OS << "  };\n}\n";
410  OS << "} // End llvm namespace \n";
411
412  OS << "#endif // GET_INSTRINFO_ENUM\n\n";
413}
414
415namespace llvm {
416
417void EmitInstrInfo(RecordKeeper &RK, raw_ostream &OS) {
418  InstrInfoEmitter(RK).run(OS);
419  EmitMapTable(RK, OS);
420}
421
422} // End llvm namespace
423