InstrInfoEmitter.cpp revision e14d2e210dc7fe28009f44818a057622a73322e4
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#include "InstrInfoEmitter.h"
16#include "CodeGenTarget.h"
17#include "Record.h"
18#include "llvm/ADT/StringExtras.h"
19#include <algorithm>
20using namespace llvm;
21
22static void PrintDefList(const std::vector<Record*> &Uses,
23                         unsigned Num, raw_ostream &OS) {
24  OS << "static const unsigned ImplicitList" << Num << "[] = { ";
25  for (unsigned i = 0, e = Uses.size(); i != e; ++i)
26    OS << getQualifiedName(Uses[i]) << ", ";
27  OS << "0 };\n";
28}
29
30static void PrintBarriers(std::vector<Record*> &Barriers,
31                          unsigned Num, raw_ostream &OS) {
32  OS << "static const TargetRegisterClass* Barriers" << Num << "[] = { ";
33  for (unsigned i = 0, e = Barriers.size(); i != e; ++i)
34    OS << "&" << getQualifiedName(Barriers[i]) << "RegClass, ";
35  OS << "NULL };\n";
36}
37
38//===----------------------------------------------------------------------===//
39// Instruction Itinerary Information.
40//===----------------------------------------------------------------------===//
41
42void InstrInfoEmitter::GatherItinClasses() {
43  std::vector<Record*> DefList =
44  Records.getAllDerivedDefinitions("InstrItinClass");
45  std::sort(DefList.begin(), DefList.end(), LessRecord());
46
47  for (unsigned i = 0, N = DefList.size(); i < N; i++)
48    ItinClassMap[DefList[i]->getName()] = i;
49}
50
51unsigned InstrInfoEmitter::getItinClassNumber(const Record *InstRec) {
52  return ItinClassMap[InstRec->getValueAsDef("Itinerary")->getName()];
53}
54
55//===----------------------------------------------------------------------===//
56// Operand Info Emission.
57//===----------------------------------------------------------------------===//
58
59std::vector<std::string>
60InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
61  std::vector<std::string> Result;
62
63  for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {
64    // Handle aggregate operands and normal operands the same way by expanding
65    // either case into a list of operands for this op.
66    std::vector<CodeGenInstruction::OperandInfo> OperandList;
67
68    // This might be a multiple operand thing.  Targets like X86 have
69    // registers in their multi-operand operands.  It may also be an anonymous
70    // operand, which has a single operand, but no declared class for the
71    // operand.
72    DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;
73
74    if (!MIOI || MIOI->getNumArgs() == 0) {
75      // Single, anonymous, operand.
76      OperandList.push_back(Inst.OperandList[i]);
77    } else {
78      for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {
79        OperandList.push_back(Inst.OperandList[i]);
80
81        Record *OpR = dynamic_cast<DefInit*>(MIOI->getArg(j))->getDef();
82        OperandList.back().Rec = OpR;
83      }
84    }
85
86    for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
87      Record *OpR = OperandList[j].Rec;
88      std::string Res;
89
90      if (OpR->isSubClassOf("RegisterClass"))
91        Res += getQualifiedName(OpR) + "RegClassID, ";
92      else if (OpR->isSubClassOf("PointerLikeRegClass"))
93        Res += utostr(OpR->getValueAsInt("RegClassKind")) + ", ";
94      else
95        Res += "0, ";
96
97      // Fill in applicable flags.
98      Res += "0";
99
100      // Ptr value whose register class is resolved via callback.
101      if (OpR->isSubClassOf("PointerLikeRegClass"))
102        Res += "|(1<<TOI::LookupPtrRegClass)";
103
104      // Predicate operands.  Check to see if the original unexpanded operand
105      // was of type PredicateOperand.
106      if (Inst.OperandList[i].Rec->isSubClassOf("PredicateOperand"))
107        Res += "|(1<<TOI::Predicate)";
108
109      // Optional def operands.  Check to see if the original unexpanded operand
110      // was of type OptionalDefOperand.
111      if (Inst.OperandList[i].Rec->isSubClassOf("OptionalDefOperand"))
112        Res += "|(1<<TOI::OptionalDef)";
113
114      // Fill in constraint info.
115      Res += ", ";
116
117      const CodeGenInstruction::ConstraintInfo &Constraint =
118        Inst.OperandList[i].Constraints[j];
119      if (Constraint.isNone())
120        Res += "0";
121      else if (Constraint.isEarlyClobber())
122        Res += "(1 << TOI::EARLY_CLOBBER)";
123      else {
124        assert(Constraint.isTied());
125        Res += "((" + utostr(Constraint.getTiedOperand()) +
126                    " << 16) | (1 << TOI::TIED_TO))";
127      }
128
129      Result.push_back(Res);
130    }
131  }
132
133  return Result;
134}
135
136void InstrInfoEmitter::EmitOperandInfo(raw_ostream &OS,
137                                       OperandInfoMapTy &OperandInfoIDs) {
138  // ID #0 is for no operand info.
139  unsigned OperandListNum = 0;
140  OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
141
142  OS << "\n";
143  const CodeGenTarget &Target = CDP.getTargetInfo();
144  for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
145       E = Target.inst_end(); II != E; ++II) {
146    std::vector<std::string> OperandInfo = GetOperandInfo(**II);
147    unsigned &N = OperandInfoIDs[OperandInfo];
148    if (N != 0) continue;
149
150    N = ++OperandListNum;
151    OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { ";
152    for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
153      OS << "{ " << OperandInfo[i] << " }, ";
154    OS << "};\n";
155  }
156}
157
158void InstrInfoEmitter::DetectRegisterClassBarriers(std::vector<Record*> &Defs,
159                                  const std::vector<CodeGenRegisterClass> &RCs,
160                                  std::vector<Record*> &Barriers) {
161  std::set<Record*> DefSet;
162  unsigned NumDefs = Defs.size();
163  for (unsigned i = 0; i < NumDefs; ++i)
164    DefSet.insert(Defs[i]);
165
166  for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
167    const CodeGenRegisterClass &RC = RCs[i];
168    unsigned NumRegs = RC.Elements.size();
169    if (NumRegs > NumDefs)
170      continue; // Can't possibly clobber this RC.
171
172    bool Clobber = true;
173    for (unsigned j = 0; j < NumRegs; ++j) {
174      Record *Reg = RC.Elements[j];
175      if (!DefSet.count(Reg)) {
176        Clobber = false;
177        break;
178      }
179    }
180    if (Clobber)
181      Barriers.push_back(RC.TheDef);
182  }
183}
184
185//===----------------------------------------------------------------------===//
186// Main Output.
187//===----------------------------------------------------------------------===//
188
189// run - Emit the main instruction description records for the target...
190void InstrInfoEmitter::run(raw_ostream &OS) {
191  GatherItinClasses();
192
193  EmitSourceFileHeader("Target Instruction Descriptors", OS);
194  OS << "namespace llvm {\n\n";
195
196  CodeGenTarget &Target = CDP.getTargetInfo();
197  const std::string &TargetName = Target.getName();
198  Record *InstrInfo = Target.getInstructionSet();
199  const std::vector<CodeGenRegisterClass> &RCs = Target.getRegisterClasses();
200
201  // Keep track of all of the def lists we have emitted already.
202  std::map<std::vector<Record*>, unsigned> EmittedLists;
203  unsigned ListNumber = 0;
204  std::map<std::vector<Record*>, unsigned> EmittedBarriers;
205  unsigned BarrierNumber = 0;
206  std::map<Record*, unsigned> BarriersMap;
207
208  // Emit all of the instruction's implicit uses and defs.
209  for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
210         E = Target.inst_end(); II != E; ++II) {
211    Record *Inst = (*II)->TheDef;
212    std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
213    if (!Uses.empty()) {
214      unsigned &IL = EmittedLists[Uses];
215      if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
216    }
217    std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
218    if (!Defs.empty()) {
219      std::vector<Record*> RCBarriers;
220      DetectRegisterClassBarriers(Defs, RCs, RCBarriers);
221      if (!RCBarriers.empty()) {
222        unsigned &IB = EmittedBarriers[RCBarriers];
223        if (!IB) PrintBarriers(RCBarriers, IB = ++BarrierNumber, OS);
224        BarriersMap.insert(std::make_pair(Inst, IB));
225      }
226
227      unsigned &IL = EmittedLists[Defs];
228      if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
229    }
230  }
231
232  OperandInfoMapTy OperandInfoIDs;
233
234  // Emit all of the operand info records.
235  EmitOperandInfo(OS, OperandInfoIDs);
236
237  // Emit all of the TargetInstrDesc records in their ENUM ordering.
238  //
239  OS << "\nstatic const TargetInstrDesc " << TargetName
240     << "Insts[] = {\n";
241  const std::vector<const CodeGenInstruction*> &NumberedInstructions =
242    Target.getInstructionsByEnumValue();
243
244  for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
245    emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
246               BarriersMap, OperandInfoIDs, OS);
247  OS << "};\n";
248  OS << "} // End llvm namespace \n";
249}
250
251void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
252                                  Record *InstrInfo,
253                         std::map<std::vector<Record*>, unsigned> &EmittedLists,
254                                  std::map<Record*, unsigned> &BarriersMap,
255                                  const OperandInfoMapTy &OpInfo,
256                                  raw_ostream &OS) {
257  int MinOperands = 0;
258  if (!Inst.OperandList.empty())
259    // Each logical operand can be multiple MI operands.
260    MinOperands = Inst.OperandList.back().MIOperandNo +
261                  Inst.OperandList.back().MINumOperands;
262
263  OS << "  { ";
264  OS << Num << ",\t" << MinOperands << ",\t"
265     << Inst.NumDefs << ",\t" << getItinClassNumber(Inst.TheDef)
266     << ",\t\"" << Inst.TheDef->getName() << "\", 0";
267
268  // Emit all of the target indepedent flags...
269  if (Inst.isReturn)           OS << "|(1<<TID::Return)";
270  if (Inst.isBranch)           OS << "|(1<<TID::Branch)";
271  if (Inst.isIndirectBranch)   OS << "|(1<<TID::IndirectBranch)";
272  if (Inst.isBarrier)          OS << "|(1<<TID::Barrier)";
273  if (Inst.hasDelaySlot)       OS << "|(1<<TID::DelaySlot)";
274  if (Inst.isCall)             OS << "|(1<<TID::Call)";
275  if (Inst.canFoldAsLoad)      OS << "|(1<<TID::FoldableAsLoad)";
276  if (Inst.mayLoad)            OS << "|(1<<TID::MayLoad)";
277  if (Inst.mayStore)           OS << "|(1<<TID::MayStore)";
278  if (Inst.isPredicable)       OS << "|(1<<TID::Predicable)";
279  if (Inst.isConvertibleToThreeAddress) OS << "|(1<<TID::ConvertibleTo3Addr)";
280  if (Inst.isCommutable)       OS << "|(1<<TID::Commutable)";
281  if (Inst.isTerminator)       OS << "|(1<<TID::Terminator)";
282  if (Inst.isReMaterializable) OS << "|(1<<TID::Rematerializable)";
283  if (Inst.isNotDuplicable)    OS << "|(1<<TID::NotDuplicable)";
284  if (Inst.hasOptionalDef)     OS << "|(1<<TID::HasOptionalDef)";
285  if (Inst.usesCustomInserter) OS << "|(1<<TID::UsesCustomInserter)";
286  if (Inst.isVariadic)         OS << "|(1<<TID::Variadic)";
287  if (Inst.hasSideEffects)     OS << "|(1<<TID::UnmodeledSideEffects)";
288  if (Inst.isAsCheapAsAMove)   OS << "|(1<<TID::CheapAsAMove)";
289  if (Inst.hasExtraSrcRegAllocReq) OS << "|(1<<TID::ExtraSrcRegAllocReq)";
290  if (Inst.hasExtraDefRegAllocReq) OS << "|(1<<TID::ExtraDefRegAllocReq)";
291  OS << ", 0";
292
293  // Emit all of the target-specific flags...
294  ListInit *LI    = InstrInfo->getValueAsListInit("TSFlagsFields");
295  ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts");
296  if (LI->getSize() != Shift->getSize())
297    throw "Lengths of " + InstrInfo->getName() +
298          ":(TargetInfoFields, TargetInfoPositions) must be equal!";
299
300  for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
301    emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),
302                     dynamic_cast<IntInit*>(Shift->getElement(i)), OS);
303
304  OS << ", ";
305
306  // Emit the implicit uses and defs lists...
307  std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
308  if (UseList.empty())
309    OS << "NULL, ";
310  else
311    OS << "ImplicitList" << EmittedLists[UseList] << ", ";
312
313  std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
314  if (DefList.empty())
315    OS << "NULL, ";
316  else
317    OS << "ImplicitList" << EmittedLists[DefList] << ", ";
318
319  std::map<Record*, unsigned>::iterator BI = BarriersMap.find(Inst.TheDef);
320  if (BI == BarriersMap.end())
321    OS << "NULL, ";
322  else
323    OS << "Barriers" << BI->second << ", ";
324
325  // Emit the operand info.
326  std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
327  if (OperandInfo.empty())
328    OS << "0";
329  else
330    OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
331
332  OS << " },  // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
333}
334
335
336void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,
337                                        IntInit *ShiftInt, raw_ostream &OS) {
338  if (Val == 0 || ShiftInt == 0)
339    throw std::string("Illegal value or shift amount in TargetInfo*!");
340  RecordVal *RV = R->getValue(Val->getValue());
341  int Shift = ShiftInt->getValue();
342
343  if (RV == 0 || RV->getValue() == 0) {
344    // This isn't an error if this is a builtin instruction.
345    if (R->getName() != "PHI" &&
346        R->getName() != "INLINEASM" &&
347        R->getName() != "DBG_LABEL" &&
348        R->getName() != "EH_LABEL" &&
349        R->getName() != "GC_LABEL" &&
350        R->getName() != "KILL" &&
351        R->getName() != "EXTRACT_SUBREG" &&
352        R->getName() != "INSERT_SUBREG" &&
353        R->getName() != "IMPLICIT_DEF" &&
354        R->getName() != "SUBREG_TO_REG" &&
355        R->getName() != "COPY_TO_REGCLASS" &&
356        R->getName() != "DBG_VALUE")
357      throw R->getName() + " doesn't have a field named '" +
358            Val->getValue() + "'!";
359    return;
360  }
361
362  Init *Value = RV->getValue();
363  if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {
364    if (BI->getValue()) OS << "|(1<<" << Shift << ")";
365    return;
366  } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {
367    // Convert the Bits to an integer to print...
368    Init *I = BI->convertInitializerTo(new IntRecTy());
369    if (I)
370      if (IntInit *II = dynamic_cast<IntInit*>(I)) {
371        if (II->getValue()) {
372          if (Shift)
373            OS << "|(" << II->getValue() << "<<" << Shift << ")";
374          else
375            OS << "|" << II->getValue();
376        }
377        return;
378      }
379
380  } else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {
381    if (II->getValue()) {
382      if (Shift)
383        OS << "|(" << II->getValue() << "<<" << Shift << ")";
384      else
385        OS << II->getValue();
386    }
387    return;
388  }
389
390  errs() << "Unhandled initializer: " << *Val << "\n";
391  throw "In record '" + R->getName() + "' for TSFlag emission.";
392}
393
394