1 //===- FastISelEmitter.cpp - Generate an instruction selector -------------===//
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 emits a "fast" instruction selector.
12 // This instruction selection method is designed to emit very poor code
13 // quickly. Also, it is not designed to do much lowering, so most illegal
14 // types (e.g. i64 on 32-bit targets) and operations (e.g. calls) are not
15 // supported and cannot easily be added. Blocks containing operations
16 // that are not supported need to be handled by a more capable selector,
17 // such as the SelectionDAG selector.
19 // The intended use for "fast" instruction selection is "-O0" mode
20 // compilation, where the quality of the generated code is irrelevant when
21 // weighed against the speed at which the code can be generated.
23 // If compile time is so important, you might wonder why we don't just
24 // skip codegen all-together, emit LLVM bytecode files, and execute them
25 // with an interpreter. The answer is that it would complicate linking and
26 // debugging, and also because that isn't how a compiler is expected to
27 // work in some circles.
29 // If you need better generated code or more lowering than what this
30 // instruction selector provides, use the SelectionDAG (DAGISel) instruction
31 // selector instead. If you're looking here because SelectionDAG isn't fast
32 // enough, consider looking into improving the SelectionDAG infastructure
33 // instead. At the time of this writing there remain several major
34 // opportunities for improvement.
36 //===----------------------------------------------------------------------===//
38 #include "FastISelEmitter.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/Streams.h"
42 #include "llvm/ADT/VectorExtras.h"
47 /// InstructionMemo - This class holds additional information about an
48 /// instruction needed to emit code for it.
50 struct InstructionMemo {
52 const CodeGenRegisterClass *RC;
53 unsigned char SubRegNo;
54 std::vector<std::string>* PhysRegs;
57 /// OperandsSignature - This class holds a description of a list of operand
58 /// types. It has utility methods for emitting text based on the operands.
60 struct OperandsSignature {
61 std::vector<std::string> Operands;
63 bool operator<(const OperandsSignature &O) const {
64 return Operands < O.Operands;
67 bool empty() const { return Operands.empty(); }
69 /// initialize - Examine the given pattern and initialize the contents
70 /// of the Operands array accordingly. Return true if all the operands
71 /// are supported, false otherwise.
73 bool initialize(TreePatternNode *InstPatNode,
74 const CodeGenTarget &Target,
75 MVT::SimpleValueType VT) {
76 if (!InstPatNode->isLeaf() &&
77 InstPatNode->getOperator()->getName() == "imm") {
78 Operands.push_back("i");
81 if (!InstPatNode->isLeaf() &&
82 InstPatNode->getOperator()->getName() == "fpimm") {
83 Operands.push_back("f");
87 const CodeGenRegisterClass *DstRC = 0;
89 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
90 TreePatternNode *Op = InstPatNode->getChild(i);
91 // For now, filter out any operand with a predicate.
92 if (!Op->getPredicateFn().empty())
94 // For now, filter out any operand with multiple values.
95 if (Op->getExtTypes().size() != 1)
97 // For now, all the operands must have the same type.
98 if (Op->getTypeNum(0) != VT)
101 if (Op->getOperator()->getName() == "imm") {
102 Operands.push_back("i");
105 if (Op->getOperator()->getName() == "fpimm") {
106 Operands.push_back("f");
109 // For now, ignore other non-leaf nodes.
112 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
115 Record *OpLeafRec = OpDI->getDef();
116 // For now, the only other thing we accept is register operands.
118 const CodeGenRegisterClass *RC = 0;
119 if (OpLeafRec->isSubClassOf("RegisterClass"))
120 RC = &Target.getRegisterClass(OpLeafRec);
121 else if (OpLeafRec->isSubClassOf("Register"))
122 RC = Target.getRegisterClassForRegister(OpLeafRec);
125 // For now, require the register operands' register classes to all
129 // For now, all the operands must have the same register class.
135 Operands.push_back("r");
140 void PrintParameters(std::ostream &OS) const {
141 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
142 if (Operands[i] == "r") {
143 OS << "unsigned Op" << i;
144 } else if (Operands[i] == "i") {
145 OS << "uint64_t imm" << i;
146 } else if (Operands[i] == "f") {
147 OS << "ConstantFP *f" << i;
149 assert("Unknown operand kind!");
157 void PrintArguments(std::ostream &OS,
158 const std::vector<std::string>& PR) const {
159 assert(PR.size() == Operands.size());
160 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
163 } else if (Operands[i] == "r") {
165 } else if (Operands[i] == "i") {
167 } else if (Operands[i] == "f") {
170 assert("Unknown operand kind!");
178 void PrintArguments(std::ostream &OS) const {
179 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
180 if (Operands[i] == "r") {
182 } else if (Operands[i] == "i") {
184 } else if (Operands[i] == "f") {
187 assert("Unknown operand kind!");
196 void PrintManglingSuffix(std::ostream &OS) const {
197 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
204 typedef std::map<std::string, InstructionMemo> PredMap;
205 typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap;
206 typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap;
207 typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap;
208 typedef std::map<OperandsSignature, OpcodeTypeRetPredMap> OperandsOpcodeTypeRetPredMap;
210 OperandsOpcodeTypeRetPredMap SimplePatterns;
215 explicit FastISelMap(std::string InstNS);
217 void CollectPatterns(CodeGenDAGPatterns &CGP);
218 void PrintClass(std::ostream &OS);
219 void PrintFunctionDefinitions(std::ostream &OS);
224 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
225 return CGP.getSDNodeInfo(Op).getEnumName();
228 static std::string getLegalCName(std::string OpName) {
229 std::string::size_type pos = OpName.find("::");
230 if (pos != std::string::npos)
231 OpName.replace(pos, 2, "_");
235 FastISelMap::FastISelMap(std::string instns)
239 void FastISelMap::CollectPatterns(CodeGenDAGPatterns &CGP) {
240 const CodeGenTarget &Target = CGP.getTargetInfo();
242 // Determine the target's namespace name.
243 InstNS = Target.getInstNamespace() + "::";
244 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
246 // Scan through all the patterns and record the simple ones.
247 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
248 E = CGP.ptm_end(); I != E; ++I) {
249 const PatternToMatch &Pattern = *I;
251 // For now, just look at Instructions, so that we don't have to worry
252 // about emitting multiple instructions for a pattern.
253 TreePatternNode *Dst = Pattern.getDstPattern();
254 if (Dst->isLeaf()) continue;
255 Record *Op = Dst->getOperator();
256 if (!Op->isSubClassOf("Instruction"))
258 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
259 if (II.OperandList.empty())
262 // For now, ignore multi-instruction patterns.
263 bool MultiInsts = false;
264 for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) {
265 TreePatternNode *ChildOp = Dst->getChild(i);
266 if (ChildOp->isLeaf())
268 if (ChildOp->getOperator()->isSubClassOf("Instruction")) {
276 // For now, ignore instructions where the first operand is not an
278 const CodeGenRegisterClass *DstRC = 0;
279 unsigned SubRegNo = ~0;
280 if (Op->getName() != "EXTRACT_SUBREG") {
281 Record *Op0Rec = II.OperandList[0].Rec;
282 if (!Op0Rec->isSubClassOf("RegisterClass"))
284 DstRC = &Target.getRegisterClass(Op0Rec);
288 SubRegNo = static_cast<IntInit*>(
289 Dst->getChild(1)->getLeafValue())->getValue();
292 // Inspect the pattern.
293 TreePatternNode *InstPatNode = Pattern.getSrcPattern();
294 if (!InstPatNode) continue;
295 if (InstPatNode->isLeaf()) continue;
297 Record *InstPatOp = InstPatNode->getOperator();
298 std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
299 MVT::SimpleValueType RetVT = InstPatNode->getTypeNum(0);
300 MVT::SimpleValueType VT = RetVT;
301 if (InstPatNode->getNumChildren())
302 VT = InstPatNode->getChild(0)->getTypeNum(0);
304 // For now, filter out instructions which just set a register to
305 // an Operand or an immediate, like MOV32ri.
306 if (InstPatOp->isSubClassOf("Operand"))
309 // For now, filter out any instructions with predicates.
310 if (!InstPatNode->getPredicateFn().empty())
313 // Check all the operands.
314 OperandsSignature Operands;
315 if (!Operands.initialize(InstPatNode, Target, VT))
318 std::vector<std::string>* PhysRegInputs = new std::vector<std::string>();
319 if (!InstPatNode->isLeaf() &&
320 (InstPatNode->getOperator()->getName() == "imm" ||
321 InstPatNode->getOperator()->getName() == "fpimmm"))
322 PhysRegInputs->push_back("");
323 else if (!InstPatNode->isLeaf()) {
324 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
325 TreePatternNode *Op = InstPatNode->getChild(i);
327 PhysRegInputs->push_back("");
331 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
332 Record *OpLeafRec = OpDI->getDef();
334 if (OpLeafRec->isSubClassOf("Register")) {
335 PhysReg += static_cast<StringInit*>(OpLeafRec->getValue( \
336 "Namespace")->getValue())->getValue();
339 std::vector<CodeGenRegister> Regs = Target.getRegisters();
340 for (unsigned i = 0; i < Regs.size(); ++i) {
341 if (Regs[i].TheDef == OpLeafRec) {
342 PhysReg += Regs[i].getName();
348 PhysRegInputs->push_back(PhysReg);
351 PhysRegInputs->push_back("");
353 // Get the predicate that guards this pattern.
354 std::string PredicateCheck = Pattern.getPredicateCheck();
356 // Ok, we found a pattern that we can handle. Remember it.
357 InstructionMemo Memo = {
358 Pattern.getDstPattern()->getOperator()->getName(),
363 assert(!SimplePatterns[Operands][OpcodeName][VT][RetVT].count(PredicateCheck) &&
364 "Duplicate pattern!");
365 SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo;
369 void FastISelMap::PrintFunctionDefinitions(std::ostream &OS) {
370 // Now emit code for all the patterns that we collected.
371 for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
372 OE = SimplePatterns.end(); OI != OE; ++OI) {
373 const OperandsSignature &Operands = OI->first;
374 const OpcodeTypeRetPredMap &OTM = OI->second;
376 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
378 const std::string &Opcode = I->first;
379 const TypeRetPredMap &TM = I->second;
381 OS << "// FastEmit functions for " << Opcode << ".\n";
384 // Emit one function for each opcode,type pair.
385 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
387 MVT::SimpleValueType VT = TI->first;
388 const RetPredMap &RM = TI->second;
389 if (RM.size() != 1) {
390 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
392 MVT::SimpleValueType RetVT = RI->first;
393 const PredMap &PM = RI->second;
394 bool HasPred = false;
396 OS << "unsigned FastEmit_"
397 << getLegalCName(Opcode)
398 << "_" << getLegalCName(getName(VT))
399 << "_" << getLegalCName(getName(RetVT)) << "_";
400 Operands.PrintManglingSuffix(OS);
402 Operands.PrintParameters(OS);
405 // Emit code for each possible instruction. There may be
406 // multiple if there are subtarget concerns.
407 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
409 std::string PredicateCheck = PI->first;
410 const InstructionMemo &Memo = PI->second;
412 if (PredicateCheck.empty()) {
414 "Multiple instructions match, at least one has "
415 "a predicate and at least one doesn't!");
417 OS << " if (" + PredicateCheck + ") {\n";
422 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
423 if ((*Memo.PhysRegs)[i] != "")
424 OS << " TII.copyRegToReg(*MBB, MBB->end(), "
425 << (*Memo.PhysRegs)[i] << ", Op" << i << ", "
426 << "TM.getRegisterInfo()->getPhysicalRegisterRegClass("
427 << (*Memo.PhysRegs)[i] << "), "
428 << "MRI.getRegClass(Op" << i << "));\n";
431 OS << " return FastEmitInst_";
432 if (Memo.SubRegNo == (unsigned char)~0) {
433 Operands.PrintManglingSuffix(OS);
434 OS << "(" << InstNS << Memo.Name << ", ";
435 OS << InstNS << Memo.RC->getName() << "RegisterClass";
436 if (!Operands.empty())
438 Operands.PrintArguments(OS, *Memo.PhysRegs);
441 OS << "extractsubreg(Op0, ";
442 OS << (unsigned)Memo.SubRegNo;
450 // Return 0 if none of the predicates were satisfied.
452 OS << " return 0;\n";
457 // Emit one function for the type that demultiplexes on return type.
458 OS << "unsigned FastEmit_"
459 << getLegalCName(Opcode) << "_"
460 << getLegalCName(getName(VT)) << "_";
461 Operands.PrintManglingSuffix(OS);
462 OS << "(MVT::SimpleValueType RetVT";
463 if (!Operands.empty())
465 Operands.PrintParameters(OS);
466 OS << ") {\nswitch (RetVT) {\n";
467 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
469 MVT::SimpleValueType RetVT = RI->first;
470 OS << " case " << getName(RetVT) << ": return FastEmit_"
471 << getLegalCName(Opcode) << "_" << getLegalCName(getName(VT))
472 << "_" << getLegalCName(getName(RetVT)) << "_";
473 Operands.PrintManglingSuffix(OS);
475 Operands.PrintArguments(OS);
478 OS << " default: return 0;\n}\n}\n\n";
481 // Non-variadic return type.
482 OS << "unsigned FastEmit_"
483 << getLegalCName(Opcode) << "_"
484 << getLegalCName(getName(VT)) << "_";
485 Operands.PrintManglingSuffix(OS);
486 OS << "(MVT::SimpleValueType RetVT";
487 if (!Operands.empty())
489 Operands.PrintParameters(OS);
492 OS << " if (RetVT != " << getName(RM.begin()->first)
493 << ")\n return 0;\n";
495 const PredMap &PM = RM.begin()->second;
496 bool HasPred = false;
498 // Emit code for each possible instruction. There may be
499 // multiple if there are subtarget concerns.
500 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end(); PI != PE; ++PI) {
501 std::string PredicateCheck = PI->first;
502 const InstructionMemo &Memo = PI->second;
504 if (PredicateCheck.empty()) {
506 "Multiple instructions match, at least one has "
507 "a predicate and at least one doesn't!");
509 OS << " if (" + PredicateCheck + ") {\n";
514 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
515 if ((*Memo.PhysRegs)[i] != "")
516 OS << " TII.copyRegToReg(*MBB, MBB->end(), "
517 << (*Memo.PhysRegs)[i] << ", Op" << i << ", "
518 << "TM.getRegisterInfo()->getPhysicalRegisterRegClass("
519 << (*Memo.PhysRegs)[i] << "), "
520 << "MRI.getRegClass(Op" << i << "));\n";
523 OS << " return FastEmitInst_";
525 if (Memo.SubRegNo == (unsigned char)~0) {
526 Operands.PrintManglingSuffix(OS);
527 OS << "(" << InstNS << Memo.Name << ", ";
528 OS << InstNS << Memo.RC->getName() << "RegisterClass";
529 if (!Operands.empty())
531 Operands.PrintArguments(OS, *Memo.PhysRegs);
534 OS << "extractsubreg(Op0, ";
535 OS << (unsigned)Memo.SubRegNo;
543 // Return 0 if none of the predicates were satisfied.
545 OS << " return 0;\n";
551 // Emit one function for the opcode that demultiplexes based on the type.
552 OS << "unsigned FastEmit_"
553 << getLegalCName(Opcode) << "_";
554 Operands.PrintManglingSuffix(OS);
555 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT";
556 if (!Operands.empty())
558 Operands.PrintParameters(OS);
560 OS << " switch (VT) {\n";
561 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
563 MVT::SimpleValueType VT = TI->first;
564 std::string TypeName = getName(VT);
565 OS << " case " << TypeName << ": return FastEmit_"
566 << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
567 Operands.PrintManglingSuffix(OS);
569 if (!Operands.empty())
571 Operands.PrintArguments(OS);
574 OS << " default: return 0;\n";
580 OS << "// Top-level FastEmit function.\n";
583 // Emit one function for the operand signature that demultiplexes based
584 // on opcode and type.
585 OS << "unsigned FastEmit_";
586 Operands.PrintManglingSuffix(OS);
587 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT, ISD::NodeType Opcode";
588 if (!Operands.empty())
590 Operands.PrintParameters(OS);
592 OS << " switch (Opcode) {\n";
593 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
595 const std::string &Opcode = I->first;
597 OS << " case " << Opcode << ": return FastEmit_"
598 << getLegalCName(Opcode) << "_";
599 Operands.PrintManglingSuffix(OS);
601 if (!Operands.empty())
603 Operands.PrintArguments(OS);
606 OS << " default: return 0;\n";
613 void FastISelEmitter::run(std::ostream &OS) {
614 const CodeGenTarget &Target = CGP.getTargetInfo();
616 // Determine the target's namespace name.
617 std::string InstNS = Target.getInstNamespace() + "::";
618 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
620 EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
621 Target.getName() + " target", OS);
623 FastISelMap F(InstNS);
624 F.CollectPatterns(CGP);
625 F.PrintFunctionDefinitions(OS);
628 FastISelEmitter::FastISelEmitter(RecordKeeper &R)