1 //===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
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]) << ", ";
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
70 DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;
72 if (!MIOI || MIOI->getNumArgs() == 0) {
73 // Single, anonymous, operand.
74 OperandList.push_back(Inst.OperandList[i]);
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;
88 if (OpR->isSubClassOf("RegisterClass"))
89 Res += getQualifiedName(OpR) + "RegClassID, ";
92 // Fill in applicable flags.
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);
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;
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] << " }, ";
140 //===----------------------------------------------------------------------===//
141 // Instruction Analysis
142 //===----------------------------------------------------------------------===//
145 const CodeGenDAGPatterns &CDP;
148 bool &NeverHasSideEffects;
150 InstAnalyzer(const CodeGenDAGPatterns &cdp,
151 bool &maystore, bool &mayload, bool &nhse)
152 : CDP(cdp), mayStore(maystore), mayLoad(mayload), NeverHasSideEffects(nhse){
155 void Analyze(Record *InstRecord) {
156 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
157 if (Pattern == 0) return; // No pattern.
159 // Assume there is no side-effect unless we see one.
160 NeverHasSideEffects = true;
162 // FIXME: Assume only the first tree is the pattern. The others are clobber
164 AnalyzeNode(Pattern->getTree(0));
168 void AnalyzeNode(const TreePatternNode *N) {
172 if (N->getOperator()->getName() != "set") {
173 // Get information about the SDNode for the operator.
174 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
176 // If node writes to memory, it obviously stores to memory.
177 if (OpInfo.hasProperty(SDNPMayStore))
180 // If it reads memory, remember this.
181 if (OpInfo.hasProperty(SDNPMayLoad))
184 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
185 // If this is an intrinsic, analyze it.
186 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem) {
187 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
190 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
191 mayLoad = true;// These may also load memory.
195 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
196 AnalyzeNode(N->getChild(i));
201 void InstrInfoEmitter::InferFromPattern(const CodeGenInstruction &Inst,
202 bool &mayStore, bool &mayLoad,
203 bool &NeverHasSideEffects) {
204 mayStore = mayLoad = NeverHasSideEffects = false;
206 InstAnalyzer(CDP, mayStore, mayLoad,NeverHasSideEffects).Analyze(Inst.TheDef);
208 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
209 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
210 // If we decided that this is a store from the pattern, then the .td file
211 // entry is redundant.
214 "Warning: mayStore flag explicitly set on instruction '%s'"
215 " but flag already inferred from pattern.\n",
216 Inst.TheDef->getName().c_str());
220 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
221 // If we decided that this is a load from the pattern, then the .td file
222 // entry is redundant.
225 "Warning: mayLoad flag explicitly set on instruction '%s'"
226 " but flag already inferred from pattern.\n",
227 Inst.TheDef->getName().c_str());
232 NeverHasSideEffects = Inst.neverHasSideEffects;
235 // If the .td file explicitly says there is no side effect, believe it.
236 if (Inst.neverHasSideEffects)
237 NeverHasSideEffects = true;
242 //===----------------------------------------------------------------------===//
244 //===----------------------------------------------------------------------===//
246 // run - Emit the main instruction description records for the target...
247 void InstrInfoEmitter::run(std::ostream &OS) {
250 EmitSourceFileHeader("Target Instruction Descriptors", OS);
251 OS << "namespace llvm {\n\n";
253 CodeGenTarget Target;
254 const std::string &TargetName = Target.getName();
255 Record *InstrInfo = Target.getInstructionSet();
257 // Keep track of all of the def lists we have emitted already.
258 std::map<std::vector<Record*>, unsigned> EmittedLists;
259 unsigned ListNumber = 0;
261 // Emit all of the instruction's implicit uses and defs.
262 for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
263 E = Target.inst_end(); II != E; ++II) {
264 Record *Inst = II->second.TheDef;
265 std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
267 unsigned &IL = EmittedLists[Uses];
268 if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
270 std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
272 unsigned &IL = EmittedLists[Defs];
273 if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
277 OperandInfoMapTy OperandInfoIDs;
279 // Emit all of the operand info records.
280 EmitOperandInfo(OS, OperandInfoIDs);
282 // Emit all of the TargetInstrDesc records in their ENUM ordering.
284 OS << "\nstatic const TargetInstrDesc " << TargetName
286 std::vector<const CodeGenInstruction*> NumberedInstructions;
287 Target.getInstructionsByEnumValue(NumberedInstructions);
289 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
290 emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
293 OS << "} // End llvm namespace \n";
296 void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
298 std::map<std::vector<Record*>, unsigned> &EmittedLists,
299 const OperandInfoMapTy &OpInfo,
301 // Determine properties of the instruction from its pattern.
302 bool mayStore, mayLoad, NeverHasSideEffects;
303 InferFromPattern(Inst, mayStore, mayLoad, NeverHasSideEffects);
305 if (NeverHasSideEffects && Inst.mayHaveSideEffects) {
306 std::cerr << "error: Instruction '" << Inst.TheDef->getName()
307 << "' is marked with 'mayHaveSideEffects', but it can never have them!\n";
312 if (!Inst.OperandList.empty())
313 // Each logical operand can be multiple MI operands.
314 MinOperands = Inst.OperandList.back().MIOperandNo +
315 Inst.OperandList.back().MINumOperands;
318 OS << Num << ",\t" << MinOperands << ",\t"
319 << Inst.NumDefs << ",\t" << getItinClassNumber(Inst.TheDef)
320 << ",\t\"" << Inst.TheDef->getName() << "\", 0";
322 // Emit all of the target indepedent flags...
323 if (Inst.isReturn) OS << "|(1<<TID::Return)";
324 if (Inst.isBranch) OS << "|(1<<TID::Branch)";
325 if (Inst.isIndirectBranch) OS << "|(1<<TID::IndirectBranch)";
326 if (Inst.isBarrier) OS << "|(1<<TID::Barrier)";
327 if (Inst.hasDelaySlot) OS << "|(1<<TID::DelaySlot)";
328 if (Inst.isCall) OS << "|(1<<TID::Call)";
329 if (Inst.isSimpleLoad) OS << "|(1<<TID::SimpleLoad)";
330 if (mayLoad) OS << "|(1<<TID::MayLoad)";
331 if (mayStore) OS << "|(1<<TID::MayStore)";
332 if (Inst.isImplicitDef)OS << "|(1<<TID::ImplicitDef)";
333 if (Inst.isPredicable) OS << "|(1<<TID::Predicable)";
334 if (Inst.isConvertibleToThreeAddress) OS << "|(1<<TID::ConvertibleTo3Addr)";
335 if (Inst.isCommutable) OS << "|(1<<TID::Commutable)";
336 if (Inst.isTerminator) OS << "|(1<<TID::Terminator)";
337 if (Inst.isReMaterializable) OS << "|(1<<TID::Rematerializable)";
338 if (Inst.isNotDuplicable) OS << "|(1<<TID::NotDuplicable)";
339 if (Inst.hasOptionalDef) OS << "|(1<<TID::HasOptionalDef)";
340 if (Inst.usesCustomDAGSchedInserter)
341 OS << "|(1<<TID::UsesCustomDAGSchedInserter)";
342 if (Inst.isVariadic) OS << "|(1<<TID::Variadic)";
343 if (Inst.mayHaveSideEffects) OS << "|(1<<TID::MayHaveSideEffects)";
344 if (NeverHasSideEffects) OS << "|(1<<TID::NeverHasSideEffects)";
347 // Emit all of the target-specific flags...
348 ListInit *LI = InstrInfo->getValueAsListInit("TSFlagsFields");
349 ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts");
350 if (LI->getSize() != Shift->getSize())
351 throw "Lengths of " + InstrInfo->getName() +
352 ":(TargetInfoFields, TargetInfoPositions) must be equal!";
354 for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
355 emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),
356 dynamic_cast<IntInit*>(Shift->getElement(i)), OS);
360 // Emit the implicit uses and defs lists...
361 std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
365 OS << "ImplicitList" << EmittedLists[UseList] << ", ";
367 std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
371 OS << "ImplicitList" << EmittedLists[DefList] << ", ";
373 // Emit the operand info.
374 std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
375 if (OperandInfo.empty())
378 OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
380 OS << " }, // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
384 void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,
385 IntInit *ShiftInt, std::ostream &OS) {
386 if (Val == 0 || ShiftInt == 0)
387 throw std::string("Illegal value or shift amount in TargetInfo*!");
388 RecordVal *RV = R->getValue(Val->getValue());
389 int Shift = ShiftInt->getValue();
391 if (RV == 0 || RV->getValue() == 0) {
392 // This isn't an error if this is a builtin instruction.
393 if (R->getName() != "PHI" &&
394 R->getName() != "INLINEASM" &&
395 R->getName() != "LABEL" &&
396 R->getName() != "EXTRACT_SUBREG" &&
397 R->getName() != "INSERT_SUBREG")
398 throw R->getName() + " doesn't have a field named '" +
399 Val->getValue() + "'!";
403 Init *Value = RV->getValue();
404 if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {
405 if (BI->getValue()) OS << "|(1<<" << Shift << ")";
407 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {
408 // Convert the Bits to an integer to print...
409 Init *I = BI->convertInitializerTo(new IntRecTy());
411 if (IntInit *II = dynamic_cast<IntInit*>(I)) {
412 if (II->getValue()) {
414 OS << "|(" << II->getValue() << "<<" << Shift << ")";
416 OS << "|" << II->getValue();
421 } else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {
422 if (II->getValue()) {
424 OS << "|(" << II->getValue() << "<<" << Shift << ")";
426 OS << II->getValue();
431 std::cerr << "Unhandled initializer: " << *Val << "\n";
432 throw "In record '" + R->getName() + "' for TSFlag emission.";