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 a "fast" instruction selector.
12 // This instruction selection method is designed to emit very poor code
13 // quickly. Also, it is not designed to do much lowering, so most illegal
14 // types (e.g. i64 on 32-bit targets) and operations (e.g. calls) are not
15 // supported and cannot easily be added. Blocks containing operations
16 // that are not supported need to be handled by a more capable selector,
17 // such as the SelectionDAG selector.
19 // The intended use for "fast" instruction selection is "-O0" mode
20 // compilation, where the quality of the generated code is irrelevant when
21 // weighed against the speed at which the code can be generated.
23 // If compile time is so important, you might wonder why we don't just
24 // skip codegen all-together, emit LLVM bytecode files, and execute them
25 // with an interpreter. The answer is that it would complicate linking and
26 // debugging, and also because that isn't how a compiler is expected to
27 // work in some circles.
29 // If you need better generated code or more lowering than what this
30 // instruction selector provides, use the SelectionDAG (DAGISel) instruction
31 // selector instead. If you're looking here because SelectionDAG isn't fast
32 // enough, consider looking into improving the SelectionDAG infastructure
33 // instead. At the time of this writing there remain several major
34 // opportunities for improvement.
36 //===----------------------------------------------------------------------===//
38 #include "FastISelEmitter.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/Streams.h"
42 #include "llvm/ADT/VectorExtras.h"
47 /// OperandsSignature - This class holds a description of a list of operand
48 /// types. It has utility methods for emitting text based on the operands.
50 struct OperandsSignature {
51 std::vector<std::string> Operands;
53 bool operator<(const OperandsSignature &O) const {
54 return Operands < O.Operands;
57 bool empty() const { return Operands.empty(); }
59 /// initialize - Examine the given pattern and initialize the contents
60 /// of the Operands array accordingly. Return true if all the operands
61 /// are supported, false otherwise.
63 bool initialize(TreePatternNode *InstPatNode,
64 const CodeGenTarget &Target,
65 MVT::SimpleValueType VT) {
66 if (!InstPatNode->isLeaf() &&
67 InstPatNode->getOperator()->getName() == "imm") {
68 Operands.push_back("i");
72 const CodeGenRegisterClass *DstRC = 0;
74 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
75 TreePatternNode *Op = InstPatNode->getChild(i);
76 // For now, filter out any operand with a predicate.
77 if (!Op->getPredicateFn().empty())
79 // For now, filter out any operand with multiple values.
80 if (Op->getExtTypes().size() != 1)
82 // For now, all the operands must have the same type.
83 if (Op->getTypeNum(0) != VT)
86 if (Op->getOperator()->getName() == "imm") {
87 Operands.push_back("i");
90 // For now, ignore fpimm and other non-leaf nodes.
93 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
96 Record *OpLeafRec = OpDI->getDef();
97 // TODO: handle instructions which have physreg operands.
98 if (OpLeafRec->isSubClassOf("Register"))
100 // For now, the only other thing we accept is register operands.
101 if (!OpLeafRec->isSubClassOf("RegisterClass"))
103 // For now, require the register operands' register classes to all
105 const CodeGenRegisterClass *RC = &Target.getRegisterClass(OpLeafRec);
108 // For now, all the operands must have the same register class.
114 Operands.push_back("r");
119 void PrintParameters(std::ostream &OS) const {
120 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
121 if (Operands[i] == "r") {
122 OS << "unsigned Op" << i;
123 } else if (Operands[i] == "i") {
124 OS << "uint64_t imm" << i;
126 assert("Unknown operand kind!");
134 void PrintArguments(std::ostream &OS) const {
135 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
136 if (Operands[i] == "r") {
138 } else if (Operands[i] == "i") {
141 assert("Unknown operand kind!");
149 void PrintManglingSuffix(std::ostream &OS) const {
150 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
156 /// InstructionMemo - This class holds additional information about an
157 /// instruction needed to emit code for it.
159 struct InstructionMemo {
161 const CodeGenRegisterClass *RC;
165 typedef std::map<std::string, InstructionMemo> PredMap;
166 typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap;
167 typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap;
168 typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap;
169 typedef std::map<OperandsSignature, OpcodeTypeRetPredMap> OperandsOpcodeTypeRetPredMap;
171 OperandsOpcodeTypeRetPredMap SimplePatterns;
176 explicit FastISelMap(std::string InstNS);
178 void CollectPatterns(CodeGenDAGPatterns &CGP);
179 void PrintClass(std::ostream &OS);
180 void PrintFunctionDefinitions(std::ostream &OS);
185 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
186 return CGP.getSDNodeInfo(Op).getEnumName();
189 static std::string getLegalCName(std::string OpName) {
190 std::string::size_type pos = OpName.find("::");
191 if (pos != std::string::npos)
192 OpName.replace(pos, 2, "_");
196 FastISelMap::FastISelMap(std::string instns)
200 void FastISelMap::CollectPatterns(CodeGenDAGPatterns &CGP) {
201 const CodeGenTarget &Target = CGP.getTargetInfo();
203 // Determine the target's namespace name.
204 InstNS = Target.getInstNamespace() + "::";
205 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
207 // Scan through all the patterns and record the simple ones.
208 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
209 E = CGP.ptm_end(); I != E; ++I) {
210 const PatternToMatch &Pattern = *I;
212 // For now, just look at Instructions, so that we don't have to worry
213 // about emitting multiple instructions for a pattern.
214 TreePatternNode *Dst = Pattern.getDstPattern();
215 if (Dst->isLeaf()) continue;
216 Record *Op = Dst->getOperator();
217 if (!Op->isSubClassOf("Instruction"))
219 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
220 if (II.OperandList.empty())
223 // For now, ignore instructions where the first operand is not an
225 Record *Op0Rec = II.OperandList[0].Rec;
226 if (!Op0Rec->isSubClassOf("RegisterClass"))
228 const CodeGenRegisterClass *DstRC = &Target.getRegisterClass(Op0Rec);
232 // Inspect the pattern.
233 TreePatternNode *InstPatNode = Pattern.getSrcPattern();
234 if (!InstPatNode) continue;
235 if (InstPatNode->isLeaf()) continue;
237 Record *InstPatOp = InstPatNode->getOperator();
238 std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
239 MVT::SimpleValueType RetVT = InstPatNode->getTypeNum(0);
240 MVT::SimpleValueType VT = RetVT;
241 if (InstPatNode->getNumChildren())
242 VT = InstPatNode->getChild(0)->getTypeNum(0);
244 // For now, filter out instructions which just set a register to
245 // an Operand or an immediate, like MOV32ri.
246 if (InstPatOp->isSubClassOf("Operand"))
249 // For now, filter out any instructions with predicates.
250 if (!InstPatNode->getPredicateFn().empty())
253 // Check all the operands.
254 OperandsSignature Operands;
255 if (!Operands.initialize(InstPatNode, Target, VT))
258 // Get the predicate that guards this pattern.
259 std::string PredicateCheck = Pattern.getPredicateCheck();
261 // Ok, we found a pattern that we can handle. Remember it.
262 InstructionMemo Memo = {
263 Pattern.getDstPattern()->getOperator()->getName(),
266 assert(!SimplePatterns[Operands][OpcodeName][VT][RetVT].count(PredicateCheck) &&
267 "Duplicate pattern!");
268 SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo;
272 void FastISelMap::PrintClass(std::ostream &OS) {
273 // Declare the target FastISel class.
274 OS << "class FastISel : public llvm::FastISel {\n";
275 for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
276 OE = SimplePatterns.end(); OI != OE; ++OI) {
277 const OperandsSignature &Operands = OI->first;
278 const OpcodeTypeRetPredMap &OTM = OI->second;
280 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
282 const std::string &Opcode = I->first;
283 const TypeRetPredMap &TM = I->second;
285 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
287 MVT::SimpleValueType VT = TI->first;
288 const RetPredMap &RM = TI->second;
291 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
293 MVT::SimpleValueType RetVT = RI->first;
294 OS << " unsigned FastEmit_" << getLegalCName(Opcode)
295 << "_" << getLegalCName(getName(VT)) << "_"
296 << getLegalCName(getName(RetVT)) << "_";
297 Operands.PrintManglingSuffix(OS);
299 Operands.PrintParameters(OS);
303 OS << " unsigned FastEmit_" << getLegalCName(Opcode)
304 << "_" << getLegalCName(getName(VT)) << "_";
305 Operands.PrintManglingSuffix(OS);
306 OS << "(MVT::SimpleValueType RetVT";
307 if (!Operands.empty())
309 Operands.PrintParameters(OS);
313 OS << " unsigned FastEmit_" << getLegalCName(Opcode) << "_";
314 Operands.PrintManglingSuffix(OS);
315 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT";
316 if (!Operands.empty())
318 Operands.PrintParameters(OS);
322 OS << " unsigned FastEmit_";
323 Operands.PrintManglingSuffix(OS);
324 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT, ISD::NodeType Opcode";
325 if (!Operands.empty())
327 Operands.PrintParameters(OS);
332 // Declare the Subtarget member, which is used for predicate checks.
333 OS << " const " << InstNS.substr(0, InstNS.size() - 2)
334 << "Subtarget *Subtarget;\n";
337 // Declare the constructor.
339 OS << " explicit FastISel(MachineFunction &mf)\n";
340 OS << " : llvm::FastISel(mf),\n";
341 OS << " Subtarget(&TM.getSubtarget<" << InstNS.substr(0, InstNS.size() - 2)
342 << "Subtarget>()) {}\n";
347 void FastISelMap::PrintFunctionDefinitions(std::ostream &OS) {
348 // Now emit code for all the patterns that we collected.
349 for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
350 OE = SimplePatterns.end(); OI != OE; ++OI) {
351 const OperandsSignature &Operands = OI->first;
352 const OpcodeTypeRetPredMap &OTM = OI->second;
354 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
356 const std::string &Opcode = I->first;
357 const TypeRetPredMap &TM = I->second;
359 OS << "// FastEmit functions for " << Opcode << ".\n";
362 // Emit one function for each opcode,type pair.
363 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
365 MVT::SimpleValueType VT = TI->first;
366 const RetPredMap &RM = TI->second;
367 if (RM.size() != 1) {
368 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
370 MVT::SimpleValueType RetVT = RI->first;
371 const PredMap &PM = RI->second;
372 bool HasPred = false;
374 OS << "unsigned FastISel::FastEmit_"
375 << getLegalCName(Opcode)
376 << "_" << getLegalCName(getName(VT))
377 << "_" << getLegalCName(getName(RetVT)) << "_";
378 Operands.PrintManglingSuffix(OS);
380 Operands.PrintParameters(OS);
383 // Emit code for each possible instruction. There may be
384 // multiple if there are subtarget concerns.
385 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
387 std::string PredicateCheck = PI->first;
388 const InstructionMemo &Memo = PI->second;
390 if (PredicateCheck.empty()) {
392 "Multiple instructions match, at least one has "
393 "a predicate and at least one doesn't!");
395 OS << " if (" + PredicateCheck + ")\n";
399 OS << " return FastEmitInst_";
400 Operands.PrintManglingSuffix(OS);
401 OS << "(" << InstNS << Memo.Name << ", ";
402 OS << InstNS << Memo.RC->getName() << "RegisterClass";
403 if (!Operands.empty())
405 Operands.PrintArguments(OS);
408 // Return 0 if none of the predicates were satisfied.
410 OS << " return 0;\n";
415 // Emit one function for the type that demultiplexes on return type.
416 OS << "unsigned FastISel::FastEmit_"
417 << getLegalCName(Opcode) << "_"
418 << getLegalCName(getName(VT)) << "_";
419 Operands.PrintManglingSuffix(OS);
420 OS << "(MVT::SimpleValueType RetVT";
421 if (!Operands.empty())
423 Operands.PrintParameters(OS);
424 OS << ") {\nswitch (RetVT) {\n";
425 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
427 MVT::SimpleValueType RetVT = RI->first;
428 OS << " case " << getName(RetVT) << ": return FastEmit_"
429 << getLegalCName(Opcode) << "_" << getLegalCName(getName(VT))
430 << "_" << getLegalCName(getName(RetVT)) << "_";
431 Operands.PrintManglingSuffix(OS);
433 Operands.PrintArguments(OS);
436 OS << " default: return 0;\n}\n}\n\n";
439 // Non-variadic return type.
440 OS << "unsigned FastISel::FastEmit_"
441 << getLegalCName(Opcode) << "_"
442 << getLegalCName(getName(VT)) << "_";
443 Operands.PrintManglingSuffix(OS);
444 OS << "(MVT::SimpleValueType RetVT";
445 if (!Operands.empty())
447 Operands.PrintParameters(OS);
450 OS << " if (RetVT != " << getName(RM.begin()->first)
451 << ")\n return 0;\n";
453 const PredMap &PM = RM.begin()->second;
454 bool HasPred = false;
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(); PI != PE; ++PI) {
459 std::string PredicateCheck = PI->first;
460 const InstructionMemo &Memo = PI->second;
462 if (PredicateCheck.empty()) {
464 "Multiple instructions match, at least one has "
465 "a predicate and at least one doesn't!");
467 OS << " if (" + PredicateCheck + ")\n";
471 OS << " return FastEmitInst_";
472 Operands.PrintManglingSuffix(OS);
473 OS << "(" << InstNS << Memo.Name << ", ";
474 OS << InstNS << Memo.RC->getName() << "RegisterClass";
475 if (!Operands.empty())
477 Operands.PrintArguments(OS);
481 // Return 0 if none of the predicates were satisfied.
483 OS << " return 0;\n";
489 // Emit one function for the opcode that demultiplexes based on the type.
490 OS << "unsigned FastISel::FastEmit_"
491 << getLegalCName(Opcode) << "_";
492 Operands.PrintManglingSuffix(OS);
493 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT";
494 if (!Operands.empty())
496 Operands.PrintParameters(OS);
498 OS << " switch (VT) {\n";
499 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
501 MVT::SimpleValueType VT = TI->first;
502 std::string TypeName = getName(VT);
503 OS << " case " << TypeName << ": return FastEmit_"
504 << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
505 Operands.PrintManglingSuffix(OS);
507 if (!Operands.empty())
509 Operands.PrintArguments(OS);
512 OS << " default: return 0;\n";
518 OS << "// Top-level FastEmit function.\n";
521 // Emit one function for the operand signature that demultiplexes based
522 // on opcode and type.
523 OS << "unsigned FastISel::FastEmit_";
524 Operands.PrintManglingSuffix(OS);
525 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT, ISD::NodeType Opcode";
526 if (!Operands.empty())
528 Operands.PrintParameters(OS);
530 OS << " switch (Opcode) {\n";
531 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
533 const std::string &Opcode = I->first;
535 OS << " case " << Opcode << ": return FastEmit_"
536 << getLegalCName(Opcode) << "_";
537 Operands.PrintManglingSuffix(OS);
539 if (!Operands.empty())
541 Operands.PrintArguments(OS);
544 OS << " default: return 0;\n";
551 void FastISelEmitter::run(std::ostream &OS) {
552 const CodeGenTarget &Target = CGP.getTargetInfo();
554 // Determine the target's namespace name.
555 std::string InstNS = Target.getInstNamespace() + "::";
556 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
558 EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
559 Target.getName() + " target", OS);
561 OS << "#include \"llvm/CodeGen/FastISel.h\"\n";
563 OS << "namespace llvm {\n";
565 OS << "namespace " << InstNS.substr(0, InstNS.size() - 2) << " {\n";
568 FastISelMap F(InstNS);
569 F.CollectPatterns(CGP);
571 F.PrintFunctionDefinitions(OS);
573 // Define the target FastISel creation function.
574 OS << "llvm::FastISel *createFastISel(MachineFunction &mf) {\n";
575 OS << " return new FastISel(mf);\n";
579 OS << "} // namespace X86\n";
581 OS << "} // namespace llvm\n";
584 FastISelEmitter::FastISelEmitter(RecordKeeper &R)