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 code for use by the "fast" instruction
11 // selection algorithm. See the comments at the top of
12 // lib/CodeGen/SelectionDAG/FastISel.cpp for background.
14 // This file scans through the target's tablegen instruction-info files
15 // and extracts instructions with obvious-looking patterns, and it emits
16 // code to look up these instructions by type and operator.
18 //===----------------------------------------------------------------------===//
20 #include "FastISelEmitter.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/ADT/VectorExtras.h"
28 /// InstructionMemo - This class holds additional information about an
29 /// instruction needed to emit code for it.
31 struct InstructionMemo {
33 const CodeGenRegisterClass *RC;
34 unsigned char SubRegNo;
35 std::vector<std::string>* PhysRegs;
38 /// OperandsSignature - This class holds a description of a list of operand
39 /// types. It has utility methods for emitting text based on the operands.
41 struct OperandsSignature {
42 std::vector<std::string> Operands;
44 bool operator<(const OperandsSignature &O) const {
45 return Operands < O.Operands;
48 bool empty() const { return Operands.empty(); }
50 /// initialize - Examine the given pattern and initialize the contents
51 /// of the Operands array accordingly. Return true if all the operands
52 /// are supported, false otherwise.
54 bool initialize(TreePatternNode *InstPatNode,
55 const CodeGenTarget &Target,
56 MVT::SimpleValueType VT) {
57 if (!InstPatNode->isLeaf() &&
58 InstPatNode->getOperator()->getName() == "imm") {
59 Operands.push_back("i");
62 if (!InstPatNode->isLeaf() &&
63 InstPatNode->getOperator()->getName() == "fpimm") {
64 Operands.push_back("f");
68 const CodeGenRegisterClass *DstRC = 0;
70 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
71 TreePatternNode *Op = InstPatNode->getChild(i);
72 // For now, filter out any operand with a predicate.
73 if (!Op->getPredicateFns().empty())
75 // For now, filter out any operand with multiple values.
76 assert(Op->hasTypeSet() && "Type infererence not done?");
77 // For now, all the operands must have the same type.
78 if (Op->getType() != VT)
81 if (Op->getOperator()->getName() == "imm") {
82 Operands.push_back("i");
85 if (Op->getOperator()->getName() == "fpimm") {
86 Operands.push_back("f");
89 // For now, ignore other non-leaf nodes.
92 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
95 Record *OpLeafRec = OpDI->getDef();
96 // For now, the only other thing we accept is register operands.
98 const CodeGenRegisterClass *RC = 0;
99 if (OpLeafRec->isSubClassOf("RegisterClass"))
100 RC = &Target.getRegisterClass(OpLeafRec);
101 else if (OpLeafRec->isSubClassOf("Register"))
102 RC = Target.getRegisterClassForRegister(OpLeafRec);
105 // For now, require the register operands' register classes to all
109 // For now, all the operands must have the same register class.
115 Operands.push_back("r");
120 void PrintParameters(raw_ostream &OS) const {
121 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
122 if (Operands[i] == "r") {
123 OS << "unsigned Op" << i;
124 } else if (Operands[i] == "i") {
125 OS << "uint64_t imm" << i;
126 } else if (Operands[i] == "f") {
127 OS << "ConstantFP *f" << i;
129 assert("Unknown operand kind!");
137 void PrintArguments(raw_ostream &OS,
138 const std::vector<std::string>& PR) const {
139 assert(PR.size() == Operands.size());
140 bool PrintedArg = false;
141 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
143 // Implicit physical register operand.
148 if (Operands[i] == "r") {
151 } else if (Operands[i] == "i") {
154 } else if (Operands[i] == "f") {
158 assert("Unknown operand kind!");
164 void PrintArguments(raw_ostream &OS) const {
165 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
166 if (Operands[i] == "r") {
168 } else if (Operands[i] == "i") {
170 } else if (Operands[i] == "f") {
173 assert("Unknown operand kind!");
182 void PrintManglingSuffix(raw_ostream &OS,
183 const std::vector<std::string>& PR) const {
184 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
186 // Implicit physical register operand. e.g. Instruction::Mul expect to
187 // select to a binary op. On x86, mul may take a single operand with
188 // the other operand being implicit. We must emit something that looks
189 // like a binary instruction except for the very inner FastEmitInst_*
196 void PrintManglingSuffix(raw_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 PrintFunctionDefinitions(raw_ostream &OS);
223 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
224 return CGP.getSDNodeInfo(Op).getEnumName();
227 static std::string getLegalCName(std::string OpName) {
228 std::string::size_type pos = OpName.find("::");
229 if (pos != std::string::npos)
230 OpName.replace(pos, 2, "_");
234 FastISelMap::FastISelMap(std::string instns)
238 void FastISelMap::CollectPatterns(CodeGenDAGPatterns &CGP) {
239 const CodeGenTarget &Target = CGP.getTargetInfo();
241 // Determine the target's namespace name.
242 InstNS = Target.getInstNamespace() + "::";
243 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
245 // Scan through all the patterns and record the simple ones.
246 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
247 E = CGP.ptm_end(); I != E; ++I) {
248 const PatternToMatch &Pattern = *I;
250 // For now, just look at Instructions, so that we don't have to worry
251 // about emitting multiple instructions for a pattern.
252 TreePatternNode *Dst = Pattern.getDstPattern();
253 if (Dst->isLeaf()) continue;
254 Record *Op = Dst->getOperator();
255 if (!Op->isSubClassOf("Instruction"))
257 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op);
258 if (II.OperandList.empty())
261 // For now, ignore multi-instruction patterns.
262 bool MultiInsts = false;
263 for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) {
264 TreePatternNode *ChildOp = Dst->getChild(i);
265 if (ChildOp->isLeaf())
267 if (ChildOp->getOperator()->isSubClassOf("Instruction")) {
275 // For now, ignore instructions where the first operand is not an
277 const CodeGenRegisterClass *DstRC = 0;
278 unsigned SubRegNo = ~0;
279 if (Op->getName() != "EXTRACT_SUBREG") {
280 Record *Op0Rec = II.OperandList[0].Rec;
281 if (!Op0Rec->isSubClassOf("RegisterClass"))
283 DstRC = &Target.getRegisterClass(Op0Rec);
287 SubRegNo = static_cast<IntInit*>(
288 Dst->getChild(1)->getLeafValue())->getValue();
291 // Inspect the pattern.
292 TreePatternNode *InstPatNode = Pattern.getSrcPattern();
293 if (!InstPatNode) continue;
294 if (InstPatNode->isLeaf()) continue;
296 Record *InstPatOp = InstPatNode->getOperator();
297 std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
298 MVT::SimpleValueType RetVT = InstPatNode->getType();
299 MVT::SimpleValueType VT = RetVT;
300 if (InstPatNode->getNumChildren())
301 VT = InstPatNode->getChild(0)->getType();
303 // For now, filter out instructions which just set a register to
304 // an Operand or an immediate, like MOV32ri.
305 if (InstPatOp->isSubClassOf("Operand"))
308 // For now, filter out any instructions with predicates.
309 if (!InstPatNode->getPredicateFns().empty())
312 // Check all the operands.
313 OperandsSignature Operands;
314 if (!Operands.initialize(InstPatNode, Target, VT))
317 std::vector<std::string>* PhysRegInputs = new std::vector<std::string>();
318 if (!InstPatNode->isLeaf() &&
319 (InstPatNode->getOperator()->getName() == "imm" ||
320 InstPatNode->getOperator()->getName() == "fpimmm"))
321 PhysRegInputs->push_back("");
322 else if (!InstPatNode->isLeaf()) {
323 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
324 TreePatternNode *Op = InstPatNode->getChild(i);
326 PhysRegInputs->push_back("");
330 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
331 Record *OpLeafRec = OpDI->getDef();
333 if (OpLeafRec->isSubClassOf("Register")) {
334 PhysReg += static_cast<StringInit*>(OpLeafRec->getValue( \
335 "Namespace")->getValue())->getValue();
338 std::vector<CodeGenRegister> Regs = Target.getRegisters();
339 for (unsigned i = 0; i < Regs.size(); ++i) {
340 if (Regs[i].TheDef == OpLeafRec) {
341 PhysReg += Regs[i].getName();
347 PhysRegInputs->push_back(PhysReg);
350 PhysRegInputs->push_back("");
352 // Get the predicate that guards this pattern.
353 std::string PredicateCheck = Pattern.getPredicateCheck();
355 // Ok, we found a pattern that we can handle. Remember it.
356 InstructionMemo Memo = {
357 Pattern.getDstPattern()->getOperator()->getName(),
362 assert(!SimplePatterns[Operands][OpcodeName][VT][RetVT].count(PredicateCheck) &&
363 "Duplicate pattern!");
364 SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo;
368 void FastISelMap::PrintFunctionDefinitions(raw_ostream &OS) {
369 // Now emit code for all the patterns that we collected.
370 for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
371 OE = SimplePatterns.end(); OI != OE; ++OI) {
372 const OperandsSignature &Operands = OI->first;
373 const OpcodeTypeRetPredMap &OTM = OI->second;
375 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
377 const std::string &Opcode = I->first;
378 const TypeRetPredMap &TM = I->second;
380 OS << "// FastEmit functions for " << Opcode << ".\n";
383 // Emit one function for each opcode,type pair.
384 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
386 MVT::SimpleValueType VT = TI->first;
387 const RetPredMap &RM = TI->second;
388 if (RM.size() != 1) {
389 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
391 MVT::SimpleValueType RetVT = RI->first;
392 const PredMap &PM = RI->second;
393 bool HasPred = false;
395 OS << "unsigned FastEmit_"
396 << getLegalCName(Opcode)
397 << "_" << getLegalCName(getName(VT))
398 << "_" << getLegalCName(getName(RetVT)) << "_";
399 Operands.PrintManglingSuffix(OS);
401 Operands.PrintParameters(OS);
404 // Emit code for each possible instruction. There may be
405 // multiple if there are subtarget concerns.
406 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
408 std::string PredicateCheck = PI->first;
409 const InstructionMemo &Memo = PI->second;
411 if (PredicateCheck.empty()) {
413 "Multiple instructions match, at least one has "
414 "a predicate and at least one doesn't!");
416 OS << " if (" + PredicateCheck + ") {\n";
421 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
422 if ((*Memo.PhysRegs)[i] != "")
423 OS << " TII.copyRegToReg(*MBB, MBB->end(), "
424 << (*Memo.PhysRegs)[i] << ", Op" << i << ", "
425 << "TM.getRegisterInfo()->getPhysicalRegisterRegClass("
426 << (*Memo.PhysRegs)[i] << "), "
427 << "MRI.getRegClass(Op" << i << "));\n";
430 OS << " return FastEmitInst_";
431 if (Memo.SubRegNo == (unsigned char)~0) {
432 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
433 OS << "(" << InstNS << Memo.Name << ", ";
434 OS << InstNS << Memo.RC->getName() << "RegisterClass";
435 if (!Operands.empty())
437 Operands.PrintArguments(OS, *Memo.PhysRegs);
440 OS << "extractsubreg(" << getName(RetVT);
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);
463 if (!Operands.empty())
465 Operands.PrintParameters(OS);
466 OS << ") {\nswitch (RetVT.SimpleTy) {\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);
487 if (!Operands.empty())
489 Operands.PrintParameters(OS);
492 OS << " if (RetVT.SimpleTy != " << 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;
502 std::string PredicateCheck = PI->first;
503 const InstructionMemo &Memo = PI->second;
505 if (PredicateCheck.empty()) {
507 "Multiple instructions match, at least one has "
508 "a predicate and at least one doesn't!");
510 OS << " if (" + PredicateCheck + ") {\n";
515 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
516 if ((*Memo.PhysRegs)[i] != "")
517 OS << " TII.copyRegToReg(*MBB, MBB->end(), "
518 << (*Memo.PhysRegs)[i] << ", Op" << i << ", "
519 << "TM.getRegisterInfo()->getPhysicalRegisterRegClass("
520 << (*Memo.PhysRegs)[i] << "), "
521 << "MRI.getRegClass(Op" << i << "));\n";
524 OS << " return FastEmitInst_";
526 if (Memo.SubRegNo == (unsigned char)~0) {
527 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
528 OS << "(" << InstNS << Memo.Name << ", ";
529 OS << InstNS << Memo.RC->getName() << "RegisterClass";
530 if (!Operands.empty())
532 Operands.PrintArguments(OS, *Memo.PhysRegs);
535 OS << "extractsubreg(RetVT, Op0, ";
536 OS << (unsigned)Memo.SubRegNo;
544 // Return 0 if none of the predicates were satisfied.
546 OS << " return 0;\n";
552 // Emit one function for the opcode that demultiplexes based on the type.
553 OS << "unsigned FastEmit_"
554 << getLegalCName(Opcode) << "_";
555 Operands.PrintManglingSuffix(OS);
556 OS << "(MVT VT, MVT RetVT";
557 if (!Operands.empty())
559 Operands.PrintParameters(OS);
561 OS << " switch (VT.SimpleTy) {\n";
562 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
564 MVT::SimpleValueType VT = TI->first;
565 std::string TypeName = getName(VT);
566 OS << " case " << TypeName << ": return FastEmit_"
567 << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
568 Operands.PrintManglingSuffix(OS);
570 if (!Operands.empty())
572 Operands.PrintArguments(OS);
575 OS << " default: return 0;\n";
581 OS << "// Top-level FastEmit function.\n";
584 // Emit one function for the operand signature that demultiplexes based
585 // on opcode and type.
586 OS << "unsigned FastEmit_";
587 Operands.PrintManglingSuffix(OS);
588 OS << "(MVT VT, MVT RetVT, unsigned Opcode";
589 if (!Operands.empty())
591 Operands.PrintParameters(OS);
593 OS << " switch (Opcode) {\n";
594 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
596 const std::string &Opcode = I->first;
598 OS << " case " << Opcode << ": return FastEmit_"
599 << getLegalCName(Opcode) << "_";
600 Operands.PrintManglingSuffix(OS);
602 if (!Operands.empty())
604 Operands.PrintArguments(OS);
607 OS << " default: return 0;\n";
614 void FastISelEmitter::run(raw_ostream &OS) {
615 const CodeGenTarget &Target = CGP.getTargetInfo();
617 // Determine the target's namespace name.
618 std::string InstNS = Target.getInstNamespace() + "::";
619 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
621 EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
622 Target.getName() + " target", OS);
624 FastISelMap F(InstNS);
625 F.CollectPatterns(CGP);
626 F.PrintFunctionDefinitions(OS);
629 FastISelEmitter::FastISelEmitter(RecordKeeper &R)