UnXFAIL this test.
[llvm-complete.git] / utils / TableGen / InstrInfoEmitter.cpp
blob5bf25d17451c10eb832f2c9de767afae5ec79a85
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.
13 //===----------------------------------------------------------------------===//
15 #include "InstrInfoEmitter.h"
16 #include "CodeGenTarget.h"
17 #include "Record.h"
18 #include <algorithm>
19 #include <iostream>
20 using namespace llvm;
22 static void PrintDefList(const std::vector<Record*> &Uses,
23 unsigned Num, std::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";
30 //===----------------------------------------------------------------------===//
31 // Instruction Itinerary Information.
32 //===----------------------------------------------------------------------===//
34 struct RecordNameComparator {
35 bool operator()(const Record *Rec1, const Record *Rec2) const {
36 return Rec1->getName() < Rec2->getName();
40 void InstrInfoEmitter::GatherItinClasses() {
41 std::vector<Record*> DefList =
42 Records.getAllDerivedDefinitions("InstrItinClass");
43 std::sort(DefList.begin(), DefList.end(), RecordNameComparator());
45 for (unsigned i = 0, N = DefList.size(); i < N; i++)
46 ItinClassMap[DefList[i]->getName()] = i;
49 unsigned InstrInfoEmitter::getItinClassNumber(const Record *InstRec) {
50 return ItinClassMap[InstRec->getValueAsDef("Itinerary")->getName()];
53 //===----------------------------------------------------------------------===//
54 // Operand Info Emission.
55 //===----------------------------------------------------------------------===//
57 std::vector<std::string>
58 InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
59 std::vector<std::string> Result;
61 for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {
62 // Handle aggregate operands and normal operands the same way by expanding
63 // either case into a list of operands for this op.
64 std::vector<CodeGenInstruction::OperandInfo> OperandList;
66 // This might be a multiple operand thing. Targets like X86 have
67 // registers in their multi-operand operands. It may also be an anonymous
68 // operand, which has a single operand, but no declared class for the
69 // operand.
70 DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;
72 if (!MIOI || MIOI->getNumArgs() == 0) {
73 // Single, anonymous, operand.
74 OperandList.push_back(Inst.OperandList[i]);
75 } else {
76 for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {
77 OperandList.push_back(Inst.OperandList[i]);
79 Record *OpR = dynamic_cast<DefInit*>(MIOI->getArg(j))->getDef();
80 OperandList.back().Rec = OpR;
84 for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
85 Record *OpR = OperandList[j].Rec;
86 std::string Res;
88 if (OpR->isSubClassOf("RegisterClass"))
89 Res += getQualifiedName(OpR) + "RegClassID, ";
90 else
91 Res += "0, ";
92 // Fill in applicable flags.
93 Res += "0";
95 // Ptr value whose register class is resolved via callback.
96 if (OpR->getName() == "ptr_rc")
97 Res += "|(1<<TOI::LookupPtrRegClass)";
99 // Predicate operands. Check to see if the original unexpanded operand
100 // was of type PredicateOperand.
101 if (Inst.OperandList[i].Rec->isSubClassOf("PredicateOperand"))
102 Res += "|(1<<TOI::Predicate)";
104 // Optional def operands. Check to see if the original unexpanded operand
105 // was of type OptionalDefOperand.
106 if (Inst.OperandList[i].Rec->isSubClassOf("OptionalDefOperand"))
107 Res += "|(1<<TOI::OptionalDef)";
109 // Fill in constraint info.
110 Res += ", " + Inst.OperandList[i].Constraints[j];
111 Result.push_back(Res);
115 return Result;
118 void InstrInfoEmitter::EmitOperandInfo(std::ostream &OS,
119 OperandInfoMapTy &OperandInfoIDs) {
120 // ID #0 is for no operand info.
121 unsigned OperandListNum = 0;
122 OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
124 OS << "\n";
125 const CodeGenTarget &Target = CDP.getTargetInfo();
126 for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
127 E = Target.inst_end(); II != E; ++II) {
128 std::vector<std::string> OperandInfo = GetOperandInfo(II->second);
129 unsigned &N = OperandInfoIDs[OperandInfo];
130 if (N != 0) continue;
132 N = ++OperandListNum;
133 OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { ";
134 for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
135 OS << "{ " << OperandInfo[i] << " }, ";
136 OS << "};\n";
140 //===----------------------------------------------------------------------===//
141 // Instruction Analysis
142 //===----------------------------------------------------------------------===//
144 class InstAnalyzer {
145 const CodeGenDAGPatterns &CDP;
146 bool &mayStore;
147 bool &mayLoad;
148 bool &HasSideEffects;
149 public:
150 InstAnalyzer(const CodeGenDAGPatterns &cdp,
151 bool &maystore, bool &mayload, bool &hse)
152 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
155 /// Analyze - Analyze the specified instruction, returning true if the
156 /// instruction had a pattern.
157 bool Analyze(Record *InstRecord) {
158 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
159 if (Pattern == 0) {
160 HasSideEffects = 1;
161 return false; // No pattern.
164 // FIXME: Assume only the first tree is the pattern. The others are clobber
165 // nodes.
166 AnalyzeNode(Pattern->getTree(0));
167 return true;
170 private:
171 void AnalyzeNode(const TreePatternNode *N) {
172 if (N->isLeaf()) {
173 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
174 Record *LeafRec = DI->getDef();
175 // Handle ComplexPattern leaves.
176 if (LeafRec->isSubClassOf("ComplexPattern")) {
177 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
178 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
179 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
180 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
183 return;
186 // Analyze children.
187 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
188 AnalyzeNode(N->getChild(i));
190 // Ignore set nodes, which are not SDNodes.
191 if (N->getOperator()->getName() == "set")
192 return;
194 // Get information about the SDNode for the operator.
195 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
197 // Notice properties of the node.
198 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
199 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
200 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
202 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
203 // If this is an intrinsic, analyze it.
204 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
205 mayLoad = true;// These may load memory.
207 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
208 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
210 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
211 // WriteMem intrinsics can have other strange effects.
212 HasSideEffects = true;
218 void InstrInfoEmitter::InferFromPattern(const CodeGenInstruction &Inst,
219 bool &MayStore, bool &MayLoad,
220 bool &HasSideEffects) {
221 MayStore = MayLoad = HasSideEffects = false;
223 bool HadPattern =
224 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
226 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
227 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
228 // If we decided that this is a store from the pattern, then the .td file
229 // entry is redundant.
230 if (MayStore)
231 fprintf(stderr,
232 "Warning: mayStore flag explicitly set on instruction '%s'"
233 " but flag already inferred from pattern.\n",
234 Inst.TheDef->getName().c_str());
235 MayStore = true;
238 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
239 // If we decided that this is a load from the pattern, then the .td file
240 // entry is redundant.
241 if (MayLoad)
242 fprintf(stderr,
243 "Warning: mayLoad flag explicitly set on instruction '%s'"
244 " but flag already inferred from pattern.\n",
245 Inst.TheDef->getName().c_str());
246 MayLoad = true;
249 if (Inst.neverHasSideEffects) {
250 if (HadPattern)
251 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
252 "which already has a pattern\n", Inst.TheDef->getName().c_str());
253 HasSideEffects = false;
256 if (Inst.hasSideEffects) {
257 if (HasSideEffects)
258 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
259 "which already inferred this.\n", Inst.TheDef->getName().c_str());
260 HasSideEffects = true;
265 //===----------------------------------------------------------------------===//
266 // Main Output.
267 //===----------------------------------------------------------------------===//
269 // run - Emit the main instruction description records for the target...
270 void InstrInfoEmitter::run(std::ostream &OS) {
271 GatherItinClasses();
273 EmitSourceFileHeader("Target Instruction Descriptors", OS);
274 OS << "namespace llvm {\n\n";
276 CodeGenTarget Target;
277 const std::string &TargetName = Target.getName();
278 Record *InstrInfo = Target.getInstructionSet();
280 // Keep track of all of the def lists we have emitted already.
281 std::map<std::vector<Record*>, unsigned> EmittedLists;
282 unsigned ListNumber = 0;
284 // Emit all of the instruction's implicit uses and defs.
285 for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
286 E = Target.inst_end(); II != E; ++II) {
287 Record *Inst = II->second.TheDef;
288 std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
289 if (!Uses.empty()) {
290 unsigned &IL = EmittedLists[Uses];
291 if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
293 std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
294 if (!Defs.empty()) {
295 unsigned &IL = EmittedLists[Defs];
296 if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
300 OperandInfoMapTy OperandInfoIDs;
302 // Emit all of the operand info records.
303 EmitOperandInfo(OS, OperandInfoIDs);
305 // Emit all of the TargetInstrDesc records in their ENUM ordering.
307 OS << "\nstatic const TargetInstrDesc " << TargetName
308 << "Insts[] = {\n";
309 std::vector<const CodeGenInstruction*> NumberedInstructions;
310 Target.getInstructionsByEnumValue(NumberedInstructions);
312 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
313 emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
314 OperandInfoIDs, OS);
315 OS << "};\n";
316 OS << "} // End llvm namespace \n";
319 void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
320 Record *InstrInfo,
321 std::map<std::vector<Record*>, unsigned> &EmittedLists,
322 const OperandInfoMapTy &OpInfo,
323 std::ostream &OS) {
324 // Determine properties of the instruction from its pattern.
325 bool mayStore, mayLoad, HasSideEffects;
326 InferFromPattern(Inst, mayStore, mayLoad, HasSideEffects);
328 int MinOperands = 0;
329 if (!Inst.OperandList.empty())
330 // Each logical operand can be multiple MI operands.
331 MinOperands = Inst.OperandList.back().MIOperandNo +
332 Inst.OperandList.back().MINumOperands;
334 OS << " { ";
335 OS << Num << ",\t" << MinOperands << ",\t"
336 << Inst.NumDefs << ",\t" << getItinClassNumber(Inst.TheDef)
337 << ",\t\"" << Inst.TheDef->getName() << "\", 0";
339 // Emit all of the target indepedent flags...
340 if (Inst.isReturn) OS << "|(1<<TID::Return)";
341 if (Inst.isBranch) OS << "|(1<<TID::Branch)";
342 if (Inst.isIndirectBranch) OS << "|(1<<TID::IndirectBranch)";
343 if (Inst.isBarrier) OS << "|(1<<TID::Barrier)";
344 if (Inst.hasDelaySlot) OS << "|(1<<TID::DelaySlot)";
345 if (Inst.isCall) OS << "|(1<<TID::Call)";
346 if (Inst.isSimpleLoad) OS << "|(1<<TID::SimpleLoad)";
347 if (mayLoad) OS << "|(1<<TID::MayLoad)";
348 if (mayStore) OS << "|(1<<TID::MayStore)";
349 if (Inst.isImplicitDef)OS << "|(1<<TID::ImplicitDef)";
350 if (Inst.isPredicable) OS << "|(1<<TID::Predicable)";
351 if (Inst.isConvertibleToThreeAddress) OS << "|(1<<TID::ConvertibleTo3Addr)";
352 if (Inst.isCommutable) OS << "|(1<<TID::Commutable)";
353 if (Inst.isTerminator) OS << "|(1<<TID::Terminator)";
354 if (Inst.isReMaterializable) OS << "|(1<<TID::Rematerializable)";
355 if (Inst.isNotDuplicable) OS << "|(1<<TID::NotDuplicable)";
356 if (Inst.hasOptionalDef) OS << "|(1<<TID::HasOptionalDef)";
357 if (Inst.usesCustomDAGSchedInserter)
358 OS << "|(1<<TID::UsesCustomDAGSchedInserter)";
359 if (Inst.isVariadic) OS << "|(1<<TID::Variadic)";
360 if (HasSideEffects) OS << "|(1<<TID::UnmodeledSideEffects)";
361 OS << ", 0";
363 // Emit all of the target-specific flags...
364 ListInit *LI = InstrInfo->getValueAsListInit("TSFlagsFields");
365 ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts");
366 if (LI->getSize() != Shift->getSize())
367 throw "Lengths of " + InstrInfo->getName() +
368 ":(TargetInfoFields, TargetInfoPositions) must be equal!";
370 for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
371 emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),
372 dynamic_cast<IntInit*>(Shift->getElement(i)), OS);
374 OS << ", ";
376 // Emit the implicit uses and defs lists...
377 std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
378 if (UseList.empty())
379 OS << "NULL, ";
380 else
381 OS << "ImplicitList" << EmittedLists[UseList] << ", ";
383 std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
384 if (DefList.empty())
385 OS << "NULL, ";
386 else
387 OS << "ImplicitList" << EmittedLists[DefList] << ", ";
389 // Emit the operand info.
390 std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
391 if (OperandInfo.empty())
392 OS << "0";
393 else
394 OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
396 OS << " }, // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
400 void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,
401 IntInit *ShiftInt, std::ostream &OS) {
402 if (Val == 0 || ShiftInt == 0)
403 throw std::string("Illegal value or shift amount in TargetInfo*!");
404 RecordVal *RV = R->getValue(Val->getValue());
405 int Shift = ShiftInt->getValue();
407 if (RV == 0 || RV->getValue() == 0) {
408 // This isn't an error if this is a builtin instruction.
409 if (R->getName() != "PHI" &&
410 R->getName() != "INLINEASM" &&
411 R->getName() != "LABEL" &&
412 R->getName() != "EXTRACT_SUBREG" &&
413 R->getName() != "INSERT_SUBREG")
414 throw R->getName() + " doesn't have a field named '" +
415 Val->getValue() + "'!";
416 return;
419 Init *Value = RV->getValue();
420 if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {
421 if (BI->getValue()) OS << "|(1<<" << Shift << ")";
422 return;
423 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {
424 // Convert the Bits to an integer to print...
425 Init *I = BI->convertInitializerTo(new IntRecTy());
426 if (I)
427 if (IntInit *II = dynamic_cast<IntInit*>(I)) {
428 if (II->getValue()) {
429 if (Shift)
430 OS << "|(" << II->getValue() << "<<" << Shift << ")";
431 else
432 OS << "|" << II->getValue();
434 return;
437 } else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {
438 if (II->getValue()) {
439 if (Shift)
440 OS << "|(" << II->getValue() << "<<" << Shift << ")";
441 else
442 OS << II->getValue();
444 return;
447 std::cerr << "Unhandled initializer: " << *Val << "\n";
448 throw "In record '" + R->getName() + "' for TSFlag emission.";