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 {
44 enum { OK_Reg, OK_FP, OK_Imm, OK_Invalid = -1 };
48 OpKind() : Repr(OK_Invalid) {}
50 bool operator<(OpKind RHS) const { return Repr < RHS.Repr; }
52 static OpKind getReg() { OpKind K; K.Repr = OK_Reg; return K; }
53 static OpKind getFP() { OpKind K; K.Repr = OK_FP; return K; }
54 static OpKind getImm() { OpKind K; K.Repr = OK_Imm; return K; }
56 bool isReg() const { return Repr == OK_Reg; }
57 bool isFP() const { return Repr == OK_FP; }
58 bool isImm() const { return Repr == OK_Imm; }
60 void printManglingSuffix(raw_ostream &OS) const {
70 SmallVector<OpKind, 3> Operands;
72 bool operator<(const OperandsSignature &O) const {
73 return Operands < O.Operands;
76 bool empty() const { return Operands.empty(); }
78 /// initialize - Examine the given pattern and initialize the contents
79 /// of the Operands array accordingly. Return true if all the operands
80 /// are supported, false otherwise.
82 bool initialize(TreePatternNode *InstPatNode, const CodeGenTarget &Target,
83 MVT::SimpleValueType VT) {
85 if (!InstPatNode->isLeaf()) {
86 if (InstPatNode->getOperator()->getName() == "imm") {
87 Operands.push_back(OpKind::getImm());
90 if (InstPatNode->getOperator()->getName() == "fpimm") {
91 Operands.push_back(OpKind::getFP());
96 const CodeGenRegisterClass *DstRC = 0;
98 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
99 TreePatternNode *Op = InstPatNode->getChild(i);
101 // For now, filter out any operand with a predicate.
102 // For now, filter out any operand with multiple values.
103 if (!Op->getPredicateFns().empty() || Op->getNumTypes() != 1)
107 if (Op->getOperator()->getName() == "imm") {
108 Operands.push_back(OpKind::getImm());
111 if (Op->getOperator()->getName() == "fpimm") {
112 Operands.push_back(OpKind::getFP());
115 // For now, ignore other non-leaf nodes.
119 assert(Op->hasTypeSet(0) && "Type infererence not done?");
121 // For now, all the operands must have the same type (if they aren't
122 // immediates). Note that this causes us to reject variable sized shifts
124 if (Op->getType(0) != VT)
127 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
130 Record *OpLeafRec = OpDI->getDef();
132 // For now, the only other thing we accept is register operands.
133 const CodeGenRegisterClass *RC = 0;
134 if (OpLeafRec->isSubClassOf("RegisterClass"))
135 RC = &Target.getRegisterClass(OpLeafRec);
136 else if (OpLeafRec->isSubClassOf("Register"))
137 RC = Target.getRegisterClassForRegister(OpLeafRec);
141 // For now, this needs to be a register class of some sort.
145 // For now, all the operands must have the same register class or be
146 // a strict subclass of the destination.
148 if (DstRC != RC && !DstRC->hasSubClass(RC))
152 Operands.push_back(OpKind::getReg());
157 void PrintParameters(raw_ostream &OS) const {
158 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
159 if (Operands[i].isReg()) {
160 OS << "unsigned Op" << i << ", bool Op" << i << "IsKill";
161 } else if (Operands[i].isImm()) {
162 OS << "uint64_t imm" << i;
163 } else if (Operands[i].isFP()) {
164 OS << "ConstantFP *f" << i;
166 assert("Unknown operand kind!");
174 void PrintArguments(raw_ostream &OS,
175 const std::vector<std::string> &PR) const {
176 assert(PR.size() == Operands.size());
177 bool PrintedArg = false;
178 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
180 // Implicit physical register operand.
185 if (Operands[i].isReg()) {
186 OS << "Op" << i << ", Op" << i << "IsKill";
188 } else if (Operands[i].isImm()) {
191 } else if (Operands[i].isFP()) {
195 assert("Unknown operand kind!");
201 void PrintArguments(raw_ostream &OS) const {
202 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
203 if (Operands[i].isReg()) {
204 OS << "Op" << i << ", Op" << i << "IsKill";
205 } else if (Operands[i].isImm()) {
207 } else if (Operands[i].isFP()) {
210 assert("Unknown operand kind!");
219 void PrintManglingSuffix(raw_ostream &OS,
220 const std::vector<std::string> &PR) const {
221 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
223 // Implicit physical register operand. e.g. Instruction::Mul expect to
224 // select to a binary op. On x86, mul may take a single operand with
225 // the other operand being implicit. We must emit something that looks
226 // like a binary instruction except for the very inner FastEmitInst_*
229 Operands[i].printManglingSuffix(OS);
233 void PrintManglingSuffix(raw_ostream &OS) const {
234 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
235 Operands[i].printManglingSuffix(OS);
240 typedef std::map<std::string, InstructionMemo> PredMap;
241 typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap;
242 typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap;
243 typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap;
244 typedef std::map<OperandsSignature, OpcodeTypeRetPredMap>
245 OperandsOpcodeTypeRetPredMap;
247 OperandsOpcodeTypeRetPredMap SimplePatterns;
252 explicit FastISelMap(std::string InstNS);
254 void CollectPatterns(CodeGenDAGPatterns &CGP);
255 void PrintFunctionDefinitions(raw_ostream &OS);
260 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
261 return CGP.getSDNodeInfo(Op).getEnumName();
264 static std::string getLegalCName(std::string OpName) {
265 std::string::size_type pos = OpName.find("::");
266 if (pos != std::string::npos)
267 OpName.replace(pos, 2, "_");
271 FastISelMap::FastISelMap(std::string instns)
275 void FastISelMap::CollectPatterns(CodeGenDAGPatterns &CGP) {
276 const CodeGenTarget &Target = CGP.getTargetInfo();
278 // Determine the target's namespace name.
279 InstNS = Target.getInstNamespace() + "::";
280 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
282 // Scan through all the patterns and record the simple ones.
283 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
284 E = CGP.ptm_end(); I != E; ++I) {
285 const PatternToMatch &Pattern = *I;
287 // For now, just look at Instructions, so that we don't have to worry
288 // about emitting multiple instructions for a pattern.
289 TreePatternNode *Dst = Pattern.getDstPattern();
290 if (Dst->isLeaf()) continue;
291 Record *Op = Dst->getOperator();
292 if (!Op->isSubClassOf("Instruction"))
294 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op);
295 if (II.Operands.empty())
298 // For now, ignore multi-instruction patterns.
299 bool MultiInsts = false;
300 for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) {
301 TreePatternNode *ChildOp = Dst->getChild(i);
302 if (ChildOp->isLeaf())
304 if (ChildOp->getOperator()->isSubClassOf("Instruction")) {
312 // For now, ignore instructions where the first operand is not an
314 const CodeGenRegisterClass *DstRC = 0;
315 std::string SubRegNo;
316 if (Op->getName() != "EXTRACT_SUBREG") {
317 Record *Op0Rec = II.Operands[0].Rec;
318 if (!Op0Rec->isSubClassOf("RegisterClass"))
320 DstRC = &Target.getRegisterClass(Op0Rec);
324 // If this isn't a leaf, then continue since the register classes are
325 // a bit too complicated for now.
326 if (!Dst->getChild(1)->isLeaf()) continue;
328 DefInit *SR = dynamic_cast<DefInit*>(Dst->getChild(1)->getLeafValue());
330 SubRegNo = getQualifiedName(SR->getDef());
332 SubRegNo = Dst->getChild(1)->getLeafValue()->getAsString();
335 // Inspect the pattern.
336 TreePatternNode *InstPatNode = Pattern.getSrcPattern();
337 if (!InstPatNode) continue;
338 if (InstPatNode->isLeaf()) continue;
340 // Ignore multiple result nodes for now.
341 if (InstPatNode->getNumTypes() > 1) continue;
343 Record *InstPatOp = InstPatNode->getOperator();
344 std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
345 MVT::SimpleValueType RetVT = MVT::isVoid;
346 if (InstPatNode->getNumTypes()) RetVT = InstPatNode->getType(0);
347 MVT::SimpleValueType VT = RetVT;
348 if (InstPatNode->getNumChildren()) {
349 assert(InstPatNode->getChild(0)->getNumTypes() == 1);
350 VT = InstPatNode->getChild(0)->getType(0);
353 // For now, filter out instructions which just set a register to
354 // an Operand or an immediate, like MOV32ri.
355 if (InstPatOp->isSubClassOf("Operand"))
358 // For now, filter out any instructions with predicates.
359 if (!InstPatNode->getPredicateFns().empty())
362 // Check all the operands.
363 OperandsSignature Operands;
364 if (!Operands.initialize(InstPatNode, Target, VT))
367 std::vector<std::string>* PhysRegInputs = new std::vector<std::string>();
368 if (!InstPatNode->isLeaf() &&
369 (InstPatNode->getOperator()->getName() == "imm" ||
370 InstPatNode->getOperator()->getName() == "fpimmm"))
371 PhysRegInputs->push_back("");
372 else if (!InstPatNode->isLeaf()) {
373 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
374 TreePatternNode *Op = InstPatNode->getChild(i);
376 PhysRegInputs->push_back("");
380 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
381 Record *OpLeafRec = OpDI->getDef();
383 if (OpLeafRec->isSubClassOf("Register")) {
384 PhysReg += static_cast<StringInit*>(OpLeafRec->getValue( \
385 "Namespace")->getValue())->getValue();
388 std::vector<CodeGenRegister> Regs = Target.getRegisters();
389 for (unsigned i = 0; i < Regs.size(); ++i) {
390 if (Regs[i].TheDef == OpLeafRec) {
391 PhysReg += Regs[i].getName();
397 PhysRegInputs->push_back(PhysReg);
400 PhysRegInputs->push_back("");
402 // Get the predicate that guards this pattern.
403 std::string PredicateCheck = Pattern.getPredicateCheck();
405 // Ok, we found a pattern that we can handle. Remember it.
406 InstructionMemo Memo = {
407 Pattern.getDstPattern()->getOperator()->getName(),
412 if (SimplePatterns[Operands][OpcodeName][VT][RetVT]
413 .count(PredicateCheck))
414 throw TGError(Pattern.getSrcRecord()->getLoc(), "Duplicate record!");
416 SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo;
420 void FastISelMap::PrintFunctionDefinitions(raw_ostream &OS) {
421 // Now emit code for all the patterns that we collected.
422 for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
423 OE = SimplePatterns.end(); OI != OE; ++OI) {
424 const OperandsSignature &Operands = OI->first;
425 const OpcodeTypeRetPredMap &OTM = OI->second;
427 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
429 const std::string &Opcode = I->first;
430 const TypeRetPredMap &TM = I->second;
432 OS << "// FastEmit functions for " << Opcode << ".\n";
435 // Emit one function for each opcode,type pair.
436 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
438 MVT::SimpleValueType VT = TI->first;
439 const RetPredMap &RM = TI->second;
440 if (RM.size() != 1) {
441 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
443 MVT::SimpleValueType RetVT = RI->first;
444 const PredMap &PM = RI->second;
445 bool HasPred = false;
447 OS << "unsigned FastEmit_"
448 << getLegalCName(Opcode)
449 << "_" << getLegalCName(getName(VT))
450 << "_" << getLegalCName(getName(RetVT)) << "_";
451 Operands.PrintManglingSuffix(OS);
453 Operands.PrintParameters(OS);
456 // Emit code for each possible instruction. There may be
457 // multiple if there are subtarget concerns.
458 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
460 std::string PredicateCheck = PI->first;
461 const InstructionMemo &Memo = PI->second;
463 if (PredicateCheck.empty()) {
465 "Multiple instructions match, at least one has "
466 "a predicate and at least one doesn't!");
468 OS << " if (" + PredicateCheck + ") {\n";
473 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
474 if ((*Memo.PhysRegs)[i] != "")
475 OS << " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, "
476 << "TII.get(TargetOpcode::COPY), "
477 << (*Memo.PhysRegs)[i] << ").addReg(Op" << i << ");\n";
480 OS << " return FastEmitInst_";
481 if (Memo.SubRegNo.empty()) {
482 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
483 OS << "(" << InstNS << Memo.Name << ", ";
484 OS << InstNS << Memo.RC->getName() << "RegisterClass";
485 if (!Operands.empty())
487 Operands.PrintArguments(OS, *Memo.PhysRegs);
490 OS << "extractsubreg(" << getName(RetVT);
491 OS << ", Op0, Op0IsKill, ";
500 // Return 0 if none of the predicates were satisfied.
502 OS << " return 0;\n";
507 // Emit one function for the type that demultiplexes on return type.
508 OS << "unsigned FastEmit_"
509 << getLegalCName(Opcode) << "_"
510 << getLegalCName(getName(VT)) << "_";
511 Operands.PrintManglingSuffix(OS);
513 if (!Operands.empty())
515 Operands.PrintParameters(OS);
516 OS << ") {\nswitch (RetVT.SimpleTy) {\n";
517 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
519 MVT::SimpleValueType RetVT = RI->first;
520 OS << " case " << getName(RetVT) << ": return FastEmit_"
521 << getLegalCName(Opcode) << "_" << getLegalCName(getName(VT))
522 << "_" << getLegalCName(getName(RetVT)) << "_";
523 Operands.PrintManglingSuffix(OS);
525 Operands.PrintArguments(OS);
528 OS << " default: return 0;\n}\n}\n\n";
531 // Non-variadic return type.
532 OS << "unsigned FastEmit_"
533 << getLegalCName(Opcode) << "_"
534 << getLegalCName(getName(VT)) << "_";
535 Operands.PrintManglingSuffix(OS);
537 if (!Operands.empty())
539 Operands.PrintParameters(OS);
542 OS << " if (RetVT.SimpleTy != " << getName(RM.begin()->first)
543 << ")\n return 0;\n";
545 const PredMap &PM = RM.begin()->second;
546 bool HasPred = false;
548 // Emit code for each possible instruction. There may be
549 // multiple if there are subtarget concerns.
550 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end(); PI != PE;
552 std::string PredicateCheck = PI->first;
553 const InstructionMemo &Memo = PI->second;
555 if (PredicateCheck.empty()) {
557 "Multiple instructions match, at least one has "
558 "a predicate and at least one doesn't!");
560 OS << " if (" + PredicateCheck + ") {\n";
565 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
566 if ((*Memo.PhysRegs)[i] != "")
567 OS << " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, "
568 << "TII.get(TargetOpcode::COPY), "
569 << (*Memo.PhysRegs)[i] << ").addReg(Op" << i << ");\n";
572 OS << " return FastEmitInst_";
574 if (Memo.SubRegNo.empty()) {
575 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
576 OS << "(" << InstNS << Memo.Name << ", ";
577 OS << InstNS << Memo.RC->getName() << "RegisterClass";
578 if (!Operands.empty())
580 Operands.PrintArguments(OS, *Memo.PhysRegs);
583 OS << "extractsubreg(RetVT, Op0, Op0IsKill, ";
592 // Return 0 if none of the predicates were satisfied.
594 OS << " return 0;\n";
600 // Emit one function for the opcode that demultiplexes based on the type.
601 OS << "unsigned FastEmit_"
602 << getLegalCName(Opcode) << "_";
603 Operands.PrintManglingSuffix(OS);
604 OS << "(MVT VT, MVT RetVT";
605 if (!Operands.empty())
607 Operands.PrintParameters(OS);
609 OS << " switch (VT.SimpleTy) {\n";
610 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
612 MVT::SimpleValueType VT = TI->first;
613 std::string TypeName = getName(VT);
614 OS << " case " << TypeName << ": return FastEmit_"
615 << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
616 Operands.PrintManglingSuffix(OS);
618 if (!Operands.empty())
620 Operands.PrintArguments(OS);
623 OS << " default: return 0;\n";
629 OS << "// Top-level FastEmit function.\n";
632 // Emit one function for the operand signature that demultiplexes based
633 // on opcode and type.
634 OS << "unsigned FastEmit_";
635 Operands.PrintManglingSuffix(OS);
636 OS << "(MVT VT, MVT RetVT, unsigned Opcode";
637 if (!Operands.empty())
639 Operands.PrintParameters(OS);
641 OS << " switch (Opcode) {\n";
642 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
644 const std::string &Opcode = I->first;
646 OS << " case " << Opcode << ": return FastEmit_"
647 << getLegalCName(Opcode) << "_";
648 Operands.PrintManglingSuffix(OS);
650 if (!Operands.empty())
652 Operands.PrintArguments(OS);
655 OS << " default: return 0;\n";
662 void FastISelEmitter::run(raw_ostream &OS) {
663 const CodeGenTarget &Target = CGP.getTargetInfo();
665 // Determine the target's namespace name.
666 std::string InstNS = Target.getInstNamespace() + "::";
667 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
669 EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
670 Target.getName() + " target", OS);
672 FastISelMap F(InstNS);
673 F.CollectPatterns(CGP);
674 F.PrintFunctionDefinitions(OS);
677 FastISelEmitter::FastISelEmitter(RecordKeeper &R)