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/SmallString.h"
24 #include "llvm/ADT/VectorExtras.h"
29 /// InstructionMemo - This class holds additional information about an
30 /// instruction needed to emit code for it.
32 struct InstructionMemo
{
34 const CodeGenRegisterClass
*RC
;
36 std::vector
<std::string
>* PhysRegs
;
39 /// OperandsSignature - This class holds a description of a list of operand
40 /// types. It has utility methods for emitting text based on the operands.
42 struct OperandsSignature
{
43 std::vector
<std::string
> Operands
;
45 bool operator<(const OperandsSignature
&O
) const {
46 return Operands
< O
.Operands
;
49 bool empty() const { return Operands
.empty(); }
51 /// initialize - Examine the given pattern and initialize the contents
52 /// of the Operands array accordingly. Return true if all the operands
53 /// are supported, false otherwise.
55 bool initialize(TreePatternNode
*InstPatNode
,
56 const CodeGenTarget
&Target
,
57 MVT::SimpleValueType VT
) {
59 if (!InstPatNode
->isLeaf()) {
60 if (InstPatNode
->getOperator()->getName() == "imm") {
61 Operands
.push_back("i");
64 if (InstPatNode
->getOperator()->getName() == "fpimm") {
65 Operands
.push_back("f");
70 const CodeGenRegisterClass
*DstRC
= 0;
72 for (unsigned i
= 0, e
= InstPatNode
->getNumChildren(); i
!= e
; ++i
) {
73 TreePatternNode
*Op
= InstPatNode
->getChild(i
);
75 // For now, filter out any operand with a predicate.
76 // For now, filter out any operand with multiple values.
77 if (!Op
->getPredicateFns().empty() ||
78 Op
->getNumTypes() != 1)
81 assert(Op
->hasTypeSet(0) && "Type infererence not done?");
82 // For now, all the operands must have the same type.
83 if (Op
->getType(0) != VT
)
87 if (Op
->getOperator()->getName() == "imm") {
88 Operands
.push_back("i");
91 if (Op
->getOperator()->getName() == "fpimm") {
92 Operands
.push_back("f");
95 // For now, ignore other non-leaf nodes.
98 DefInit
*OpDI
= dynamic_cast<DefInit
*>(Op
->getLeafValue());
101 Record
*OpLeafRec
= OpDI
->getDef();
102 // For now, the only other thing we accept is register operands.
104 const CodeGenRegisterClass
*RC
= 0;
105 if (OpLeafRec
->isSubClassOf("RegisterClass"))
106 RC
= &Target
.getRegisterClass(OpLeafRec
);
107 else if (OpLeafRec
->isSubClassOf("Register"))
108 RC
= Target
.getRegisterClassForRegister(OpLeafRec
);
112 // For now, this needs to be a register class of some sort.
116 // For now, all the operands must have the same register class or be
117 // a strict subclass of the destination.
119 if (DstRC
!= RC
&& !DstRC
->hasSubClass(RC
))
123 Operands
.push_back("r");
128 void PrintParameters(raw_ostream
&OS
) const {
129 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
130 if (Operands
[i
] == "r") {
131 OS
<< "unsigned Op" << i
<< ", bool Op" << i
<< "IsKill";
132 } else if (Operands
[i
] == "i") {
133 OS
<< "uint64_t imm" << i
;
134 } else if (Operands
[i
] == "f") {
135 OS
<< "ConstantFP *f" << i
;
137 assert("Unknown operand kind!");
145 void PrintArguments(raw_ostream
&OS
,
146 const std::vector
<std::string
>& PR
) const {
147 assert(PR
.size() == Operands
.size());
148 bool PrintedArg
= false;
149 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
151 // Implicit physical register operand.
156 if (Operands
[i
] == "r") {
157 OS
<< "Op" << i
<< ", Op" << i
<< "IsKill";
159 } else if (Operands
[i
] == "i") {
162 } else if (Operands
[i
] == "f") {
166 assert("Unknown operand kind!");
172 void PrintArguments(raw_ostream
&OS
) const {
173 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
174 if (Operands
[i
] == "r") {
175 OS
<< "Op" << i
<< ", Op" << i
<< "IsKill";
176 } else if (Operands
[i
] == "i") {
178 } else if (Operands
[i
] == "f") {
181 assert("Unknown operand kind!");
190 void PrintManglingSuffix(raw_ostream
&OS
,
191 const std::vector
<std::string
>& PR
) const {
192 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
194 // Implicit physical register operand. e.g. Instruction::Mul expect to
195 // select to a binary op. On x86, mul may take a single operand with
196 // the other operand being implicit. We must emit something that looks
197 // like a binary instruction except for the very inner FastEmitInst_*
204 void PrintManglingSuffix(raw_ostream
&OS
) const {
205 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
212 typedef std::map
<std::string
, InstructionMemo
> PredMap
;
213 typedef std::map
<MVT::SimpleValueType
, PredMap
> RetPredMap
;
214 typedef std::map
<MVT::SimpleValueType
, RetPredMap
> TypeRetPredMap
;
215 typedef std::map
<std::string
, TypeRetPredMap
> OpcodeTypeRetPredMap
;
216 typedef std::map
<OperandsSignature
, OpcodeTypeRetPredMap
>
217 OperandsOpcodeTypeRetPredMap
;
219 OperandsOpcodeTypeRetPredMap SimplePatterns
;
224 explicit FastISelMap(std::string InstNS
);
226 void CollectPatterns(CodeGenDAGPatterns
&CGP
);
227 void PrintFunctionDefinitions(raw_ostream
&OS
);
232 static std::string
getOpcodeName(Record
*Op
, CodeGenDAGPatterns
&CGP
) {
233 return CGP
.getSDNodeInfo(Op
).getEnumName();
236 static std::string
getLegalCName(std::string OpName
) {
237 std::string::size_type pos
= OpName
.find("::");
238 if (pos
!= std::string::npos
)
239 OpName
.replace(pos
, 2, "_");
243 FastISelMap::FastISelMap(std::string instns
)
247 void FastISelMap::CollectPatterns(CodeGenDAGPatterns
&CGP
) {
248 const CodeGenTarget
&Target
= CGP
.getTargetInfo();
250 // Determine the target's namespace name.
251 InstNS
= Target
.getInstNamespace() + "::";
252 assert(InstNS
.size() > 2 && "Can't determine target-specific namespace!");
254 // Scan through all the patterns and record the simple ones.
255 for (CodeGenDAGPatterns::ptm_iterator I
= CGP
.ptm_begin(),
256 E
= CGP
.ptm_end(); I
!= E
; ++I
) {
257 const PatternToMatch
&Pattern
= *I
;
259 // For now, just look at Instructions, so that we don't have to worry
260 // about emitting multiple instructions for a pattern.
261 TreePatternNode
*Dst
= Pattern
.getDstPattern();
262 if (Dst
->isLeaf()) continue;
263 Record
*Op
= Dst
->getOperator();
264 if (!Op
->isSubClassOf("Instruction"))
266 CodeGenInstruction
&II
= CGP
.getTargetInfo().getInstruction(Op
);
267 if (II
.Operands
.size() == 0)
270 // For now, ignore multi-instruction patterns.
271 bool MultiInsts
= false;
272 for (unsigned i
= 0, e
= Dst
->getNumChildren(); i
!= e
; ++i
) {
273 TreePatternNode
*ChildOp
= Dst
->getChild(i
);
274 if (ChildOp
->isLeaf())
276 if (ChildOp
->getOperator()->isSubClassOf("Instruction")) {
284 // For now, ignore instructions where the first operand is not an
286 const CodeGenRegisterClass
*DstRC
= 0;
287 std::string SubRegNo
;
288 if (Op
->getName() != "EXTRACT_SUBREG") {
289 Record
*Op0Rec
= II
.Operands
[0].Rec
;
290 if (!Op0Rec
->isSubClassOf("RegisterClass"))
292 DstRC
= &Target
.getRegisterClass(Op0Rec
);
296 // If this isn't a leaf, then continue since the register classes are
297 // a bit too complicated for now.
298 if (!Dst
->getChild(1)->isLeaf()) continue;
300 DefInit
*SR
= dynamic_cast<DefInit
*>(Dst
->getChild(1)->getLeafValue());
302 SubRegNo
= getQualifiedName(SR
->getDef());
304 SubRegNo
= Dst
->getChild(1)->getLeafValue()->getAsString();
307 // Inspect the pattern.
308 TreePatternNode
*InstPatNode
= Pattern
.getSrcPattern();
309 if (!InstPatNode
) continue;
310 if (InstPatNode
->isLeaf()) continue;
312 // Ignore multiple result nodes for now.
313 if (InstPatNode
->getNumTypes() > 1) continue;
315 Record
*InstPatOp
= InstPatNode
->getOperator();
316 std::string OpcodeName
= getOpcodeName(InstPatOp
, CGP
);
317 MVT::SimpleValueType RetVT
= MVT::isVoid
;
318 if (InstPatNode
->getNumTypes()) RetVT
= InstPatNode
->getType(0);
319 MVT::SimpleValueType VT
= RetVT
;
320 if (InstPatNode
->getNumChildren()) {
321 assert(InstPatNode
->getChild(0)->getNumTypes() == 1);
322 VT
= InstPatNode
->getChild(0)->getType(0);
325 // For now, filter out instructions which just set a register to
326 // an Operand or an immediate, like MOV32ri.
327 if (InstPatOp
->isSubClassOf("Operand"))
330 // For now, filter out any instructions with predicates.
331 if (!InstPatNode
->getPredicateFns().empty())
334 // Check all the operands.
335 OperandsSignature Operands
;
336 if (!Operands
.initialize(InstPatNode
, Target
, VT
))
339 std::vector
<std::string
>* PhysRegInputs
= new std::vector
<std::string
>();
340 if (!InstPatNode
->isLeaf() &&
341 (InstPatNode
->getOperator()->getName() == "imm" ||
342 InstPatNode
->getOperator()->getName() == "fpimmm"))
343 PhysRegInputs
->push_back("");
344 else if (!InstPatNode
->isLeaf()) {
345 for (unsigned i
= 0, e
= InstPatNode
->getNumChildren(); i
!= e
; ++i
) {
346 TreePatternNode
*Op
= InstPatNode
->getChild(i
);
348 PhysRegInputs
->push_back("");
352 DefInit
*OpDI
= dynamic_cast<DefInit
*>(Op
->getLeafValue());
353 Record
*OpLeafRec
= OpDI
->getDef();
355 if (OpLeafRec
->isSubClassOf("Register")) {
356 PhysReg
+= static_cast<StringInit
*>(OpLeafRec
->getValue( \
357 "Namespace")->getValue())->getValue();
360 std::vector
<CodeGenRegister
> Regs
= Target
.getRegisters();
361 for (unsigned i
= 0; i
< Regs
.size(); ++i
) {
362 if (Regs
[i
].TheDef
== OpLeafRec
) {
363 PhysReg
+= Regs
[i
].getName();
369 PhysRegInputs
->push_back(PhysReg
);
372 PhysRegInputs
->push_back("");
374 // Get the predicate that guards this pattern.
375 std::string PredicateCheck
= Pattern
.getPredicateCheck();
377 // Ok, we found a pattern that we can handle. Remember it.
378 InstructionMemo Memo
= {
379 Pattern
.getDstPattern()->getOperator()->getName(),
384 if (SimplePatterns
[Operands
][OpcodeName
][VT
][RetVT
]
385 .count(PredicateCheck
))
386 throw TGError(Pattern
.getSrcRecord()->getLoc(), "Duplicate record!");
388 SimplePatterns
[Operands
][OpcodeName
][VT
][RetVT
][PredicateCheck
] = Memo
;
392 void FastISelMap::PrintFunctionDefinitions(raw_ostream
&OS
) {
393 // Now emit code for all the patterns that we collected.
394 for (OperandsOpcodeTypeRetPredMap::const_iterator OI
= SimplePatterns
.begin(),
395 OE
= SimplePatterns
.end(); OI
!= OE
; ++OI
) {
396 const OperandsSignature
&Operands
= OI
->first
;
397 const OpcodeTypeRetPredMap
&OTM
= OI
->second
;
399 for (OpcodeTypeRetPredMap::const_iterator I
= OTM
.begin(), E
= OTM
.end();
401 const std::string
&Opcode
= I
->first
;
402 const TypeRetPredMap
&TM
= I
->second
;
404 OS
<< "// FastEmit functions for " << Opcode
<< ".\n";
407 // Emit one function for each opcode,type pair.
408 for (TypeRetPredMap::const_iterator TI
= TM
.begin(), TE
= TM
.end();
410 MVT::SimpleValueType VT
= TI
->first
;
411 const RetPredMap
&RM
= TI
->second
;
412 if (RM
.size() != 1) {
413 for (RetPredMap::const_iterator RI
= RM
.begin(), RE
= RM
.end();
415 MVT::SimpleValueType RetVT
= RI
->first
;
416 const PredMap
&PM
= RI
->second
;
417 bool HasPred
= false;
419 OS
<< "unsigned FastEmit_"
420 << getLegalCName(Opcode
)
421 << "_" << getLegalCName(getName(VT
))
422 << "_" << getLegalCName(getName(RetVT
)) << "_";
423 Operands
.PrintManglingSuffix(OS
);
425 Operands
.PrintParameters(OS
);
428 // Emit code for each possible instruction. There may be
429 // multiple if there are subtarget concerns.
430 for (PredMap::const_iterator PI
= PM
.begin(), PE
= PM
.end();
432 std::string PredicateCheck
= PI
->first
;
433 const InstructionMemo
&Memo
= PI
->second
;
435 if (PredicateCheck
.empty()) {
437 "Multiple instructions match, at least one has "
438 "a predicate and at least one doesn't!");
440 OS
<< " if (" + PredicateCheck
+ ") {\n";
445 for (unsigned i
= 0; i
< Memo
.PhysRegs
->size(); ++i
) {
446 if ((*Memo
.PhysRegs
)[i
] != "")
447 OS
<< " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, "
448 << "TII.get(TargetOpcode::COPY), "
449 << (*Memo
.PhysRegs
)[i
] << ").addReg(Op" << i
<< ");\n";
452 OS
<< " return FastEmitInst_";
453 if (Memo
.SubRegNo
.empty()) {
454 Operands
.PrintManglingSuffix(OS
, *Memo
.PhysRegs
);
455 OS
<< "(" << InstNS
<< Memo
.Name
<< ", ";
456 OS
<< InstNS
<< Memo
.RC
->getName() << "RegisterClass";
457 if (!Operands
.empty())
459 Operands
.PrintArguments(OS
, *Memo
.PhysRegs
);
462 OS
<< "extractsubreg(" << getName(RetVT
);
463 OS
<< ", Op0, Op0IsKill, ";
472 // Return 0 if none of the predicates were satisfied.
474 OS
<< " return 0;\n";
479 // Emit one function for the type that demultiplexes on return type.
480 OS
<< "unsigned FastEmit_"
481 << getLegalCName(Opcode
) << "_"
482 << getLegalCName(getName(VT
)) << "_";
483 Operands
.PrintManglingSuffix(OS
);
485 if (!Operands
.empty())
487 Operands
.PrintParameters(OS
);
488 OS
<< ") {\nswitch (RetVT.SimpleTy) {\n";
489 for (RetPredMap::const_iterator RI
= RM
.begin(), RE
= RM
.end();
491 MVT::SimpleValueType RetVT
= RI
->first
;
492 OS
<< " case " << getName(RetVT
) << ": return FastEmit_"
493 << getLegalCName(Opcode
) << "_" << getLegalCName(getName(VT
))
494 << "_" << getLegalCName(getName(RetVT
)) << "_";
495 Operands
.PrintManglingSuffix(OS
);
497 Operands
.PrintArguments(OS
);
500 OS
<< " default: return 0;\n}\n}\n\n";
503 // Non-variadic return type.
504 OS
<< "unsigned FastEmit_"
505 << getLegalCName(Opcode
) << "_"
506 << getLegalCName(getName(VT
)) << "_";
507 Operands
.PrintManglingSuffix(OS
);
509 if (!Operands
.empty())
511 Operands
.PrintParameters(OS
);
514 OS
<< " if (RetVT.SimpleTy != " << getName(RM
.begin()->first
)
515 << ")\n return 0;\n";
517 const PredMap
&PM
= RM
.begin()->second
;
518 bool HasPred
= false;
520 // Emit code for each possible instruction. There may be
521 // multiple if there are subtarget concerns.
522 for (PredMap::const_iterator PI
= PM
.begin(), PE
= PM
.end(); PI
!= PE
;
524 std::string PredicateCheck
= PI
->first
;
525 const InstructionMemo
&Memo
= PI
->second
;
527 if (PredicateCheck
.empty()) {
529 "Multiple instructions match, at least one has "
530 "a predicate and at least one doesn't!");
532 OS
<< " if (" + PredicateCheck
+ ") {\n";
537 for (unsigned i
= 0; i
< Memo
.PhysRegs
->size(); ++i
) {
538 if ((*Memo
.PhysRegs
)[i
] != "")
539 OS
<< " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, "
540 << "TII.get(TargetOpcode::COPY), "
541 << (*Memo
.PhysRegs
)[i
] << ").addReg(Op" << i
<< ");\n";
544 OS
<< " return FastEmitInst_";
546 if (Memo
.SubRegNo
.empty()) {
547 Operands
.PrintManglingSuffix(OS
, *Memo
.PhysRegs
);
548 OS
<< "(" << InstNS
<< Memo
.Name
<< ", ";
549 OS
<< InstNS
<< Memo
.RC
->getName() << "RegisterClass";
550 if (!Operands
.empty())
552 Operands
.PrintArguments(OS
, *Memo
.PhysRegs
);
555 OS
<< "extractsubreg(RetVT, Op0, Op0IsKill, ";
564 // Return 0 if none of the predicates were satisfied.
566 OS
<< " return 0;\n";
572 // Emit one function for the opcode that demultiplexes based on the type.
573 OS
<< "unsigned FastEmit_"
574 << getLegalCName(Opcode
) << "_";
575 Operands
.PrintManglingSuffix(OS
);
576 OS
<< "(MVT VT, MVT RetVT";
577 if (!Operands
.empty())
579 Operands
.PrintParameters(OS
);
581 OS
<< " switch (VT.SimpleTy) {\n";
582 for (TypeRetPredMap::const_iterator TI
= TM
.begin(), TE
= TM
.end();
584 MVT::SimpleValueType VT
= TI
->first
;
585 std::string TypeName
= getName(VT
);
586 OS
<< " case " << TypeName
<< ": return FastEmit_"
587 << getLegalCName(Opcode
) << "_" << getLegalCName(TypeName
) << "_";
588 Operands
.PrintManglingSuffix(OS
);
590 if (!Operands
.empty())
592 Operands
.PrintArguments(OS
);
595 OS
<< " default: return 0;\n";
601 OS
<< "// Top-level FastEmit function.\n";
604 // Emit one function for the operand signature that demultiplexes based
605 // on opcode and type.
606 OS
<< "unsigned FastEmit_";
607 Operands
.PrintManglingSuffix(OS
);
608 OS
<< "(MVT VT, MVT RetVT, unsigned Opcode";
609 if (!Operands
.empty())
611 Operands
.PrintParameters(OS
);
613 OS
<< " switch (Opcode) {\n";
614 for (OpcodeTypeRetPredMap::const_iterator I
= OTM
.begin(), E
= OTM
.end();
616 const std::string
&Opcode
= I
->first
;
618 OS
<< " case " << Opcode
<< ": return FastEmit_"
619 << getLegalCName(Opcode
) << "_";
620 Operands
.PrintManglingSuffix(OS
);
622 if (!Operands
.empty())
624 Operands
.PrintArguments(OS
);
627 OS
<< " default: return 0;\n";
634 void FastISelEmitter::run(raw_ostream
&OS
) {
635 const CodeGenTarget
&Target
= CGP
.getTargetInfo();
637 // Determine the target's namespace name.
638 std::string InstNS
= Target
.getInstNamespace() + "::";
639 assert(InstNS
.size() > 2 && "Can't determine target-specific namespace!");
641 EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
642 Target
.getName() + " target", OS
);
644 FastISelMap
F(InstNS
);
645 F
.CollectPatterns(CGP
);
646 F
.PrintFunctionDefinitions(OS
);
649 FastISelEmitter::FastISelEmitter(RecordKeeper
&R
)