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) {
57 if (!InstPatNode->isLeaf()) {
58 if (InstPatNode->getOperator()->getName() == "imm") {
59 Operands.push_back("i");
62 if (InstPatNode->getOperator()->getName() == "fpimm") {
63 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 // For now, filter out any operand with multiple values.
74 if (!Op->getPredicateFns().empty() ||
75 Op->getNumTypes() != 1)
78 assert(Op->hasTypeSet(0) && "Type infererence not done?");
79 // For now, all the operands must have the same type.
80 if (Op->getType(0) != VT)
84 if (Op->getOperator()->getName() == "imm") {
85 Operands.push_back("i");
88 if (Op->getOperator()->getName() == "fpimm") {
89 Operands.push_back("f");
92 // For now, ignore other non-leaf nodes.
95 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
98 Record *OpLeafRec = OpDI->getDef();
99 // For now, the only other thing we accept is register operands.
101 const CodeGenRegisterClass *RC = 0;
102 if (OpLeafRec->isSubClassOf("RegisterClass"))
103 RC = &Target.getRegisterClass(OpLeafRec);
104 else if (OpLeafRec->isSubClassOf("Register"))
105 RC = Target.getRegisterClassForRegister(OpLeafRec);
108 // For now, require the register operands' register classes to all
112 // For now, all the operands must have the same register class.
118 Operands.push_back("r");
123 void PrintParameters(raw_ostream &OS) const {
124 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
125 if (Operands[i] == "r") {
126 OS << "unsigned Op" << i << ", bool Op" << i << "IsKill";
127 } else if (Operands[i] == "i") {
128 OS << "uint64_t imm" << i;
129 } else if (Operands[i] == "f") {
130 OS << "ConstantFP *f" << i;
132 assert("Unknown operand kind!");
140 void PrintArguments(raw_ostream &OS,
141 const std::vector<std::string>& PR) const {
142 assert(PR.size() == Operands.size());
143 bool PrintedArg = false;
144 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
146 // Implicit physical register operand.
151 if (Operands[i] == "r") {
152 OS << "Op" << i << ", Op" << i << "IsKill";
154 } else if (Operands[i] == "i") {
157 } else if (Operands[i] == "f") {
161 assert("Unknown operand kind!");
167 void PrintArguments(raw_ostream &OS) const {
168 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
169 if (Operands[i] == "r") {
170 OS << "Op" << i << ", Op" << i << "IsKill";
171 } else if (Operands[i] == "i") {
173 } else if (Operands[i] == "f") {
176 assert("Unknown operand kind!");
185 void PrintManglingSuffix(raw_ostream &OS,
186 const std::vector<std::string>& PR) const {
187 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
189 // Implicit physical register operand. e.g. Instruction::Mul expect to
190 // select to a binary op. On x86, mul may take a single operand with
191 // the other operand being implicit. We must emit something that looks
192 // like a binary instruction except for the very inner FastEmitInst_*
199 void PrintManglingSuffix(raw_ostream &OS) const {
200 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
207 typedef std::map<std::string, InstructionMemo> PredMap;
208 typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap;
209 typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap;
210 typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap;
211 typedef std::map<OperandsSignature, OpcodeTypeRetPredMap> OperandsOpcodeTypeRetPredMap;
213 OperandsOpcodeTypeRetPredMap SimplePatterns;
218 explicit FastISelMap(std::string InstNS);
220 void CollectPatterns(CodeGenDAGPatterns &CGP);
221 void PrintFunctionDefinitions(raw_ostream &OS);
226 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
227 return CGP.getSDNodeInfo(Op).getEnumName();
230 static std::string getLegalCName(std::string OpName) {
231 std::string::size_type pos = OpName.find("::");
232 if (pos != std::string::npos)
233 OpName.replace(pos, 2, "_");
237 FastISelMap::FastISelMap(std::string instns)
241 void FastISelMap::CollectPatterns(CodeGenDAGPatterns &CGP) {
242 const CodeGenTarget &Target = CGP.getTargetInfo();
244 // Determine the target's namespace name.
245 InstNS = Target.getInstNamespace() + "::";
246 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
248 // Scan through all the patterns and record the simple ones.
249 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
250 E = CGP.ptm_end(); I != E; ++I) {
251 const PatternToMatch &Pattern = *I;
253 // For now, just look at Instructions, so that we don't have to worry
254 // about emitting multiple instructions for a pattern.
255 TreePatternNode *Dst = Pattern.getDstPattern();
256 if (Dst->isLeaf()) continue;
257 Record *Op = Dst->getOperator();
258 if (!Op->isSubClassOf("Instruction"))
260 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op);
261 if (II.OperandList.empty())
264 // For now, ignore multi-instruction patterns.
265 bool MultiInsts = false;
266 for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) {
267 TreePatternNode *ChildOp = Dst->getChild(i);
268 if (ChildOp->isLeaf())
270 if (ChildOp->getOperator()->isSubClassOf("Instruction")) {
278 // For now, ignore instructions where the first operand is not an
280 const CodeGenRegisterClass *DstRC = 0;
281 std::string SubRegNo;
282 if (Op->getName() != "EXTRACT_SUBREG") {
283 Record *Op0Rec = II.OperandList[0].Rec;
284 if (!Op0Rec->isSubClassOf("RegisterClass"))
286 DstRC = &Target.getRegisterClass(Op0Rec);
290 DefInit *SR = dynamic_cast<DefInit*>(Dst->getChild(1)->getLeafValue());
292 SubRegNo = getQualifiedName(SR->getDef());
294 SubRegNo = Dst->getChild(1)->getLeafValue()->getAsString();
297 // Inspect the pattern.
298 TreePatternNode *InstPatNode = Pattern.getSrcPattern();
299 if (!InstPatNode) continue;
300 if (InstPatNode->isLeaf()) continue;
302 // Ignore multiple result nodes for now.
303 if (InstPatNode->getNumTypes() > 1) continue;
305 Record *InstPatOp = InstPatNode->getOperator();
306 std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
307 MVT::SimpleValueType RetVT = MVT::isVoid;
308 if (InstPatNode->getNumTypes()) RetVT = InstPatNode->getType(0);
309 MVT::SimpleValueType VT = RetVT;
310 if (InstPatNode->getNumChildren()) {
311 assert(InstPatNode->getChild(0)->getNumTypes() == 1);
312 VT = InstPatNode->getChild(0)->getType(0);
315 // For now, filter out instructions which just set a register to
316 // an Operand or an immediate, like MOV32ri.
317 if (InstPatOp->isSubClassOf("Operand"))
320 // For now, filter out any instructions with predicates.
321 if (!InstPatNode->getPredicateFns().empty())
324 // Check all the operands.
325 OperandsSignature Operands;
326 if (!Operands.initialize(InstPatNode, Target, VT))
329 std::vector<std::string>* PhysRegInputs = new std::vector<std::string>();
330 if (!InstPatNode->isLeaf() &&
331 (InstPatNode->getOperator()->getName() == "imm" ||
332 InstPatNode->getOperator()->getName() == "fpimmm"))
333 PhysRegInputs->push_back("");
334 else if (!InstPatNode->isLeaf()) {
335 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
336 TreePatternNode *Op = InstPatNode->getChild(i);
338 PhysRegInputs->push_back("");
342 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
343 Record *OpLeafRec = OpDI->getDef();
345 if (OpLeafRec->isSubClassOf("Register")) {
346 PhysReg += static_cast<StringInit*>(OpLeafRec->getValue( \
347 "Namespace")->getValue())->getValue();
350 std::vector<CodeGenRegister> Regs = Target.getRegisters();
351 for (unsigned i = 0; i < Regs.size(); ++i) {
352 if (Regs[i].TheDef == OpLeafRec) {
353 PhysReg += Regs[i].getName();
359 PhysRegInputs->push_back(PhysReg);
362 PhysRegInputs->push_back("");
364 // Get the predicate that guards this pattern.
365 std::string PredicateCheck = Pattern.getPredicateCheck();
367 // Ok, we found a pattern that we can handle. Remember it.
368 InstructionMemo Memo = {
369 Pattern.getDstPattern()->getOperator()->getName(),
374 assert(!SimplePatterns[Operands][OpcodeName][VT][RetVT].count(PredicateCheck) &&
375 "Duplicate pattern!");
376 SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo;
380 void FastISelMap::PrintFunctionDefinitions(raw_ostream &OS) {
381 // Now emit code for all the patterns that we collected.
382 for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
383 OE = SimplePatterns.end(); OI != OE; ++OI) {
384 const OperandsSignature &Operands = OI->first;
385 const OpcodeTypeRetPredMap &OTM = OI->second;
387 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
389 const std::string &Opcode = I->first;
390 const TypeRetPredMap &TM = I->second;
392 OS << "// FastEmit functions for " << Opcode << ".\n";
395 // Emit one function for each opcode,type pair.
396 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
398 MVT::SimpleValueType VT = TI->first;
399 const RetPredMap &RM = TI->second;
400 if (RM.size() != 1) {
401 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
403 MVT::SimpleValueType RetVT = RI->first;
404 const PredMap &PM = RI->second;
405 bool HasPred = false;
407 OS << "unsigned FastEmit_"
408 << getLegalCName(Opcode)
409 << "_" << getLegalCName(getName(VT))
410 << "_" << getLegalCName(getName(RetVT)) << "_";
411 Operands.PrintManglingSuffix(OS);
413 Operands.PrintParameters(OS);
416 // Emit code for each possible instruction. There may be
417 // multiple if there are subtarget concerns.
418 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
420 std::string PredicateCheck = PI->first;
421 const InstructionMemo &Memo = PI->second;
423 if (PredicateCheck.empty()) {
425 "Multiple instructions match, at least one has "
426 "a predicate and at least one doesn't!");
428 OS << " if (" + PredicateCheck + ") {\n";
433 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
434 if ((*Memo.PhysRegs)[i] != "")
435 OS << " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, "
436 << "TII.get(TargetOpcode::COPY), "
437 << (*Memo.PhysRegs)[i] << ").addReg(Op" << i << ");\n";
440 OS << " return FastEmitInst_";
441 if (Memo.SubRegNo.empty()) {
442 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
443 OS << "(" << InstNS << Memo.Name << ", ";
444 OS << InstNS << Memo.RC->getName() << "RegisterClass";
445 if (!Operands.empty())
447 Operands.PrintArguments(OS, *Memo.PhysRegs);
450 OS << "extractsubreg(" << getName(RetVT);
451 OS << ", Op0, Op0IsKill, ";
460 // Return 0 if none of the predicates were satisfied.
462 OS << " return 0;\n";
467 // Emit one function for the type that demultiplexes on return type.
468 OS << "unsigned FastEmit_"
469 << getLegalCName(Opcode) << "_"
470 << getLegalCName(getName(VT)) << "_";
471 Operands.PrintManglingSuffix(OS);
473 if (!Operands.empty())
475 Operands.PrintParameters(OS);
476 OS << ") {\nswitch (RetVT.SimpleTy) {\n";
477 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
479 MVT::SimpleValueType RetVT = RI->first;
480 OS << " case " << getName(RetVT) << ": return FastEmit_"
481 << getLegalCName(Opcode) << "_" << getLegalCName(getName(VT))
482 << "_" << getLegalCName(getName(RetVT)) << "_";
483 Operands.PrintManglingSuffix(OS);
485 Operands.PrintArguments(OS);
488 OS << " default: return 0;\n}\n}\n\n";
491 // Non-variadic return type.
492 OS << "unsigned FastEmit_"
493 << getLegalCName(Opcode) << "_"
494 << getLegalCName(getName(VT)) << "_";
495 Operands.PrintManglingSuffix(OS);
497 if (!Operands.empty())
499 Operands.PrintParameters(OS);
502 OS << " if (RetVT.SimpleTy != " << getName(RM.begin()->first)
503 << ")\n return 0;\n";
505 const PredMap &PM = RM.begin()->second;
506 bool HasPred = false;
508 // Emit code for each possible instruction. There may be
509 // multiple if there are subtarget concerns.
510 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end(); PI != PE;
512 std::string PredicateCheck = PI->first;
513 const InstructionMemo &Memo = PI->second;
515 if (PredicateCheck.empty()) {
517 "Multiple instructions match, at least one has "
518 "a predicate and at least one doesn't!");
520 OS << " if (" + PredicateCheck + ") {\n";
525 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
526 if ((*Memo.PhysRegs)[i] != "")
527 OS << " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, "
528 << "TII.get(TargetOpcode::COPY), "
529 << (*Memo.PhysRegs)[i] << ").addReg(Op" << i << ");\n";
532 OS << " return FastEmitInst_";
534 if (Memo.SubRegNo.empty()) {
535 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
536 OS << "(" << InstNS << Memo.Name << ", ";
537 OS << InstNS << Memo.RC->getName() << "RegisterClass";
538 if (!Operands.empty())
540 Operands.PrintArguments(OS, *Memo.PhysRegs);
543 OS << "extractsubreg(RetVT, Op0, Op0IsKill, ";
552 // Return 0 if none of the predicates were satisfied.
554 OS << " return 0;\n";
560 // Emit one function for the opcode that demultiplexes based on the type.
561 OS << "unsigned FastEmit_"
562 << getLegalCName(Opcode) << "_";
563 Operands.PrintManglingSuffix(OS);
564 OS << "(MVT VT, MVT RetVT";
565 if (!Operands.empty())
567 Operands.PrintParameters(OS);
569 OS << " switch (VT.SimpleTy) {\n";
570 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
572 MVT::SimpleValueType VT = TI->first;
573 std::string TypeName = getName(VT);
574 OS << " case " << TypeName << ": return FastEmit_"
575 << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
576 Operands.PrintManglingSuffix(OS);
578 if (!Operands.empty())
580 Operands.PrintArguments(OS);
583 OS << " default: return 0;\n";
589 OS << "// Top-level FastEmit function.\n";
592 // Emit one function for the operand signature that demultiplexes based
593 // on opcode and type.
594 OS << "unsigned FastEmit_";
595 Operands.PrintManglingSuffix(OS);
596 OS << "(MVT VT, MVT RetVT, unsigned Opcode";
597 if (!Operands.empty())
599 Operands.PrintParameters(OS);
601 OS << " switch (Opcode) {\n";
602 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
604 const std::string &Opcode = I->first;
606 OS << " case " << Opcode << ": return FastEmit_"
607 << getLegalCName(Opcode) << "_";
608 Operands.PrintManglingSuffix(OS);
610 if (!Operands.empty())
612 Operands.PrintArguments(OS);
615 OS << " default: return 0;\n";
622 void FastISelEmitter::run(raw_ostream &OS) {
623 const CodeGenTarget &Target = CGP.getTargetInfo();
625 // Determine the target's namespace name.
626 std::string InstNS = Target.getInstNamespace() + "::";
627 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
629 EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
630 Target.getName() + " target", OS);
632 FastISelMap F(InstNS);
633 F.CollectPatterns(CGP);
634 F.PrintFunctionDefinitions(OS);
637 FastISelEmitter::FastISelEmitter(RecordKeeper &R)