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