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;
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) {
58 if (!InstPatNode->isLeaf()) {
59 if (InstPatNode->getOperator()->getName() == "imm") {
60 Operands.push_back("i");
63 if (InstPatNode->getOperator()->getName() == "fpimm") {
64 Operands.push_back("f");
69 const CodeGenRegisterClass *DstRC = 0;
71 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
72 TreePatternNode *Op = InstPatNode->getChild(i);
74 // For now, filter out any operand with a predicate.
75 // For now, filter out any operand with multiple values.
76 if (!Op->getPredicateFns().empty() ||
77 Op->getNumTypes() != 1)
80 assert(Op->hasTypeSet(0) && "Type infererence not done?");
81 // For now, all the operands must have the same type.
82 if (Op->getType(0) != VT)
86 if (Op->getOperator()->getName() == "imm") {
87 Operands.push_back("i");
90 if (Op->getOperator()->getName() == "fpimm") {
91 Operands.push_back("f");
94 // For now, ignore other non-leaf nodes.
97 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
100 Record *OpLeafRec = OpDI->getDef();
101 // For now, the only other thing we accept is register operands.
103 const CodeGenRegisterClass *RC = 0;
104 if (OpLeafRec->isSubClassOf("RegisterClass"))
105 RC = &Target.getRegisterClass(OpLeafRec);
106 else if (OpLeafRec->isSubClassOf("Register"))
107 RC = Target.getRegisterClassForRegister(OpLeafRec);
111 // For now, this needs to be a register class of some sort.
115 // For now, all the operands must have the same register class.
121 Operands.push_back("r");
126 void PrintParameters(raw_ostream &OS) const {
127 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
128 if (Operands[i] == "r") {
129 OS << "unsigned Op" << i << ", bool Op" << i << "IsKill";
130 } else if (Operands[i] == "i") {
131 OS << "uint64_t imm" << i;
132 } else if (Operands[i] == "f") {
133 OS << "ConstantFP *f" << i;
135 assert("Unknown operand kind!");
143 void PrintArguments(raw_ostream &OS,
144 const std::vector<std::string>& PR) const {
145 assert(PR.size() == Operands.size());
146 bool PrintedArg = false;
147 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
149 // Implicit physical register operand.
154 if (Operands[i] == "r") {
155 OS << "Op" << i << ", Op" << i << "IsKill";
157 } else if (Operands[i] == "i") {
160 } else if (Operands[i] == "f") {
164 assert("Unknown operand kind!");
170 void PrintArguments(raw_ostream &OS) const {
171 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
172 if (Operands[i] == "r") {
173 OS << "Op" << i << ", Op" << i << "IsKill";
174 } else if (Operands[i] == "i") {
176 } else if (Operands[i] == "f") {
179 assert("Unknown operand kind!");
188 void PrintManglingSuffix(raw_ostream &OS,
189 const std::vector<std::string>& PR) const {
190 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
192 // Implicit physical register operand. e.g. Instruction::Mul expect to
193 // select to a binary op. On x86, mul may take a single operand with
194 // the other operand being implicit. We must emit something that looks
195 // like a binary instruction except for the very inner FastEmitInst_*
202 void PrintManglingSuffix(raw_ostream &OS) const {
203 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
210 typedef std::map<std::string, InstructionMemo> PredMap;
211 typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap;
212 typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap;
213 typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap;
214 typedef std::map<OperandsSignature, OpcodeTypeRetPredMap>
215 OperandsOpcodeTypeRetPredMap;
217 OperandsOpcodeTypeRetPredMap SimplePatterns;
222 explicit FastISelMap(std::string InstNS);
224 void CollectPatterns(CodeGenDAGPatterns &CGP);
225 void PrintFunctionDefinitions(raw_ostream &OS);
230 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
231 return CGP.getSDNodeInfo(Op).getEnumName();
234 static std::string getLegalCName(std::string OpName) {
235 std::string::size_type pos = OpName.find("::");
236 if (pos != std::string::npos)
237 OpName.replace(pos, 2, "_");
241 FastISelMap::FastISelMap(std::string instns)
245 void FastISelMap::CollectPatterns(CodeGenDAGPatterns &CGP) {
246 const CodeGenTarget &Target = CGP.getTargetInfo();
248 // Determine the target's namespace name.
249 InstNS = Target.getInstNamespace() + "::";
250 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
252 // Scan through all the patterns and record the simple ones.
253 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
254 E = CGP.ptm_end(); I != E; ++I) {
255 const PatternToMatch &Pattern = *I;
257 // For now, just look at Instructions, so that we don't have to worry
258 // about emitting multiple instructions for a pattern.
259 TreePatternNode *Dst = Pattern.getDstPattern();
260 if (Dst->isLeaf()) continue;
261 Record *Op = Dst->getOperator();
262 if (!Op->isSubClassOf("Instruction"))
264 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op);
265 if (II.OperandList.empty())
268 // For now, ignore multi-instruction patterns.
269 bool MultiInsts = false;
270 for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) {
271 TreePatternNode *ChildOp = Dst->getChild(i);
272 if (ChildOp->isLeaf())
274 if (ChildOp->getOperator()->isSubClassOf("Instruction")) {
282 // For now, ignore instructions where the first operand is not an
284 const CodeGenRegisterClass *DstRC = 0;
285 std::string SubRegNo;
286 if (Op->getName() != "EXTRACT_SUBREG") {
287 Record *Op0Rec = II.OperandList[0].Rec;
288 if (!Op0Rec->isSubClassOf("RegisterClass"))
290 DstRC = &Target.getRegisterClass(Op0Rec);
294 // If this isn't a leaf, then continue since the register classes are
295 // a bit too complicated for now.
296 if (!Dst->getChild(1)->isLeaf()) continue;
298 DefInit *SR = dynamic_cast<DefInit*>(Dst->getChild(1)->getLeafValue());
300 SubRegNo = getQualifiedName(SR->getDef());
302 SubRegNo = Dst->getChild(1)->getLeafValue()->getAsString();
305 // Inspect the pattern.
306 TreePatternNode *InstPatNode = Pattern.getSrcPattern();
307 if (!InstPatNode) continue;
308 if (InstPatNode->isLeaf()) continue;
310 // Ignore multiple result nodes for now.
311 if (InstPatNode->getNumTypes() > 1) continue;
313 Record *InstPatOp = InstPatNode->getOperator();
314 std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
315 MVT::SimpleValueType RetVT = MVT::isVoid;
316 if (InstPatNode->getNumTypes()) RetVT = InstPatNode->getType(0);
317 MVT::SimpleValueType VT = RetVT;
318 if (InstPatNode->getNumChildren()) {
319 assert(InstPatNode->getChild(0)->getNumTypes() == 1);
320 VT = InstPatNode->getChild(0)->getType(0);
323 // For now, filter out instructions which just set a register to
324 // an Operand or an immediate, like MOV32ri.
325 if (InstPatOp->isSubClassOf("Operand"))
328 // For now, filter out any instructions with predicates.
329 if (!InstPatNode->getPredicateFns().empty())
332 // Check all the operands.
333 OperandsSignature Operands;
334 if (!Operands.initialize(InstPatNode, Target, VT))
337 std::vector<std::string>* PhysRegInputs = new std::vector<std::string>();
338 if (!InstPatNode->isLeaf() &&
339 (InstPatNode->getOperator()->getName() == "imm" ||
340 InstPatNode->getOperator()->getName() == "fpimmm"))
341 PhysRegInputs->push_back("");
342 else if (!InstPatNode->isLeaf()) {
343 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
344 TreePatternNode *Op = InstPatNode->getChild(i);
346 PhysRegInputs->push_back("");
350 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
351 Record *OpLeafRec = OpDI->getDef();
353 if (OpLeafRec->isSubClassOf("Register")) {
354 PhysReg += static_cast<StringInit*>(OpLeafRec->getValue( \
355 "Namespace")->getValue())->getValue();
358 std::vector<CodeGenRegister> Regs = Target.getRegisters();
359 for (unsigned i = 0; i < Regs.size(); ++i) {
360 if (Regs[i].TheDef == OpLeafRec) {
361 PhysReg += Regs[i].getName();
367 PhysRegInputs->push_back(PhysReg);
370 PhysRegInputs->push_back("");
372 // Get the predicate that guards this pattern.
373 std::string PredicateCheck = Pattern.getPredicateCheck();
375 // Ok, we found a pattern that we can handle. Remember it.
376 InstructionMemo Memo = {
377 Pattern.getDstPattern()->getOperator()->getName(),
382 assert(!SimplePatterns[Operands][OpcodeName][VT][RetVT]
383 .count(PredicateCheck) &&
384 "Duplicate pattern!");
385 SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo;
389 void FastISelMap::PrintFunctionDefinitions(raw_ostream &OS) {
390 // Now emit code for all the patterns that we collected.
391 for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
392 OE = SimplePatterns.end(); OI != OE; ++OI) {
393 const OperandsSignature &Operands = OI->first;
394 const OpcodeTypeRetPredMap &OTM = OI->second;
396 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
398 const std::string &Opcode = I->first;
399 const TypeRetPredMap &TM = I->second;
401 OS << "// FastEmit functions for " << Opcode << ".\n";
404 // Emit one function for each opcode,type pair.
405 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
407 MVT::SimpleValueType VT = TI->first;
408 const RetPredMap &RM = TI->second;
409 if (RM.size() != 1) {
410 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
412 MVT::SimpleValueType RetVT = RI->first;
413 const PredMap &PM = RI->second;
414 bool HasPred = false;
416 OS << "unsigned FastEmit_"
417 << getLegalCName(Opcode)
418 << "_" << getLegalCName(getName(VT))
419 << "_" << getLegalCName(getName(RetVT)) << "_";
420 Operands.PrintManglingSuffix(OS);
422 Operands.PrintParameters(OS);
425 // Emit code for each possible instruction. There may be
426 // multiple if there are subtarget concerns.
427 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
429 std::string PredicateCheck = PI->first;
430 const InstructionMemo &Memo = PI->second;
432 if (PredicateCheck.empty()) {
434 "Multiple instructions match, at least one has "
435 "a predicate and at least one doesn't!");
437 OS << " if (" + PredicateCheck + ") {\n";
442 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
443 if ((*Memo.PhysRegs)[i] != "")
444 OS << " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, "
445 << "TII.get(TargetOpcode::COPY), "
446 << (*Memo.PhysRegs)[i] << ").addReg(Op" << i << ");\n";
449 OS << " return FastEmitInst_";
450 if (Memo.SubRegNo.empty()) {
451 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
452 OS << "(" << InstNS << Memo.Name << ", ";
453 OS << InstNS << Memo.RC->getName() << "RegisterClass";
454 if (!Operands.empty())
456 Operands.PrintArguments(OS, *Memo.PhysRegs);
459 OS << "extractsubreg(" << getName(RetVT);
460 OS << ", Op0, Op0IsKill, ";
469 // Return 0 if none of the predicates were satisfied.
471 OS << " return 0;\n";
476 // Emit one function for the type that demultiplexes on return type.
477 OS << "unsigned FastEmit_"
478 << getLegalCName(Opcode) << "_"
479 << getLegalCName(getName(VT)) << "_";
480 Operands.PrintManglingSuffix(OS);
482 if (!Operands.empty())
484 Operands.PrintParameters(OS);
485 OS << ") {\nswitch (RetVT.SimpleTy) {\n";
486 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
488 MVT::SimpleValueType RetVT = RI->first;
489 OS << " case " << getName(RetVT) << ": return FastEmit_"
490 << getLegalCName(Opcode) << "_" << getLegalCName(getName(VT))
491 << "_" << getLegalCName(getName(RetVT)) << "_";
492 Operands.PrintManglingSuffix(OS);
494 Operands.PrintArguments(OS);
497 OS << " default: return 0;\n}\n}\n\n";
500 // Non-variadic return type.
501 OS << "unsigned FastEmit_"
502 << getLegalCName(Opcode) << "_"
503 << getLegalCName(getName(VT)) << "_";
504 Operands.PrintManglingSuffix(OS);
506 if (!Operands.empty())
508 Operands.PrintParameters(OS);
511 OS << " if (RetVT.SimpleTy != " << getName(RM.begin()->first)
512 << ")\n return 0;\n";
514 const PredMap &PM = RM.begin()->second;
515 bool HasPred = false;
517 // Emit code for each possible instruction. There may be
518 // multiple if there are subtarget concerns.
519 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end(); PI != PE;
521 std::string PredicateCheck = PI->first;
522 const InstructionMemo &Memo = PI->second;
524 if (PredicateCheck.empty()) {
526 "Multiple instructions match, at least one has "
527 "a predicate and at least one doesn't!");
529 OS << " if (" + PredicateCheck + ") {\n";
534 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
535 if ((*Memo.PhysRegs)[i] != "")
536 OS << " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, "
537 << "TII.get(TargetOpcode::COPY), "
538 << (*Memo.PhysRegs)[i] << ").addReg(Op" << i << ");\n";
541 OS << " return FastEmitInst_";
543 if (Memo.SubRegNo.empty()) {
544 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
545 OS << "(" << InstNS << Memo.Name << ", ";
546 OS << InstNS << Memo.RC->getName() << "RegisterClass";
547 if (!Operands.empty())
549 Operands.PrintArguments(OS, *Memo.PhysRegs);
552 OS << "extractsubreg(RetVT, Op0, Op0IsKill, ";
561 // Return 0 if none of the predicates were satisfied.
563 OS << " return 0;\n";
569 // Emit one function for the opcode that demultiplexes based on the type.
570 OS << "unsigned FastEmit_"
571 << getLegalCName(Opcode) << "_";
572 Operands.PrintManglingSuffix(OS);
573 OS << "(MVT VT, MVT RetVT";
574 if (!Operands.empty())
576 Operands.PrintParameters(OS);
578 OS << " switch (VT.SimpleTy) {\n";
579 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
581 MVT::SimpleValueType VT = TI->first;
582 std::string TypeName = getName(VT);
583 OS << " case " << TypeName << ": return FastEmit_"
584 << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
585 Operands.PrintManglingSuffix(OS);
587 if (!Operands.empty())
589 Operands.PrintArguments(OS);
592 OS << " default: return 0;\n";
598 OS << "// Top-level FastEmit function.\n";
601 // Emit one function for the operand signature that demultiplexes based
602 // on opcode and type.
603 OS << "unsigned FastEmit_";
604 Operands.PrintManglingSuffix(OS);
605 OS << "(MVT VT, MVT RetVT, unsigned Opcode";
606 if (!Operands.empty())
608 Operands.PrintParameters(OS);
610 OS << " switch (Opcode) {\n";
611 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
613 const std::string &Opcode = I->first;
615 OS << " case " << Opcode << ": return FastEmit_"
616 << getLegalCName(Opcode) << "_";
617 Operands.PrintManglingSuffix(OS);
619 if (!Operands.empty())
621 Operands.PrintArguments(OS);
624 OS << " default: return 0;\n";
631 void FastISelEmitter::run(raw_ostream &OS) {
632 const CodeGenTarget &Target = CGP.getTargetInfo();
634 // Determine the target's namespace name.
635 std::string InstNS = Target.getInstNamespace() + "::";
636 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
638 EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
639 Target.getName() + " target", OS);
641 FastISelMap F(InstNS);
642 F.CollectPatterns(CGP);
643 F.PrintFunctionDefinitions(OS);
646 FastISelEmitter::FastISelEmitter(RecordKeeper &R)