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 or be
116
// a strict subclass of the destination.
118
if (DstRC != RC && !DstRC->hasSubClass(RC))
122
Operands.push_back("r");
127
void PrintParameters(raw_ostream &OS) const {
128
for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
129
if (Operands[i] == "r") {
130
OS << "unsigned Op" << i << ", bool Op" << i << "IsKill";
131
} else if (Operands[i] == "i") {
132
OS << "uint64_t imm" << i;
133
} else if (Operands[i] == "f") {
134
OS << "ConstantFP *f" << i;
136
assert("Unknown operand kind!");
144
void PrintArguments(raw_ostream &OS,
145
const std::vector<std::string>& PR) const {
146
assert(PR.size() == Operands.size());
147
bool PrintedArg = false;
148
for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
150
// Implicit physical register operand.
155
if (Operands[i] == "r") {
156
OS << "Op" << i << ", Op" << i << "IsKill";
158
} else if (Operands[i] == "i") {
161
} else if (Operands[i] == "f") {
165
assert("Unknown operand kind!");
171
void PrintArguments(raw_ostream &OS) const {
172
for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
173
if (Operands[i] == "r") {
174
OS << "Op" << i << ", Op" << i << "IsKill";
175
} else if (Operands[i] == "i") {
177
} else if (Operands[i] == "f") {
180
assert("Unknown operand kind!");
189
void PrintManglingSuffix(raw_ostream &OS,
190
const std::vector<std::string>& PR) const {
191
for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
193
// Implicit physical register operand. e.g. Instruction::Mul expect to
194
// select to a binary op. On x86, mul may take a single operand with
195
// the other operand being implicit. We must emit something that looks
196
// like a binary instruction except for the very inner FastEmitInst_*
203
void PrintManglingSuffix(raw_ostream &OS) const {
204
for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
211
typedef std::map<std::string, InstructionMemo> PredMap;
212
typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap;
213
typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap;
214
typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap;
215
typedef std::map<OperandsSignature, OpcodeTypeRetPredMap>
216
OperandsOpcodeTypeRetPredMap;
218
OperandsOpcodeTypeRetPredMap SimplePatterns;
223
explicit FastISelMap(std::string InstNS);
225
void CollectPatterns(CodeGenDAGPatterns &CGP);
226
void PrintFunctionDefinitions(raw_ostream &OS);
231
static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
232
return CGP.getSDNodeInfo(Op).getEnumName();
235
static std::string getLegalCName(std::string OpName) {
236
std::string::size_type pos = OpName.find("::");
237
if (pos != std::string::npos)
238
OpName.replace(pos, 2, "_");
242
FastISelMap::FastISelMap(std::string instns)
246
void FastISelMap::CollectPatterns(CodeGenDAGPatterns &CGP) {
247
const CodeGenTarget &Target = CGP.getTargetInfo();
249
// Determine the target's namespace name.
250
InstNS = Target.getInstNamespace() + "::";
251
assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
253
// Scan through all the patterns and record the simple ones.
254
for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
255
E = CGP.ptm_end(); I != E; ++I) {
256
const PatternToMatch &Pattern = *I;
258
// For now, just look at Instructions, so that we don't have to worry
259
// about emitting multiple instructions for a pattern.
260
TreePatternNode *Dst = Pattern.getDstPattern();
261
if (Dst->isLeaf()) continue;
262
Record *Op = Dst->getOperator();
263
if (!Op->isSubClassOf("Instruction"))
265
CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op);
266
if (II.OperandList.empty())
269
// For now, ignore multi-instruction patterns.
270
bool MultiInsts = false;
271
for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) {
272
TreePatternNode *ChildOp = Dst->getChild(i);
273
if (ChildOp->isLeaf())
275
if (ChildOp->getOperator()->isSubClassOf("Instruction")) {
283
// For now, ignore instructions where the first operand is not an
285
const CodeGenRegisterClass *DstRC = 0;
286
std::string SubRegNo;
287
if (Op->getName() != "EXTRACT_SUBREG") {
288
Record *Op0Rec = II.OperandList[0].Rec;
289
if (!Op0Rec->isSubClassOf("RegisterClass"))
291
DstRC = &Target.getRegisterClass(Op0Rec);
295
// If this isn't a leaf, then continue since the register classes are
296
// a bit too complicated for now.
297
if (!Dst->getChild(1)->isLeaf()) continue;
299
DefInit *SR = dynamic_cast<DefInit*>(Dst->getChild(1)->getLeafValue());
301
SubRegNo = getQualifiedName(SR->getDef());
303
SubRegNo = Dst->getChild(1)->getLeafValue()->getAsString();
306
// Inspect the pattern.
307
TreePatternNode *InstPatNode = Pattern.getSrcPattern();
308
if (!InstPatNode) continue;
309
if (InstPatNode->isLeaf()) continue;
311
// Ignore multiple result nodes for now.
312
if (InstPatNode->getNumTypes() > 1) continue;
314
Record *InstPatOp = InstPatNode->getOperator();
315
std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
316
MVT::SimpleValueType RetVT = MVT::isVoid;
317
if (InstPatNode->getNumTypes()) RetVT = InstPatNode->getType(0);
318
MVT::SimpleValueType VT = RetVT;
319
if (InstPatNode->getNumChildren()) {
320
assert(InstPatNode->getChild(0)->getNumTypes() == 1);
321
VT = InstPatNode->getChild(0)->getType(0);
324
// For now, filter out instructions which just set a register to
325
// an Operand or an immediate, like MOV32ri.
326
if (InstPatOp->isSubClassOf("Operand"))
329
// For now, filter out any instructions with predicates.
330
if (!InstPatNode->getPredicateFns().empty())
333
// Check all the operands.
334
OperandsSignature Operands;
335
if (!Operands.initialize(InstPatNode, Target, VT))
338
std::vector<std::string>* PhysRegInputs = new std::vector<std::string>();
339
if (!InstPatNode->isLeaf() &&
340
(InstPatNode->getOperator()->getName() == "imm" ||
341
InstPatNode->getOperator()->getName() == "fpimmm"))
342
PhysRegInputs->push_back("");
343
else if (!InstPatNode->isLeaf()) {
344
for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
345
TreePatternNode *Op = InstPatNode->getChild(i);
347
PhysRegInputs->push_back("");
351
DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
352
Record *OpLeafRec = OpDI->getDef();
354
if (OpLeafRec->isSubClassOf("Register")) {
355
PhysReg += static_cast<StringInit*>(OpLeafRec->getValue( \
356
"Namespace")->getValue())->getValue();
359
std::vector<CodeGenRegister> Regs = Target.getRegisters();
360
for (unsigned i = 0; i < Regs.size(); ++i) {
361
if (Regs[i].TheDef == OpLeafRec) {
362
PhysReg += Regs[i].getName();
368
PhysRegInputs->push_back(PhysReg);
371
PhysRegInputs->push_back("");
373
// Get the predicate that guards this pattern.
374
std::string PredicateCheck = Pattern.getPredicateCheck();
376
// Ok, we found a pattern that we can handle. Remember it.
377
InstructionMemo Memo = {
378
Pattern.getDstPattern()->getOperator()->getName(),
383
assert(!SimplePatterns[Operands][OpcodeName][VT][RetVT]
384
.count(PredicateCheck) &&
385
"Duplicate pattern!");
386
SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo;
390
void FastISelMap::PrintFunctionDefinitions(raw_ostream &OS) {
391
// Now emit code for all the patterns that we collected.
392
for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
393
OE = SimplePatterns.end(); OI != OE; ++OI) {
394
const OperandsSignature &Operands = OI->first;
395
const OpcodeTypeRetPredMap &OTM = OI->second;
397
for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
399
const std::string &Opcode = I->first;
400
const TypeRetPredMap &TM = I->second;
402
OS << "// FastEmit functions for " << Opcode << ".\n";
405
// Emit one function for each opcode,type pair.
406
for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
408
MVT::SimpleValueType VT = TI->first;
409
const RetPredMap &RM = TI->second;
410
if (RM.size() != 1) {
411
for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
413
MVT::SimpleValueType RetVT = RI->first;
414
const PredMap &PM = RI->second;
415
bool HasPred = false;
417
OS << "unsigned FastEmit_"
418
<< getLegalCName(Opcode)
419
<< "_" << getLegalCName(getName(VT))
420
<< "_" << getLegalCName(getName(RetVT)) << "_";
421
Operands.PrintManglingSuffix(OS);
423
Operands.PrintParameters(OS);
426
// Emit code for each possible instruction. There may be
427
// multiple if there are subtarget concerns.
428
for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
430
std::string PredicateCheck = PI->first;
431
const InstructionMemo &Memo = PI->second;
433
if (PredicateCheck.empty()) {
435
"Multiple instructions match, at least one has "
436
"a predicate and at least one doesn't!");
438
OS << " if (" + PredicateCheck + ") {\n";
443
for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
444
if ((*Memo.PhysRegs)[i] != "")
445
OS << " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, "
446
<< "TII.get(TargetOpcode::COPY), "
447
<< (*Memo.PhysRegs)[i] << ").addReg(Op" << i << ");\n";
450
OS << " return FastEmitInst_";
451
if (Memo.SubRegNo.empty()) {
452
Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
453
OS << "(" << InstNS << Memo.Name << ", ";
454
OS << InstNS << Memo.RC->getName() << "RegisterClass";
455
if (!Operands.empty())
457
Operands.PrintArguments(OS, *Memo.PhysRegs);
460
OS << "extractsubreg(" << getName(RetVT);
461
OS << ", Op0, Op0IsKill, ";
470
// Return 0 if none of the predicates were satisfied.
472
OS << " return 0;\n";
477
// Emit one function for the type that demultiplexes on return type.
478
OS << "unsigned FastEmit_"
479
<< getLegalCName(Opcode) << "_"
480
<< getLegalCName(getName(VT)) << "_";
481
Operands.PrintManglingSuffix(OS);
483
if (!Operands.empty())
485
Operands.PrintParameters(OS);
486
OS << ") {\nswitch (RetVT.SimpleTy) {\n";
487
for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
489
MVT::SimpleValueType RetVT = RI->first;
490
OS << " case " << getName(RetVT) << ": return FastEmit_"
491
<< getLegalCName(Opcode) << "_" << getLegalCName(getName(VT))
492
<< "_" << getLegalCName(getName(RetVT)) << "_";
493
Operands.PrintManglingSuffix(OS);
495
Operands.PrintArguments(OS);
498
OS << " default: return 0;\n}\n}\n\n";
501
// Non-variadic return type.
502
OS << "unsigned FastEmit_"
503
<< getLegalCName(Opcode) << "_"
504
<< getLegalCName(getName(VT)) << "_";
505
Operands.PrintManglingSuffix(OS);
507
if (!Operands.empty())
509
Operands.PrintParameters(OS);
512
OS << " if (RetVT.SimpleTy != " << getName(RM.begin()->first)
513
<< ")\n return 0;\n";
515
const PredMap &PM = RM.begin()->second;
516
bool HasPred = false;
518
// Emit code for each possible instruction. There may be
519
// multiple if there are subtarget concerns.
520
for (PredMap::const_iterator PI = PM.begin(), PE = PM.end(); PI != PE;
522
std::string PredicateCheck = PI->first;
523
const InstructionMemo &Memo = PI->second;
525
if (PredicateCheck.empty()) {
527
"Multiple instructions match, at least one has "
528
"a predicate and at least one doesn't!");
530
OS << " if (" + PredicateCheck + ") {\n";
535
for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
536
if ((*Memo.PhysRegs)[i] != "")
537
OS << " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, "
538
<< "TII.get(TargetOpcode::COPY), "
539
<< (*Memo.PhysRegs)[i] << ").addReg(Op" << i << ");\n";
542
OS << " return FastEmitInst_";
544
if (Memo.SubRegNo.empty()) {
545
Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
546
OS << "(" << InstNS << Memo.Name << ", ";
547
OS << InstNS << Memo.RC->getName() << "RegisterClass";
548
if (!Operands.empty())
550
Operands.PrintArguments(OS, *Memo.PhysRegs);
553
OS << "extractsubreg(RetVT, Op0, Op0IsKill, ";
562
// Return 0 if none of the predicates were satisfied.
564
OS << " return 0;\n";
570
// Emit one function for the opcode that demultiplexes based on the type.
571
OS << "unsigned FastEmit_"
572
<< getLegalCName(Opcode) << "_";
573
Operands.PrintManglingSuffix(OS);
574
OS << "(MVT VT, MVT RetVT";
575
if (!Operands.empty())
577
Operands.PrintParameters(OS);
579
OS << " switch (VT.SimpleTy) {\n";
580
for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
582
MVT::SimpleValueType VT = TI->first;
583
std::string TypeName = getName(VT);
584
OS << " case " << TypeName << ": return FastEmit_"
585
<< getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
586
Operands.PrintManglingSuffix(OS);
588
if (!Operands.empty())
590
Operands.PrintArguments(OS);
593
OS << " default: return 0;\n";
599
OS << "// Top-level FastEmit function.\n";
602
// Emit one function for the operand signature that demultiplexes based
603
// on opcode and type.
604
OS << "unsigned FastEmit_";
605
Operands.PrintManglingSuffix(OS);
606
OS << "(MVT VT, MVT RetVT, unsigned Opcode";
607
if (!Operands.empty())
609
Operands.PrintParameters(OS);
611
OS << " switch (Opcode) {\n";
612
for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
614
const std::string &Opcode = I->first;
616
OS << " case " << Opcode << ": return FastEmit_"
617
<< getLegalCName(Opcode) << "_";
618
Operands.PrintManglingSuffix(OS);
620
if (!Operands.empty())
622
Operands.PrintArguments(OS);
625
OS << " default: return 0;\n";
632
void FastISelEmitter::run(raw_ostream &OS) {
633
const CodeGenTarget &Target = CGP.getTargetInfo();
635
// Determine the target's namespace name.
636
std::string InstNS = Target.getInstNamespace() + "::";
637
assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
639
EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
640
Target.getName() + " target", OS);
642
FastISelMap F(InstNS);
643
F.CollectPatterns(CGP);
644
F.PrintFunctionDefinitions(OS);
647
FastISelEmitter::FastISelEmitter(RecordKeeper &R)