1 //===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
3 // This tablegen backend is responsible for emitting a description of the target
4 // instruction set for the code generator.
6 //===----------------------------------------------------------------------===//
8 #include "InstrSelectorEmitter.h"
9 #include "CodeGenWrappers.h"
11 #include "Support/Debug.h"
12 #include "Support/StringExtras.h"
15 NodeType::ArgResultTypes NodeType::Translate(Record *R) {
16 const std::string &Name = R->getName();
17 if (Name == "DNVT_void") return Void;
18 if (Name == "DNVT_val" ) return Val;
19 if (Name == "DNVT_arg0") return Arg0;
20 if (Name == "DNVT_arg1") return Arg1;
21 if (Name == "DNVT_ptr" ) return Ptr;
22 if (Name == "DNVT_bool") return Bool;
23 throw "Unknown DagNodeValType '" + Name + "'!";
27 //===----------------------------------------------------------------------===//
28 // TreePatternNode implementation
31 /// getValueRecord - Returns the value of this tree node as a record. For now
32 /// we only allow DefInit's as our leaf values, so this is used.
33 Record *TreePatternNode::getValueRecord() const {
34 DefInit *DI = dynamic_cast<DefInit*>(getValue());
35 assert(DI && "Instruction Selector does not yet support non-def leaves!");
40 // updateNodeType - Set the node type of N to VT if VT contains information. If
41 // N already contains a conflicting type, then throw an exception
43 bool TreePatternNode::updateNodeType(MVT::ValueType VT,
44 const std::string &RecName) {
45 if (VT == MVT::Other || getType() == VT) return false;
46 if (getType() == MVT::Other) {
51 throw "Type inferfence contradiction found for pattern " + RecName;
54 /// InstantiateNonterminals - If this pattern refers to any nonterminals which
55 /// are not themselves completely resolved, clone the nonterminal and resolve it
56 /// with the using context we provide.
58 void TreePatternNode::InstantiateNonterminals(InstrSelectorEmitter &ISE) {
60 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
61 getChild(i)->InstantiateNonterminals(ISE);
65 // If this is a leaf, it might be a reference to a nonterminal! Check now.
66 Record *R = getValueRecord();
67 if (R->isSubClassOf("Nonterminal")) {
68 Pattern *NT = ISE.getPattern(R);
69 if (!NT->isResolved()) {
70 // We found an unresolved nonterminal reference. Ask the ISE to clone
71 // it for us, then update our reference to the fresh, new, resolved,
74 Value = new DefInit(ISE.InstantiateNonterminal(NT, getType()));
80 /// clone - Make a copy of this tree and all of its children.
82 TreePatternNode *TreePatternNode::clone() const {
85 New = new TreePatternNode(Value);
87 std::vector<std::pair<TreePatternNode*, std::string> > CChildren;
88 CChildren.reserve(Children.size());
89 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
90 CChildren.push_back(std::make_pair(getChild(i)->clone(),getChildName(i)));
91 New = new TreePatternNode(Operator, CChildren);
97 std::ostream &operator<<(std::ostream &OS, const TreePatternNode &N) {
99 return OS << N.getType() << ":" << *N.getValue();
100 OS << "(" << N.getType() << ":";
101 OS << N.getOperator()->getName();
103 if (N.getNumChildren() != 0) {
104 OS << " " << *N.getChild(0);
105 for (unsigned i = 1, e = N.getNumChildren(); i != e; ++i)
106 OS << ", " << *N.getChild(i);
111 void TreePatternNode::dump() const { std::cerr << *this; }
113 //===----------------------------------------------------------------------===//
114 // Pattern implementation
117 // Parse the specified DagInit into a TreePattern which we can use.
119 Pattern::Pattern(PatternType pty, DagInit *RawPat, Record *TheRec,
120 InstrSelectorEmitter &ise)
121 : PTy(pty), ResultNode(0), TheRecord(TheRec), ISE(ise) {
123 // First, parse the pattern...
124 Tree = ParseTreePattern(RawPat);
126 // Run the type-inference engine...
129 if (PTy == Instruction || PTy == Expander) {
130 // Check to make sure there is not any unset types in the tree pattern...
132 std::cerr << "In pattern: " << *Tree << "\n";
133 error("Could not infer all types!");
136 // Check to see if we have a top-level (set) of a register.
137 if (Tree->getOperator()->getName() == "set") {
138 assert(Tree->getNumChildren() == 2 && "Set with != 2 arguments?");
139 if (!Tree->getChild(0)->isLeaf())
140 error("Arg #0 of set should be a register or register class!");
141 ResultNode = Tree->getChild(0);
142 ResultName = Tree->getChildName(0);
143 Tree = Tree->getChild(1);
147 calculateArgs(Tree, "");
150 void Pattern::error(const std::string &Msg) const {
151 std::string M = "In ";
153 case Nonterminal: M += "nonterminal "; break;
154 case Instruction: M += "instruction "; break;
155 case Expander : M += "expander "; break;
157 throw M + TheRecord->getName() + ": " + Msg;
160 /// calculateArgs - Compute the list of all of the arguments to this pattern,
161 /// which are the non-void leaf nodes in this pattern.
163 void Pattern::calculateArgs(TreePatternNode *N, const std::string &Name) {
164 if (N->isLeaf() || N->getNumChildren() == 0) {
165 if (N->getType() != MVT::isVoid)
166 Args.push_back(std::make_pair(N, Name));
168 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
169 calculateArgs(N->getChild(i), N->getChildName(i));
173 /// getIntrinsicType - Check to see if the specified record has an intrinsic
174 /// type which should be applied to it. This infer the type of register
175 /// references from the register file information, for example.
177 MVT::ValueType Pattern::getIntrinsicType(Record *R) const {
178 // Check to see if this is a register or a register class...
179 if (R->isSubClassOf("RegisterClass"))
180 return getValueType(R->getValueAsDef("RegType"));
181 else if (R->isSubClassOf("Nonterminal"))
182 return ISE.ReadNonterminal(R)->getTree()->getType();
183 else if (R->isSubClassOf("Register")) {
184 std::cerr << "WARNING: Explicit registers not handled yet!\n";
188 error("Unknown value used: " + R->getName());
192 TreePatternNode *Pattern::ParseTreePattern(DagInit *Dag) {
193 Record *Operator = Dag->getNodeType();
195 if (Operator->isSubClassOf("ValueType")) {
196 // If the operator is a ValueType, then this must be "type cast" of a leaf
198 if (Dag->getNumArgs() != 1)
199 error("Type cast only valid for a leaf node!");
201 Init *Arg = Dag->getArg(0);
202 TreePatternNode *New;
203 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
204 New = new TreePatternNode(DI);
205 // If it's a regclass or something else known, set the type.
206 New->setType(getIntrinsicType(DI->getDef()));
209 error("Unknown leaf value for tree pattern!");
212 // Apply the type cast...
213 New->updateNodeType(getValueType(Operator), TheRecord->getName());
217 if (!ISE.getNodeTypes().count(Operator))
218 error("Unrecognized node '" + Operator->getName() + "'!");
220 std::vector<std::pair<TreePatternNode*, std::string> > Children;
222 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
223 Init *Arg = Dag->getArg(i);
224 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
225 Children.push_back(std::make_pair(ParseTreePattern(DI),
226 Dag->getArgName(i)));
227 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
228 Record *R = DefI->getDef();
229 // Direct reference to a leaf DagNode? Turn it into a DagNode if its own.
230 if (R->isSubClassOf("DagNode")) {
231 Dag->setArg(i, new DagInit(R,
232 std::vector<std::pair<Init*, std::string> >()));
233 --i; // Revisit this node...
235 Children.push_back(std::make_pair(new TreePatternNode(DefI),
236 Dag->getArgName(i)));
237 // If it's a regclass or something else known, set the type.
238 Children.back().first->setType(getIntrinsicType(R));
242 error("Unknown leaf value for tree pattern!");
246 return new TreePatternNode(Operator, Children);
249 void Pattern::InferAllTypes() {
250 bool MadeChange, AnyUnset;
253 AnyUnset = InferTypes(Tree, MadeChange);
254 } while ((AnyUnset || MadeChange) && !(AnyUnset && !MadeChange));
255 Resolved = !AnyUnset;
259 // InferTypes - Perform type inference on the tree, returning true if there
260 // are any remaining untyped nodes and setting MadeChange if any changes were
262 bool Pattern::InferTypes(TreePatternNode *N, bool &MadeChange) {
263 if (N->isLeaf()) return N->getType() == MVT::Other;
265 bool AnyUnset = false;
266 Record *Operator = N->getOperator();
267 const NodeType &NT = ISE.getNodeType(Operator);
269 // Check to see if we can infer anything about the argument types from the
271 if (N->getNumChildren() != NT.ArgTypes.size())
272 error("Incorrect number of children for " + Operator->getName() + " node!");
274 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
275 TreePatternNode *Child = N->getChild(i);
276 AnyUnset |= InferTypes(Child, MadeChange);
278 switch (NT.ArgTypes[i]) {
280 MadeChange |= Child->updateNodeType(MVT::i1, TheRecord->getName());
283 MadeChange |= Child->updateNodeType(N->getChild(0)->getType(),
284 TheRecord->getName());
287 MadeChange |= Child->updateNodeType(N->getChild(1)->getType(),
288 TheRecord->getName());
291 if (Child->getType() == MVT::isVoid)
292 error("Inferred a void node in an illegal place!");
295 MadeChange |= Child->updateNodeType(ISE.getTarget().getPointerType(),
296 TheRecord->getName());
298 default: assert(0 && "Invalid argument ArgType!");
302 // See if we can infer anything about the return type now...
303 switch (NT.ResultType) {
305 MadeChange |= N->updateNodeType(MVT::isVoid, TheRecord->getName());
308 MadeChange |= N->updateNodeType(MVT::i1, TheRecord->getName());
311 MadeChange |= N->updateNodeType(N->getChild(0)->getType(),
312 TheRecord->getName());
315 MadeChange |= N->updateNodeType(N->getChild(1)->getType(),
316 TheRecord->getName());
319 MadeChange |= N->updateNodeType(ISE.getTarget().getPointerType(),
320 TheRecord->getName());
323 if (N->getType() == MVT::isVoid)
324 error("Inferred a void node in an illegal place!");
327 assert(0 && "Unhandled type constraint!");
331 return AnyUnset | N->getType() == MVT::Other;
334 /// clone - This method is used to make an exact copy of the current pattern,
335 /// then change the "TheRecord" instance variable to the specified record.
337 Pattern *Pattern::clone(Record *R) const {
338 assert(PTy == Nonterminal && "Can only clone nonterminals");
339 return new Pattern(Tree->clone(), R, Resolved, ISE);
344 std::ostream &operator<<(std::ostream &OS, const Pattern &P) {
345 switch (P.getPatternType()) {
346 case Pattern::Nonterminal: OS << "Nonterminal pattern "; break;
347 case Pattern::Instruction: OS << "Instruction pattern "; break;
348 case Pattern::Expander: OS << "Expander pattern "; break;
351 OS << P.getRecord()->getName() << ":\t";
353 if (Record *Result = P.getResult())
354 OS << Result->getName() << " = ";
358 OS << " [not completely resolved]";
362 void Pattern::dump() const { std::cerr << *this; }
366 /// getSlotName - If this is a leaf node, return the slot name that the operand
368 std::string Pattern::getSlotName() const {
369 if (getPatternType() == Pattern::Nonterminal) {
370 // Just use the nonterminal name, which will already include the type if
371 // it has been cloned.
372 return getRecord()->getName();
374 std::string SlotName;
376 SlotName = getResult()->getName()+"_";
379 return SlotName + getName(getTree()->getType());
383 /// getSlotName - If this is a leaf node, return the slot name that the
384 /// operand will update.
385 std::string Pattern::getSlotName(Record *R) {
386 if (R->isSubClassOf("Nonterminal")) {
387 // Just use the nonterminal name, which will already include the type if
388 // it has been cloned.
390 } else if (R->isSubClassOf("RegisterClass")) {
391 MVT::ValueType Ty = getValueType(R->getValueAsDef("RegType"));
392 return R->getName() + "_" + getName(Ty);
394 assert(0 && "Don't know how to get a slot name for this!");
398 //===----------------------------------------------------------------------===//
399 // PatternOrganizer implementation
402 /// addPattern - Add the specified pattern to the appropriate location in the
404 void PatternOrganizer::addPattern(Pattern *P) {
405 NodesForSlot &Nodes = AllPatterns[P->getSlotName()];
406 if (!P->getTree()->isLeaf())
407 Nodes[P->getTree()->getOperator()].push_back(P);
409 // Right now we only support DefInit's with node types...
410 Nodes[P->getTree()->getValueRecord()].push_back(P);
416 //===----------------------------------------------------------------------===//
417 // InstrSelectorEmitter implementation
420 /// ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
421 /// turning them into the more accessible NodeTypes data structure.
423 void InstrSelectorEmitter::ReadNodeTypes() {
424 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("DagNode");
425 DEBUG(std::cerr << "Getting node types: ");
426 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
427 Record *Node = Nodes[i];
429 // Translate the return type...
430 NodeType::ArgResultTypes RetTy =
431 NodeType::Translate(Node->getValueAsDef("RetType"));
433 // Translate the arguments...
434 ListInit *Args = Node->getValueAsListInit("ArgTypes");
435 std::vector<NodeType::ArgResultTypes> ArgTypes;
437 for (unsigned a = 0, e = Args->getSize(); a != e; ++a) {
438 if (DefInit *DI = dynamic_cast<DefInit*>(Args->getElement(a)))
439 ArgTypes.push_back(NodeType::Translate(DI->getDef()));
441 throw "In node " + Node->getName() + ", argument is not a Def!";
443 if (a == 0 && ArgTypes.back() == NodeType::Arg0)
444 throw "In node " + Node->getName() + ", arg 0 cannot have type 'arg0'!";
445 if (a == 1 && ArgTypes.back() == NodeType::Arg1)
446 throw "In node " + Node->getName() + ", arg 1 cannot have type 'arg1'!";
447 if (ArgTypes.back() == NodeType::Void)
448 throw "In node " + Node->getName() + ", args cannot be void type!";
450 if ((RetTy == NodeType::Arg0 && Args->getSize() == 0) ||
451 (RetTy == NodeType::Arg1 && Args->getSize() < 2))
452 throw "In node " + Node->getName() +
453 ", invalid return type for node with this many operands!";
455 // Add the node type mapping now...
456 NodeTypes[Node] = NodeType(RetTy, ArgTypes);
457 DEBUG(std::cerr << Node->getName() << ", ");
459 DEBUG(std::cerr << "DONE!\n");
462 Pattern *InstrSelectorEmitter::ReadNonterminal(Record *R) {
463 Pattern *&P = Patterns[R];
464 if (P) return P; // Don't reread it!
466 DagInit *DI = R->getValueAsDag("Pattern");
467 P = new Pattern(Pattern::Nonterminal, DI, R, *this);
468 DEBUG(std::cerr << "Parsed " << *P << "\n");
473 // ReadNonTerminals - Read in all nonterminals and incorporate them into our
475 void InstrSelectorEmitter::ReadNonterminals() {
476 std::vector<Record*> NTs = Records.getAllDerivedDefinitions("Nonterminal");
477 for (unsigned i = 0, e = NTs.size(); i != e; ++i)
478 ReadNonterminal(NTs[i]);
482 /// ReadInstructionPatterns - Read in all subclasses of Instruction, and process
483 /// those with a useful Pattern field.
485 void InstrSelectorEmitter::ReadInstructionPatterns() {
486 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
487 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
488 Record *Inst = Insts[i];
489 if (DagInit *DI = dynamic_cast<DagInit*>(Inst->getValueInit("Pattern"))) {
490 Patterns[Inst] = new Pattern(Pattern::Instruction, DI, Inst, *this);
491 DEBUG(std::cerr << "Parsed " << *Patterns[Inst] << "\n");
496 /// ReadExpanderPatterns - Read in all expander patterns...
498 void InstrSelectorEmitter::ReadExpanderPatterns() {
499 std::vector<Record*> Expanders = Records.getAllDerivedDefinitions("Expander");
500 for (unsigned i = 0, e = Expanders.size(); i != e; ++i) {
501 Record *Expander = Expanders[i];
502 DagInit *DI = Expander->getValueAsDag("Pattern");
503 Patterns[Expander] = new Pattern(Pattern::Expander, DI, Expander, *this);
504 DEBUG(std::cerr << "Parsed " << *Patterns[Expander] << "\n");
509 // InstantiateNonterminals - Instantiate any unresolved nonterminals with
510 // information from the context that they are used in.
512 void InstrSelectorEmitter::InstantiateNonterminals() {
513 DEBUG(std::cerr << "Instantiating nonterminals:\n");
514 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
515 E = Patterns.end(); I != E; ++I)
516 if (I->second->isResolved())
517 I->second->InstantiateNonterminals();
520 /// InstantiateNonterminal - This method takes the nonterminal specified by
521 /// NT, which should not be completely resolved, clones it, applies ResultTy
522 /// to its root, then runs the type inference stuff on it. This should
523 /// produce a newly resolved nonterminal, which we make a record for and
524 /// return. To be extra fancy and efficient, this only makes one clone for
525 /// each type it is instantiated with.
526 Record *InstrSelectorEmitter::InstantiateNonterminal(Pattern *NT,
527 MVT::ValueType ResultTy) {
528 assert(!NT->isResolved() && "Nonterminal is already resolved!");
530 // Check to see if we have already instantiated this pair...
531 Record* &Slot = InstantiatedNTs[std::make_pair(NT, ResultTy)];
532 if (Slot) return Slot;
534 Record *New = new Record(NT->getRecord()->getName()+"_"+getName(ResultTy));
536 // Copy over the superclasses...
537 const std::vector<Record*> &SCs = NT->getRecord()->getSuperClasses();
538 for (unsigned i = 0, e = SCs.size(); i != e; ++i)
539 New->addSuperClass(SCs[i]);
541 DEBUG(std::cerr << " Nonterminal '" << NT->getRecord()->getName()
542 << "' for type '" << getName(ResultTy) << "', producing '"
543 << New->getName() << "'\n");
545 // Copy the pattern...
546 Pattern *NewPat = NT->clone(New);
548 // Apply the type to the root...
549 NewPat->getTree()->updateNodeType(ResultTy, New->getName());
552 NewPat->InferAllTypes();
554 // Make sure everything is good to go now...
555 if (!NewPat->isResolved())
556 NewPat->error("Instantiating nonterminal did not resolve all types!");
558 // Add the pattern to the patterns map, add the record to the RecordKeeper,
559 // return the new record.
560 Patterns[New] = NewPat;
565 // CalculateComputableValues - Fill in the ComputableValues map through
566 // analysis of the patterns we are playing with.
567 void InstrSelectorEmitter::CalculateComputableValues() {
568 // Loop over all of the patterns, adding them to the ComputableValues map
569 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
570 E = Patterns.end(); I != E; ++I)
571 if (I->second->isResolved()) {
572 // We don't want to add patterns like R32 = R32. This is a hack working
573 // around a special case of a general problem, but for now we explicitly
574 // forbid these patterns. They can never match anyway.
575 Pattern *P = I->second;
576 if (!P->getResult() || !P->getTree()->isLeaf() ||
577 P->getResult() != P->getTree()->getValueRecord())
578 ComputableValues.addPattern(P);
583 // MoveIdenticalPatterns - Given a tree pattern 'P', move all of the tree
584 // patterns which have the same top-level structure as P from the 'From' list to
586 static void MoveIdenticalPatterns(TreePatternNode *P,
587 std::vector<std::pair<Pattern*, TreePatternNode*> > &From,
588 std::vector<std::pair<Pattern*, TreePatternNode*> > &To) {
589 assert(!P->isLeaf() && "All leaves are identical!");
591 const std::vector<TreePatternNode*> &PChildren = P->getChildren();
592 for (unsigned i = 0; i != From.size(); ++i) {
593 TreePatternNode *N = From[i].second;
594 assert(P->getOperator() == N->getOperator() &&"Differing operators?");
595 assert(PChildren.size() == N->getChildren().size() &&
596 "Nodes with different arity??");
597 bool isDifferent = false;
598 for (unsigned c = 0, e = PChildren.size(); c != e; ++c) {
599 TreePatternNode *PC = PChildren[c];
600 TreePatternNode *NC = N->getChild(c);
601 if (PC->isLeaf() != NC->isLeaf()) {
607 if (PC->getOperator() != NC->getOperator()) {
611 } else { // It's a leaf!
612 if (PC->getValueRecord() != NC->getValueRecord()) {
618 // If it's the same as the reference one, move it over now...
620 To.push_back(std::make_pair(From[i].first, N));
621 From.erase(From.begin()+i);
622 --i; // Don't skip an entry...
628 static std::string getNodeName(Record *R) {
629 RecordVal *RV = R->getValue("EnumName");
631 if (Init *I = RV->getValue())
632 if (StringInit *SI = dynamic_cast<StringInit*>(I))
633 return SI->getValue();
638 static void EmitPatternPredicates(TreePatternNode *Tree,
639 const std::string &VarName, std::ostream &OS){
640 OS << " && " << VarName << "->getNodeType() == ISD::"
641 << getNodeName(Tree->getOperator());
643 for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
644 if (!Tree->getChild(c)->isLeaf())
645 EmitPatternPredicates(Tree->getChild(c),
646 VarName + "->getUse(" + utostr(c)+")", OS);
649 static void EmitPatternCosts(TreePatternNode *Tree, const std::string &VarName,
651 for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
652 if (Tree->getChild(c)->isLeaf()) {
654 << Pattern::getSlotName(Tree->getChild(c)->getValueRecord()) << "("
655 << VarName << "->getUse(" << c << "))";
657 EmitPatternCosts(Tree->getChild(c),
658 VarName + "->getUse(" + utostr(c) + ")", OS);
663 // EmitMatchCosters - Given a list of patterns, which all have the same root
664 // pattern operator, emit an efficient decision tree to decide which one to
665 // pick. This is structured this way to avoid reevaluations of non-obvious
667 void InstrSelectorEmitter::EmitMatchCosters(std::ostream &OS,
668 const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
669 const std::string &VarPrefix,
670 unsigned IndentAmt) {
671 assert(!Patterns.empty() && "No patterns to emit matchers for!");
672 std::string Indent(IndentAmt, ' ');
674 // Load all of the operands of the root node into scalars for fast access
675 const NodeType &ONT = getNodeType(Patterns[0].second->getOperator());
676 for (unsigned i = 0, e = ONT.ArgTypes.size(); i != e; ++i)
677 OS << Indent << "SelectionDAGNode *" << VarPrefix << "_Op" << i
678 << " = N->getUse(" << i << ");\n";
680 // Compute the costs of computing the various nonterminals/registers, which
681 // are directly used at this level.
682 OS << "\n" << Indent << "// Operand matching costs...\n";
683 std::set<std::string> ComputedValues; // Avoid duplicate computations...
684 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
685 TreePatternNode *NParent = Patterns[i].second;
686 for (unsigned c = 0, e = NParent->getNumChildren(); c != e; ++c) {
687 TreePatternNode *N = NParent->getChild(c);
689 Record *VR = N->getValueRecord();
690 const std::string &LeafName = VR->getName();
691 std::string OpName = VarPrefix + "_Op" + utostr(c);
692 std::string ValName = OpName + "_" + LeafName + "_Cost";
693 if (!ComputedValues.count(ValName)) {
694 OS << Indent << "unsigned " << ValName << " = Match_"
695 << Pattern::getSlotName(VR) << "(" << OpName << ");\n";
696 ComputedValues.insert(ValName);
704 std::string LocCostName = VarPrefix + "_Cost";
705 OS << Indent << "unsigned " << LocCostName << "Min = ~0U >> 1;\n"
706 << Indent << "unsigned " << VarPrefix << "_PatternMin = NoMatchPattern;\n";
709 // Separate out all of the patterns into groups based on what their top-level
710 // signature looks like...
711 std::vector<std::pair<Pattern*, TreePatternNode*> > PatternsLeft(Patterns);
712 while (!PatternsLeft.empty()) {
713 // Process all of the patterns that have the same signature as the last
715 std::vector<std::pair<Pattern*, TreePatternNode*> > Group;
716 MoveIdenticalPatterns(PatternsLeft.back().second, PatternsLeft, Group);
717 assert(!Group.empty() && "Didn't at least pick the source pattern?");
720 OS << "PROCESSING GROUP:\n";
721 for (unsigned i = 0, e = Group.size(); i != e; ++i)
722 OS << " " << *Group[i].first << "\n";
726 OS << Indent << "{ // ";
728 if (Group.size() != 1) {
729 OS << Group.size() << " size group...\n";
730 OS << Indent << " unsigned " << VarPrefix << "_Pattern = NoMatch;\n";
732 OS << *Group[0].first << "\n";
733 OS << Indent << " unsigned " << VarPrefix << "_Pattern = "
734 << Group[0].first->getRecord()->getName() << "_Pattern;\n";
737 OS << Indent << " unsigned " << LocCostName << " = ";
738 if (Group.size() == 1)
739 OS << "1;\n"; // Add inst cost if at individual rec
743 // Loop over all of the operands, adding in their costs...
744 TreePatternNode *N = Group[0].second;
745 const std::vector<TreePatternNode*> &Children = N->getChildren();
747 // If necessary, emit conditionals to check for the appropriate tree
749 for (unsigned i = 0, e = Children.size(); i != e; ++i) {
750 TreePatternNode *C = Children[i];
752 // We already calculated the cost for this leaf, add it in now...
753 OS << Indent << " " << LocCostName << " += "
754 << VarPrefix << "_Op" << utostr(i) << "_"
755 << C->getValueRecord()->getName() << "_Cost;\n";
757 // If it's not a leaf, we have to check to make sure that the current
758 // node has the appropriate structure, then recurse into it...
759 OS << Indent << " if (" << VarPrefix << "_Op" << i
760 << "->getNodeType() == ISD::" << getNodeName(C->getOperator())
762 std::vector<std::pair<Pattern*, TreePatternNode*> > SubPatterns;
763 for (unsigned n = 0, e = Group.size(); n != e; ++n)
764 SubPatterns.push_back(std::make_pair(Group[n].first,
765 Group[n].second->getChild(i)));
766 EmitMatchCosters(OS, SubPatterns, VarPrefix+"_Op"+utostr(i),
768 OS << Indent << " }\n";
772 // If the cost for this match is less than the minimum computed cost so far,
773 // update the minimum cost and selected pattern.
774 OS << Indent << " if (" << LocCostName << " < " << LocCostName << "Min) { "
775 << LocCostName << "Min = " << LocCostName << "; " << VarPrefix
776 << "_PatternMin = " << VarPrefix << "_Pattern; }\n";
778 OS << Indent << "}\n";
782 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
783 Pattern *P = Patterns[i].first;
784 TreePatternNode *PTree = P->getTree();
785 unsigned PatternCost = 1;
787 // Check to see if there are any non-leaf elements in the pattern. If so,
788 // we need to emit a predicate for this match.
789 bool AnyNonLeaf = false;
790 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
791 if (!PTree->getChild(c)->isLeaf()) {
796 if (!AnyNonLeaf) { // No predicate necessary, just output a scope...
797 OS << " {// " << *P << "\n";
799 // We need to emit a predicate to make sure the tree pattern matches, do
802 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
803 if (!PTree->getChild(c)->isLeaf())
804 EmitPatternPredicates(PTree->getChild(c),
805 VarPrefix + "_Op" + utostr(c), OS);
807 OS << ") {\n // " << *P << "\n";
810 OS << " unsigned PatCost = " << PatternCost;
812 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
813 if (PTree->getChild(c)->isLeaf()) {
814 OS << " + " << VarPrefix << "_Op" << c << "_"
815 << PTree->getChild(c)->getValueRecord()->getName() << "_Cost";
817 EmitPatternCosts(PTree->getChild(c), VarPrefix + "_Op" + utostr(c), OS);
820 OS << " if (PatCost < MinCost) { MinCost = PatCost; Pattern = "
821 << P->getRecord()->getName() << "_Pattern; }\n"
826 static void ReduceAllOperands(TreePatternNode *N, const std::string &Name,
827 std::vector<std::pair<TreePatternNode*, std::string> > &Operands,
830 // If this is a leaf, register or nonterminal reference...
831 std::string SlotName = Pattern::getSlotName(N->getValueRecord());
832 OS << " ReducedValue_" << SlotName << " *" << Name << "Val = Reduce_"
833 << SlotName << "(" << Name << ", MBB);\n";
834 Operands.push_back(std::make_pair(N, Name+"Val"));
835 } else if (N->getNumChildren() == 0) {
836 // This is a reference to a leaf tree node, like an immediate or frame
838 if (N->getType() != MVT::isVoid) {
839 std::string SlotName =
840 getNodeName(N->getOperator()) + "_" + getName(N->getType());
841 OS << " ReducedValue_" << SlotName << " *" << Name << "Val = "
842 << Name << "->getValue<ReducedValue_" << SlotName << ">(ISD::"
843 << SlotName << "_Slot);\n";
844 Operands.push_back(std::make_pair(N, Name+"Val"));
847 // Otherwise this is an interior node...
848 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
849 std::string ChildName = Name + "_Op" + utostr(i);
850 OS << " SelectionDAGNode *" << ChildName << " = " << Name
851 << "->getUse(" << i << ");\n";
852 ReduceAllOperands(N->getChild(i), ChildName, Operands, OS);
857 /// PrintExpanderOperand - Print out Arg as part of the instruction emission
858 /// process for the expander pattern P. This argument may be referencing some
859 /// values defined in P, or may just be physical register references or
860 /// something like that. If PrintArg is true, we are printing out arguments to
861 /// the BuildMI call. If it is false, we are printing the result register
863 void InstrSelectorEmitter::PrintExpanderOperand(Init *Arg,
864 const std::string &NameVar,
865 TreePatternNode *ArgDeclNode,
866 Pattern *P, bool PrintArg,
868 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
869 Record *Arg = DI->getDef();
870 if (!ArgDeclNode->isLeaf())
871 P->error("Expected leaf node as argument!");
872 Record *ArgDecl = ArgDeclNode->getValueRecord();
873 if (Arg->isSubClassOf("Register")) {
874 // This is a physical register reference... make sure that the instruction
875 // requested a register!
876 if (!ArgDecl->isSubClassOf("RegisterClass"))
877 P->error("Argument mismatch for instruction pattern!");
879 // FIXME: This should check to see if the register is in the specified
881 if (PrintArg) OS << ".addReg(";
882 OS << getQualifiedName(Arg);
883 if (PrintArg) OS << ")";
885 } else if (Arg->isSubClassOf("RegisterClass")) {
886 // If this is a symbolic register class reference, we must be using a
888 if (NameVar.empty()) P->error("Did not specify WHICH register to pass!");
889 if (Arg != ArgDecl) P->error("Instruction pattern mismatch!");
891 if (PrintArg) OS << ".addReg(";
893 if (PrintArg) OS << ")";
895 } else if (Arg->getName() == "frameidx") {
896 if (!PrintArg) P->error("Cannot define a new frameidx value!");
897 OS << ".addFrameIndex(" << NameVar << ")";
900 P->error("Unknown operand type '" + Arg->getName() + "' to expander!");
901 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
902 if (!NameVar.empty())
903 P->error("Illegal to specify a name for a constant initializer arg!");
905 // Hack this check to allow R32 values with 0 as the initializer for memory
906 // references... FIXME!
907 if (ArgDeclNode->isLeaf() && II->getValue() == 0 &&
908 ArgDeclNode->getValueRecord()->getName() == "R32") {
911 if (ArgDeclNode->isLeaf() || ArgDeclNode->getOperator()->getName()!="imm")
912 P->error("Illegal immediate int value '" + itostr(II->getValue()) +
914 OS << ".addZImm(" << II->getValue() << ")";
918 P->error("Unknown operand type to expander!");
921 static std::string getArgName(Pattern *P, const std::string &ArgName,
922 const std::vector<std::pair<TreePatternNode*, std::string> > &Operands) {
923 assert(P->getNumArgs() == Operands.size() &&"Argument computation mismatch!");
924 if (ArgName.empty()) return "";
926 for (unsigned i = 0, e = P->getNumArgs(); i != e; ++i)
927 if (P->getArgName(i) == ArgName)
928 return Operands[i].second + "->Val";
930 if (ArgName == P->getResultName())
932 P->error("Pattern does not define a value named $" + ArgName + "!");
937 void InstrSelectorEmitter::run(std::ostream &OS) {
938 // Type-check all of the node types to ensure we "understand" them.
941 // Read in all of the nonterminals, instructions, and expanders...
943 ReadInstructionPatterns();
944 ReadExpanderPatterns();
946 // Instantiate any unresolved nonterminals with information from the context
947 // that they are used in.
948 InstantiateNonterminals();
950 // Clear InstantiatedNTs, we don't need it anymore...
951 InstantiatedNTs.clear();
953 DEBUG(std::cerr << "Patterns acquired:\n");
954 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
955 E = Patterns.end(); I != E; ++I)
956 if (I->second->isResolved())
957 DEBUG(std::cerr << " " << *I->second << "\n");
959 CalculateComputableValues();
961 EmitSourceFileHeader("Instruction Selector for the " + Target.getName() +
963 OS << "#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n";
965 // Output the slot number enums...
966 OS << "\nenum { // Slot numbers...\n"
967 << " LastBuiltinSlot = ISD::NumBuiltinSlots-1, // Start numbering here\n";
968 for (PatternOrganizer::iterator I = ComputableValues.begin(),
969 E = ComputableValues.end(); I != E; ++I)
970 OS << " " << I->first << "_Slot,\n";
971 OS << " NumSlots\n};\n\n// Reduction value typedefs...\n";
973 // Output the reduction value typedefs...
974 for (PatternOrganizer::iterator I = ComputableValues.begin(),
975 E = ComputableValues.end(); I != E; ++I) {
977 OS << "typedef ReducedValue<unsigned, " << I->first
978 << "_Slot> ReducedValue_" << I->first << ";\n";
981 // Output the pattern enums...
983 << "enum { // Patterns...\n"
984 << " NotComputed = 0,\n"
985 << " NoMatchPattern, \n";
986 for (PatternOrganizer::iterator I = ComputableValues.begin(),
987 E = ComputableValues.end(); I != E; ++I) {
988 OS << " // " << I->first << " patterns...\n";
989 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
990 E = I->second.end(); J != E; ++J)
991 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
992 OS << " " << J->second[i]->getRecord()->getName() << "_Pattern,\n";
996 //===--------------------------------------------------------------------===//
997 // Emit the class definition...
999 OS << "namespace {\n"
1000 << " class " << Target.getName() << "ISel {\n"
1001 << " SelectionDAG &DAG;\n"
1003 << " X86ISel(SelectionDAG &D) : DAG(D) {}\n"
1004 << " void generateCode();\n"
1006 << " unsigned makeAnotherReg(const TargetRegisterClass *RC) {\n"
1007 << " return DAG.getMachineFunction().getSSARegMap()->createVirt"
1008 "ualRegister(RC);\n"
1010 << " // DAG matching methods for classes... all of these methods"
1011 " return the cost\n"
1012 << " // of producing a value of the specified class and type, which"
1014 << " // added to the DAG node.\n";
1016 // Output all of the matching prototypes for slots...
1017 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1018 E = ComputableValues.end(); I != E; ++I)
1019 OS << " unsigned Match_" << I->first << "(SelectionDAGNode *N);\n";
1020 OS << "\n // DAG matching methods for DAG nodes...\n";
1022 // Output all of the matching prototypes for slot/node pairs
1023 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1024 E = ComputableValues.end(); I != E; ++I)
1025 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1026 E = I->second.end(); J != E; ++J)
1027 OS << " unsigned Match_" << I->first << "_" << getNodeName(J->first)
1028 << "(SelectionDAGNode *N);\n";
1030 // Output all of the dag reduction methods prototypes...
1031 OS << "\n // DAG reduction methods...\n";
1032 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1033 E = ComputableValues.end(); I != E; ++I)
1034 OS << " ReducedValue_" << I->first << " *Reduce_" << I->first
1035 << "(SelectionDAGNode *N,\n" << std::string(27+2*I->first.size(), ' ')
1036 << "MachineBasicBlock *MBB);\n";
1039 // Emit the generateCode entry-point...
1040 OS << "void X86ISel::generateCode() {\n"
1041 << " SelectionDAGNode *Root = DAG.getRoot();\n"
1042 << " assert(Root->getValueType() == MVT::isVoid && "
1043 "\"Root of DAG produces value??\");\n\n"
1044 << " std::cerr << \"\\n\";\n"
1045 << " unsigned Cost = Match_Void_void(Root);\n"
1046 << " if (Cost >= ~0U >> 1) {\n"
1047 << " std::cerr << \"Match failed!\\n\";\n"
1048 << " Root->dump();\n"
1051 << " std::cerr << \"Total DAG Cost: \" << Cost << \"\\n\\n\";\n\n"
1052 << " Reduce_Void_void(Root, 0);\n"
1054 << "//===" << std::string(70, '-') << "===//\n"
1055 << "// Matching methods...\n"
1058 //===--------------------------------------------------------------------===//
1059 // Emit all of the matcher methods...
1061 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1062 E = ComputableValues.end(); I != E; ++I) {
1063 const std::string &SlotName = I->first;
1064 OS << "unsigned " << Target.getName() << "ISel::Match_" << SlotName
1065 << "(SelectionDAGNode *N) {\n"
1066 << " assert(N->getValueType() == MVT::"
1067 << getEnumName((*I->second.begin()).second[0]->getTree()->getType())
1068 << ");\n" << " // If we already have a cost available for " << SlotName
1070 << " if (N->getPatternFor(" << SlotName << "_Slot))\n"
1071 << " return N->getCostFor(" << SlotName << "_Slot);\n\n"
1072 << " unsigned Cost;\n"
1073 << " switch (N->getNodeType()) {\n"
1074 << " default: Cost = ~0U >> 1; // Match failed\n"
1075 << " N->setPatternCostFor(" << SlotName << "_Slot, NoMatchPattern, Cost, NumSlots);\n"
1078 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1079 E = I->second.end(); J != E; ++J)
1080 if (!J->first->isSubClassOf("Nonterminal"))
1081 OS << " case ISD::" << getNodeName(J->first) << ":\tCost = Match_"
1082 << SlotName << "_" << getNodeName(J->first) << "(N); break;\n";
1083 OS << " }\n"; // End of the switch statement
1085 // Emit any patterns which have a nonterminal leaf as the RHS. These may
1086 // match multiple root nodes, so they cannot be handled with the switch...
1087 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1088 E = I->second.end(); J != E; ++J)
1089 if (J->first->isSubClassOf("Nonterminal")) {
1090 OS << " unsigned " << J->first->getName() << "_Cost = Match_"
1091 << getNodeName(J->first) << "(N);\n"
1092 << " if (" << getNodeName(J->first) << "_Cost < Cost) Cost = "
1093 << getNodeName(J->first) << "_Cost;\n";
1096 OS << " return Cost;\n}\n\n";
1098 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1099 E = I->second.end(); J != E; ++J) {
1100 Record *Operator = J->first;
1101 bool isNonterm = Operator->isSubClassOf("Nonterminal");
1103 OS << "unsigned " << Target.getName() << "ISel::Match_";
1104 if (!isNonterm) OS << SlotName << "_";
1105 OS << getNodeName(Operator) << "(SelectionDAGNode *N) {\n"
1106 << " unsigned Pattern = NoMatchPattern;\n"
1107 << " unsigned MinCost = ~0U >> 1;\n";
1109 std::vector<std::pair<Pattern*, TreePatternNode*> > Patterns;
1110 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
1111 Patterns.push_back(std::make_pair(J->second[i],
1112 J->second[i]->getTree()));
1113 EmitMatchCosters(OS, Patterns, "N", 2);
1115 OS << "\n N->setPatternCostFor(" << SlotName
1116 << "_Slot, Pattern, MinCost, NumSlots);\n"
1117 << " return MinCost;\n"
1123 //===--------------------------------------------------------------------===//
1124 // Emit all of the reducer methods...
1126 OS << "\n\n//===" << std::string(70, '-') << "===//\n"
1127 << "// Reducer methods...\n"
1130 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1131 E = ComputableValues.end(); I != E; ++I) {
1132 const std::string &SlotName = I->first;
1133 OS << "ReducedValue_" << SlotName << " *" << Target.getName()
1134 << "ISel::Reduce_" << SlotName
1135 << "(SelectionDAGNode *N, MachineBasicBlock *MBB) {\n"
1136 << " ReducedValue_" << SlotName << " *Val = N->hasValue<ReducedValue_"
1137 << SlotName << ">(" << SlotName << "_Slot);\n"
1138 << " if (Val) return Val;\n"
1139 << " if (N->getBB()) MBB = N->getBB();\n\n"
1140 << " switch (N->getPatternFor(" << SlotName << "_Slot)) {\n";
1142 // Loop over all of the patterns that can produce a value for this slot...
1143 PatternOrganizer::NodesForSlot &NodesForSlot = I->second;
1144 for (PatternOrganizer::NodesForSlot::iterator J = NodesForSlot.begin(),
1145 E = NodesForSlot.end(); J != E; ++J)
1146 for (unsigned i = 0, e = J->second.size(); i != e; ++i) {
1147 Pattern *P = J->second[i];
1148 OS << " case " << P->getRecord()->getName() << "_Pattern: {\n"
1149 << " // " << *P << "\n";
1150 // Loop over the operands, reducing them...
1151 std::vector<std::pair<TreePatternNode*, std::string> > Operands;
1152 ReduceAllOperands(P->getTree(), "N", Operands, OS);
1154 // Now that we have reduced all of our operands, and have the values
1155 // that reduction produces, perform the reduction action for this
1159 // If the pattern produces a register result, generate a new register
1161 if (Record *R = P->getResult()) {
1162 assert(R->isSubClassOf("RegisterClass") &&
1163 "Only handle register class results so far!");
1164 OS << " unsigned NewReg = makeAnotherReg(" << Target.getName()
1165 << "::" << R->getName() << "RegisterClass);\n";
1167 DEBUG(OS << " std::cerr << \"%reg\" << NewReg << \" =\t\";\n");
1169 DEBUG(OS << " std::cerr << \"\t\t\";\n");
1173 // Print out the pattern that matched...
1174 DEBUG(OS << " std::cerr << \" " << P->getRecord()->getName() <<'"');
1175 DEBUG(for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1176 if (Operands[i].first->isLeaf()) {
1177 Record *RV = Operands[i].first->getValueRecord();
1178 assert(RV->isSubClassOf("RegisterClass") &&
1179 "Only handles registers here so far!");
1180 OS << " << \" %reg\" << " << Operands[i].second
1183 OS << " << ' ' << " << Operands[i].second
1186 DEBUG(OS << " << \"\\n\";\n");
1188 // Generate the reduction code appropriate to the particular type of
1189 // pattern that this is...
1190 switch (P->getPatternType()) {
1191 case Pattern::Instruction:
1192 // Instruction patterns just emit a single MachineInstr, using BuildMI
1193 OS << " BuildMI(MBB, " << Target.getName() << "::"
1194 << P->getRecord()->getName() << ", " << Operands.size();
1195 if (P->getResult()) OS << ", NewReg";
1198 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1199 if (Operands[i].first->isLeaf()) {
1200 Record *RV = Operands[i].first->getValueRecord();
1201 assert(RV->isSubClassOf("RegisterClass") &&
1202 "Only handles registers here so far!");
1203 OS << ".addReg(" << Operands[i].second << "->Val)";
1205 OS << ".addZImm(" << Operands[i].second << "->Val)";
1209 case Pattern::Expander: {
1210 // Expander patterns emit one machine instr for each instruction in
1211 // the list of instructions expanded to.
1212 ListInit *Insts = P->getRecord()->getValueAsListInit("Result");
1213 for (unsigned IN = 0, e = Insts->getSize(); IN != e; ++IN) {
1214 DagInit *DIInst = dynamic_cast<DagInit*>(Insts->getElement(IN));
1215 if (!DIInst) P->error("Result list must contain instructions!");
1216 Pattern *InstPat = getPattern(DIInst->getNodeType());
1217 if (!InstPat || InstPat->getPatternType() != Pattern::Instruction)
1218 P->error("Instruction list must contain Instruction patterns!");
1220 bool hasResult = InstPat->getResult() != 0;
1221 if (InstPat->getNumArgs() != DIInst->getNumArgs()-hasResult) {
1222 P->error("Incorrect number of arguments specified for inst '" +
1223 InstPat->getRecord()->getName() + "' in result list!");
1226 // Start emission of the instruction...
1227 OS << " BuildMI(MBB, " << Target.getName() << "::"
1228 << InstPat->getRecord()->getName() << ", "
1229 << DIInst->getNumArgs()-hasResult;
1230 // Emit register result if necessary..
1231 if (Record *R = InstPat->getResult()) {
1232 std::string ArgNameVal =
1233 getArgName(P, DIInst->getArgName(0), Operands);
1234 PrintExpanderOperand(DIInst->getArg(0), ArgNameVal,
1235 InstPat->getResultNode(), P, false,
1240 for (unsigned i = hasResult, e = DIInst->getNumArgs(); i != e; ++i){
1241 std::string ArgNameVal =
1242 getArgName(P, DIInst->getArgName(i), Operands);
1244 PrintExpanderOperand(DIInst->getArg(i), ArgNameVal,
1245 InstPat->getArg(i-hasResult), P, true, OS);
1253 assert(0 && "Reduction of this type of pattern not implemented!");
1256 OS << " Val = new ReducedValue_" << SlotName << "(" << Result<<");\n"
1262 OS << " default: assert(0 && \"Unknown " << SlotName << " pattern!\");\n"
1263 << " }\n\n N->addValue(Val); // Do not ever recalculate this\n"
1264 << " return Val;\n}\n\n";