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 if (Op
->getExtTypes().size() != 1)
78 // For now, all the operands must have the same type.
79 if (Op
->getTypeNum(0) != VT
)
82 if (Op
->getOperator()->getName() == "imm") {
83 Operands
.push_back("i");
86 if (Op
->getOperator()->getName() == "fpimm") {
87 Operands
.push_back("f");
90 // For now, ignore other non-leaf nodes.
93 DefInit
*OpDI
= dynamic_cast<DefInit
*>(Op
->getLeafValue());
96 Record
*OpLeafRec
= OpDI
->getDef();
97 // For now, the only other thing we accept is register operands.
99 const CodeGenRegisterClass
*RC
= 0;
100 if (OpLeafRec
->isSubClassOf("RegisterClass"))
101 RC
= &Target
.getRegisterClass(OpLeafRec
);
102 else if (OpLeafRec
->isSubClassOf("Register"))
103 RC
= Target
.getRegisterClassForRegister(OpLeafRec
);
106 // For now, require the register operands' register classes to all
110 // For now, all the operands must have the same register class.
116 Operands
.push_back("r");
121 void PrintParameters(raw_ostream
&OS
) const {
122 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
123 if (Operands
[i
] == "r") {
124 OS
<< "unsigned Op" << i
;
125 } else if (Operands
[i
] == "i") {
126 OS
<< "uint64_t imm" << i
;
127 } else if (Operands
[i
] == "f") {
128 OS
<< "ConstantFP *f" << i
;
130 assert("Unknown operand kind!");
138 void PrintArguments(raw_ostream
&OS
,
139 const std::vector
<std::string
>& PR
) const {
140 assert(PR
.size() == Operands
.size());
141 bool PrintedArg
= false;
142 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
144 // Implicit physical register operand.
149 if (Operands
[i
] == "r") {
152 } else if (Operands
[i
] == "i") {
155 } else if (Operands
[i
] == "f") {
159 assert("Unknown operand kind!");
165 void PrintArguments(raw_ostream
&OS
) const {
166 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
167 if (Operands
[i
] == "r") {
169 } else if (Operands
[i
] == "i") {
171 } else if (Operands
[i
] == "f") {
174 assert("Unknown operand kind!");
183 void PrintManglingSuffix(raw_ostream
&OS
,
184 const std::vector
<std::string
>& PR
) const {
185 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
187 // Implicit physical register operand. e.g. Instruction::Mul expect to
188 // select to a binary op. On x86, mul may take a single operand with
189 // the other operand being implicit. We must emit something that looks
190 // like a binary instruction except for the very inner FastEmitInst_*
197 void PrintManglingSuffix(raw_ostream
&OS
) const {
198 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
205 typedef std::map
<std::string
, InstructionMemo
> PredMap
;
206 typedef std::map
<MVT::SimpleValueType
, PredMap
> RetPredMap
;
207 typedef std::map
<MVT::SimpleValueType
, RetPredMap
> TypeRetPredMap
;
208 typedef std::map
<std::string
, TypeRetPredMap
> OpcodeTypeRetPredMap
;
209 typedef std::map
<OperandsSignature
, OpcodeTypeRetPredMap
> OperandsOpcodeTypeRetPredMap
;
211 OperandsOpcodeTypeRetPredMap SimplePatterns
;
216 explicit FastISelMap(std::string InstNS
);
218 void CollectPatterns(CodeGenDAGPatterns
&CGP
);
219 void PrintClass(raw_ostream
&OS
);
220 void PrintFunctionDefinitions(raw_ostream
&OS
);
225 static std::string
getOpcodeName(Record
*Op
, CodeGenDAGPatterns
&CGP
) {
226 return CGP
.getSDNodeInfo(Op
).getEnumName();
229 static std::string
getLegalCName(std::string OpName
) {
230 std::string::size_type pos
= OpName
.find("::");
231 if (pos
!= std::string::npos
)
232 OpName
.replace(pos
, 2, "_");
236 FastISelMap::FastISelMap(std::string instns
)
240 void FastISelMap::CollectPatterns(CodeGenDAGPatterns
&CGP
) {
241 const CodeGenTarget
&Target
= CGP
.getTargetInfo();
243 // Determine the target's namespace name.
244 InstNS
= Target
.getInstNamespace() + "::";
245 assert(InstNS
.size() > 2 && "Can't determine target-specific namespace!");
247 // Scan through all the patterns and record the simple ones.
248 for (CodeGenDAGPatterns::ptm_iterator I
= CGP
.ptm_begin(),
249 E
= CGP
.ptm_end(); I
!= E
; ++I
) {
250 const PatternToMatch
&Pattern
= *I
;
252 // For now, just look at Instructions, so that we don't have to worry
253 // about emitting multiple instructions for a pattern.
254 TreePatternNode
*Dst
= Pattern
.getDstPattern();
255 if (Dst
->isLeaf()) continue;
256 Record
*Op
= Dst
->getOperator();
257 if (!Op
->isSubClassOf("Instruction"))
259 CodeGenInstruction
&II
= CGP
.getTargetInfo().getInstruction(Op
->getName());
260 if (II
.OperandList
.empty())
263 // For now, ignore multi-instruction patterns.
264 bool MultiInsts
= false;
265 for (unsigned i
= 0, e
= Dst
->getNumChildren(); i
!= e
; ++i
) {
266 TreePatternNode
*ChildOp
= Dst
->getChild(i
);
267 if (ChildOp
->isLeaf())
269 if (ChildOp
->getOperator()->isSubClassOf("Instruction")) {
277 // For now, ignore instructions where the first operand is not an
279 const CodeGenRegisterClass
*DstRC
= 0;
280 unsigned SubRegNo
= ~0;
281 if (Op
->getName() != "EXTRACT_SUBREG") {
282 Record
*Op0Rec
= II
.OperandList
[0].Rec
;
283 if (!Op0Rec
->isSubClassOf("RegisterClass"))
285 DstRC
= &Target
.getRegisterClass(Op0Rec
);
289 SubRegNo
= static_cast<IntInit
*>(
290 Dst
->getChild(1)->getLeafValue())->getValue();
293 // Inspect the pattern.
294 TreePatternNode
*InstPatNode
= Pattern
.getSrcPattern();
295 if (!InstPatNode
) continue;
296 if (InstPatNode
->isLeaf()) continue;
298 Record
*InstPatOp
= InstPatNode
->getOperator();
299 std::string OpcodeName
= getOpcodeName(InstPatOp
, CGP
);
300 MVT::SimpleValueType RetVT
= InstPatNode
->getTypeNum(0);
301 MVT::SimpleValueType VT
= RetVT
;
302 if (InstPatNode
->getNumChildren())
303 VT
= InstPatNode
->getChild(0)->getTypeNum(0);
305 // For now, filter out instructions which just set a register to
306 // an Operand or an immediate, like MOV32ri.
307 if (InstPatOp
->isSubClassOf("Operand"))
310 // For now, filter out any instructions with predicates.
311 if (!InstPatNode
->getPredicateFns().empty())
314 // Check all the operands.
315 OperandsSignature Operands
;
316 if (!Operands
.initialize(InstPatNode
, Target
, VT
))
319 std::vector
<std::string
>* PhysRegInputs
= new std::vector
<std::string
>();
320 if (!InstPatNode
->isLeaf() &&
321 (InstPatNode
->getOperator()->getName() == "imm" ||
322 InstPatNode
->getOperator()->getName() == "fpimmm"))
323 PhysRegInputs
->push_back("");
324 else if (!InstPatNode
->isLeaf()) {
325 for (unsigned i
= 0, e
= InstPatNode
->getNumChildren(); i
!= e
; ++i
) {
326 TreePatternNode
*Op
= InstPatNode
->getChild(i
);
328 PhysRegInputs
->push_back("");
332 DefInit
*OpDI
= dynamic_cast<DefInit
*>(Op
->getLeafValue());
333 Record
*OpLeafRec
= OpDI
->getDef();
335 if (OpLeafRec
->isSubClassOf("Register")) {
336 PhysReg
+= static_cast<StringInit
*>(OpLeafRec
->getValue( \
337 "Namespace")->getValue())->getValue();
340 std::vector
<CodeGenRegister
> Regs
= Target
.getRegisters();
341 for (unsigned i
= 0; i
< Regs
.size(); ++i
) {
342 if (Regs
[i
].TheDef
== OpLeafRec
) {
343 PhysReg
+= Regs
[i
].getName();
349 PhysRegInputs
->push_back(PhysReg
);
352 PhysRegInputs
->push_back("");
354 // Get the predicate that guards this pattern.
355 std::string PredicateCheck
= Pattern
.getPredicateCheck();
357 // Ok, we found a pattern that we can handle. Remember it.
358 InstructionMemo Memo
= {
359 Pattern
.getDstPattern()->getOperator()->getName(),
364 assert(!SimplePatterns
[Operands
][OpcodeName
][VT
][RetVT
].count(PredicateCheck
) &&
365 "Duplicate pattern!");
366 SimplePatterns
[Operands
][OpcodeName
][VT
][RetVT
][PredicateCheck
] = Memo
;
370 void FastISelMap::PrintFunctionDefinitions(raw_ostream
&OS
) {
371 // Now emit code for all the patterns that we collected.
372 for (OperandsOpcodeTypeRetPredMap::const_iterator OI
= SimplePatterns
.begin(),
373 OE
= SimplePatterns
.end(); OI
!= OE
; ++OI
) {
374 const OperandsSignature
&Operands
= OI
->first
;
375 const OpcodeTypeRetPredMap
&OTM
= OI
->second
;
377 for (OpcodeTypeRetPredMap::const_iterator I
= OTM
.begin(), E
= OTM
.end();
379 const std::string
&Opcode
= I
->first
;
380 const TypeRetPredMap
&TM
= I
->second
;
382 OS
<< "// FastEmit functions for " << Opcode
<< ".\n";
385 // Emit one function for each opcode,type pair.
386 for (TypeRetPredMap::const_iterator TI
= TM
.begin(), TE
= TM
.end();
388 MVT::SimpleValueType VT
= TI
->first
;
389 const RetPredMap
&RM
= TI
->second
;
390 if (RM
.size() != 1) {
391 for (RetPredMap::const_iterator RI
= RM
.begin(), RE
= RM
.end();
393 MVT::SimpleValueType RetVT
= RI
->first
;
394 const PredMap
&PM
= RI
->second
;
395 bool HasPred
= false;
397 OS
<< "unsigned FastEmit_"
398 << getLegalCName(Opcode
)
399 << "_" << getLegalCName(getName(VT
))
400 << "_" << getLegalCName(getName(RetVT
)) << "_";
401 Operands
.PrintManglingSuffix(OS
);
403 Operands
.PrintParameters(OS
);
406 // Emit code for each possible instruction. There may be
407 // multiple if there are subtarget concerns.
408 for (PredMap::const_iterator PI
= PM
.begin(), PE
= PM
.end();
410 std::string PredicateCheck
= PI
->first
;
411 const InstructionMemo
&Memo
= PI
->second
;
413 if (PredicateCheck
.empty()) {
415 "Multiple instructions match, at least one has "
416 "a predicate and at least one doesn't!");
418 OS
<< " if (" + PredicateCheck
+ ") {\n";
423 for (unsigned i
= 0; i
< Memo
.PhysRegs
->size(); ++i
) {
424 if ((*Memo
.PhysRegs
)[i
] != "")
425 OS
<< " TII.copyRegToReg(*MBB, MBB->end(), "
426 << (*Memo
.PhysRegs
)[i
] << ", Op" << i
<< ", "
427 << "TM.getRegisterInfo()->getPhysicalRegisterRegClass("
428 << (*Memo
.PhysRegs
)[i
] << "), "
429 << "MRI.getRegClass(Op" << i
<< "));\n";
432 OS
<< " return FastEmitInst_";
433 if (Memo
.SubRegNo
== (unsigned char)~0) {
434 Operands
.PrintManglingSuffix(OS
, *Memo
.PhysRegs
);
435 OS
<< "(" << InstNS
<< Memo
.Name
<< ", ";
436 OS
<< InstNS
<< Memo
.RC
->getName() << "RegisterClass";
437 if (!Operands
.empty())
439 Operands
.PrintArguments(OS
, *Memo
.PhysRegs
);
442 OS
<< "extractsubreg(" << getName(RetVT
);
444 OS
<< (unsigned)Memo
.SubRegNo
;
452 // Return 0 if none of the predicates were satisfied.
454 OS
<< " return 0;\n";
459 // Emit one function for the type that demultiplexes on return type.
460 OS
<< "unsigned FastEmit_"
461 << getLegalCName(Opcode
) << "_"
462 << getLegalCName(getName(VT
)) << "_";
463 Operands
.PrintManglingSuffix(OS
);
464 OS
<< "(MVT::SimpleValueType RetVT";
465 if (!Operands
.empty())
467 Operands
.PrintParameters(OS
);
468 OS
<< ") {\nswitch (RetVT) {\n";
469 for (RetPredMap::const_iterator RI
= RM
.begin(), RE
= RM
.end();
471 MVT::SimpleValueType RetVT
= RI
->first
;
472 OS
<< " case " << getName(RetVT
) << ": return FastEmit_"
473 << getLegalCName(Opcode
) << "_" << getLegalCName(getName(VT
))
474 << "_" << getLegalCName(getName(RetVT
)) << "_";
475 Operands
.PrintManglingSuffix(OS
);
477 Operands
.PrintArguments(OS
);
480 OS
<< " default: return 0;\n}\n}\n\n";
483 // Non-variadic return type.
484 OS
<< "unsigned FastEmit_"
485 << getLegalCName(Opcode
) << "_"
486 << getLegalCName(getName(VT
)) << "_";
487 Operands
.PrintManglingSuffix(OS
);
488 OS
<< "(MVT::SimpleValueType RetVT";
489 if (!Operands
.empty())
491 Operands
.PrintParameters(OS
);
494 OS
<< " if (RetVT != " << getName(RM
.begin()->first
)
495 << ")\n return 0;\n";
497 const PredMap
&PM
= RM
.begin()->second
;
498 bool HasPred
= false;
500 // Emit code for each possible instruction. There may be
501 // multiple if there are subtarget concerns.
502 for (PredMap::const_iterator PI
= PM
.begin(), PE
= PM
.end(); PI
!= PE
;
504 std::string PredicateCheck
= PI
->first
;
505 const InstructionMemo
&Memo
= PI
->second
;
507 if (PredicateCheck
.empty()) {
509 "Multiple instructions match, at least one has "
510 "a predicate and at least one doesn't!");
512 OS
<< " if (" + PredicateCheck
+ ") {\n";
517 for (unsigned i
= 0; i
< Memo
.PhysRegs
->size(); ++i
) {
518 if ((*Memo
.PhysRegs
)[i
] != "")
519 OS
<< " TII.copyRegToReg(*MBB, MBB->end(), "
520 << (*Memo
.PhysRegs
)[i
] << ", Op" << i
<< ", "
521 << "TM.getRegisterInfo()->getPhysicalRegisterRegClass("
522 << (*Memo
.PhysRegs
)[i
] << "), "
523 << "MRI.getRegClass(Op" << i
<< "));\n";
526 OS
<< " return FastEmitInst_";
528 if (Memo
.SubRegNo
== (unsigned char)~0) {
529 Operands
.PrintManglingSuffix(OS
, *Memo
.PhysRegs
);
530 OS
<< "(" << InstNS
<< Memo
.Name
<< ", ";
531 OS
<< InstNS
<< Memo
.RC
->getName() << "RegisterClass";
532 if (!Operands
.empty())
534 Operands
.PrintArguments(OS
, *Memo
.PhysRegs
);
537 OS
<< "extractsubreg(RetVT, Op0, ";
538 OS
<< (unsigned)Memo
.SubRegNo
;
546 // Return 0 if none of the predicates were satisfied.
548 OS
<< " return 0;\n";
554 // Emit one function for the opcode that demultiplexes based on the type.
555 OS
<< "unsigned FastEmit_"
556 << getLegalCName(Opcode
) << "_";
557 Operands
.PrintManglingSuffix(OS
);
558 OS
<< "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT";
559 if (!Operands
.empty())
561 Operands
.PrintParameters(OS
);
563 OS
<< " switch (VT) {\n";
564 for (TypeRetPredMap::const_iterator TI
= TM
.begin(), TE
= TM
.end();
566 MVT::SimpleValueType VT
= TI
->first
;
567 std::string TypeName
= getName(VT
);
568 OS
<< " case " << TypeName
<< ": return FastEmit_"
569 << getLegalCName(Opcode
) << "_" << getLegalCName(TypeName
) << "_";
570 Operands
.PrintManglingSuffix(OS
);
572 if (!Operands
.empty())
574 Operands
.PrintArguments(OS
);
577 OS
<< " default: return 0;\n";
583 OS
<< "// Top-level FastEmit function.\n";
586 // Emit one function for the operand signature that demultiplexes based
587 // on opcode and type.
588 OS
<< "unsigned FastEmit_";
589 Operands
.PrintManglingSuffix(OS
);
590 OS
<< "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT, ISD::NodeType Opcode";
591 if (!Operands
.empty())
593 Operands
.PrintParameters(OS
);
595 OS
<< " switch (Opcode) {\n";
596 for (OpcodeTypeRetPredMap::const_iterator I
= OTM
.begin(), E
= OTM
.end();
598 const std::string
&Opcode
= I
->first
;
600 OS
<< " case " << Opcode
<< ": return FastEmit_"
601 << getLegalCName(Opcode
) << "_";
602 Operands
.PrintManglingSuffix(OS
);
604 if (!Operands
.empty())
606 Operands
.PrintArguments(OS
);
609 OS
<< " default: return 0;\n";
616 void FastISelEmitter::run(raw_ostream
&OS
) {
617 const CodeGenTarget
&Target
= CGP
.getTargetInfo();
619 // Determine the target's namespace name.
620 std::string InstNS
= Target
.getInstNamespace() + "::";
621 assert(InstNS
.size() > 2 && "Can't determine target-specific namespace!");
623 EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
624 Target
.getName() + " target", OS
);
626 FastISelMap
F(InstNS
);
627 F
.CollectPatterns(CGP
);
628 F
.PrintFunctionDefinitions(OS
);
631 FastISelEmitter::FastISelEmitter(RecordKeeper
&R
)