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_ptr" ) return Ptr;
21 throw "Unknown DagNodeValType '" + Name + "'!";
25 //===----------------------------------------------------------------------===//
26 // TreePatternNode implementation
29 /// getValueRecord - Returns the value of this tree node as a record. For now
30 /// we only allow DefInit's as our leaf values, so this is used.
31 Record *TreePatternNode::getValueRecord() const {
32 DefInit *DI = dynamic_cast<DefInit*>(getValue());
33 assert(DI && "Instruction Selector does not yet support non-def leaves!");
38 // updateNodeType - Set the node type of N to VT if VT contains information. If
39 // N already contains a conflicting type, then throw an exception
41 bool TreePatternNode::updateNodeType(MVT::ValueType VT,
42 const std::string &RecName) {
43 if (VT == MVT::Other || getType() == VT) return false;
44 if (getType() == MVT::Other) {
49 throw "Type inferfence contradiction found for pattern " + RecName;
52 /// InstantiateNonterminals - If this pattern refers to any nonterminals which
53 /// are not themselves completely resolved, clone the nonterminal and resolve it
54 /// with the using context we provide.
56 void TreePatternNode::InstantiateNonterminals(InstrSelectorEmitter &ISE) {
58 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
59 getChild(i)->InstantiateNonterminals(ISE);
63 // If this is a leaf, it might be a reference to a nonterminal! Check now.
64 Record *R = getValueRecord();
65 if (R->isSubClassOf("Nonterminal")) {
66 Pattern *NT = ISE.getPattern(R);
67 if (!NT->isResolved()) {
68 // We found an unresolved nonterminal reference. Ask the ISE to clone
69 // it for us, then update our reference to the fresh, new, resolved,
72 Value = new DefInit(ISE.InstantiateNonterminal(NT, getType()));
78 /// clone - Make a copy of this tree and all of its children.
80 TreePatternNode *TreePatternNode::clone() const {
83 New = new TreePatternNode(Value);
85 std::vector<std::pair<TreePatternNode*, std::string> > CChildren;
86 CChildren.reserve(Children.size());
87 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
88 CChildren.push_back(std::make_pair(getChild(i)->clone(),getChildName(i)));
89 New = new TreePatternNode(Operator, CChildren);
95 std::ostream &operator<<(std::ostream &OS, const TreePatternNode &N) {
97 return OS << N.getType() << ":" << *N.getValue();
98 OS << "(" << N.getType() << ":";
99 OS << N.getOperator()->getName();
101 if (N.getNumChildren() != 0) {
102 OS << " " << *N.getChild(0);
103 for (unsigned i = 1, e = N.getNumChildren(); i != e; ++i)
104 OS << ", " << *N.getChild(i);
109 void TreePatternNode::dump() const { std::cerr << *this; }
111 //===----------------------------------------------------------------------===//
112 // Pattern implementation
115 // Parse the specified DagInit into a TreePattern which we can use.
117 Pattern::Pattern(PatternType pty, DagInit *RawPat, Record *TheRec,
118 InstrSelectorEmitter &ise)
119 : PTy(pty), TheRecord(TheRec), ISE(ise) {
121 // First, parse the pattern...
122 Tree = ParseTreePattern(RawPat);
124 // Run the type-inference engine...
127 if (PTy == Instruction || PTy == Expander) {
128 // Check to make sure there is not any unset types in the tree pattern...
130 std::cerr << "In pattern: " << *Tree << "\n";
131 error("Could not infer all types!");
134 // Check to see if we have a top-level (set) of a register.
135 if (Tree->getOperator()->getName() == "set") {
136 assert(Tree->getNumChildren() == 2 && "Set with != 2 arguments?");
137 if (!Tree->getChild(0)->isLeaf())
138 error("Arg #0 of set should be a register or register class!");
139 Result = Tree->getChild(0)->getValueRecord();
140 Tree = Tree->getChild(1);
144 calculateArgs(Tree, "");
147 void Pattern::error(const std::string &Msg) const {
148 std::string M = "In ";
150 case Nonterminal: M += "nonterminal "; break;
151 case Instruction: M += "instruction "; break;
152 case Expander : M += "expander "; break;
154 throw M + TheRecord->getName() + ": " + Msg;
157 /// calculateArgs - Compute the list of all of the arguments to this pattern,
158 /// which are the non-void leaf nodes in this pattern.
160 void Pattern::calculateArgs(TreePatternNode *N, const std::string &Name) {
161 if (N->isLeaf() || N->getNumChildren() == 0) {
162 if (N->getType() != MVT::isVoid)
163 Args.push_back(std::make_pair(N, Name));
165 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
166 calculateArgs(N->getChild(i), N->getChildName(i));
170 /// getIntrinsicType - Check to see if the specified record has an intrinsic
171 /// type which should be applied to it. This infer the type of register
172 /// references from the register file information, for example.
174 MVT::ValueType Pattern::getIntrinsicType(Record *R) const {
175 // Check to see if this is a register or a register class...
176 if (R->isSubClassOf("RegisterClass"))
177 return getValueType(R->getValueAsDef("RegType"));
178 else if (R->isSubClassOf("Nonterminal"))
179 return ISE.ReadNonterminal(R)->getTree()->getType();
180 else if (R->isSubClassOf("Register")) {
181 std::cerr << "WARNING: Explicit registers not handled yet!\n";
185 error("Unknown value used: " + R->getName());
189 TreePatternNode *Pattern::ParseTreePattern(DagInit *Dag) {
190 Record *Operator = Dag->getNodeType();
192 if (Operator->isSubClassOf("ValueType")) {
193 // If the operator is a ValueType, then this must be "type cast" of a leaf
195 if (Dag->getNumArgs() != 1)
196 error("Type cast only valid for a leaf node!");
198 Init *Arg = Dag->getArg(0);
199 TreePatternNode *New;
200 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
201 New = new TreePatternNode(DI);
202 // If it's a regclass or something else known, set the type.
203 New->setType(getIntrinsicType(DI->getDef()));
206 error("Unknown leaf value for tree pattern!");
209 // Apply the type cast...
210 New->updateNodeType(getValueType(Operator), TheRecord->getName());
214 if (!ISE.getNodeTypes().count(Operator))
215 error("Unrecognized node '" + Operator->getName() + "'!");
217 std::vector<std::pair<TreePatternNode*, std::string> > Children;
219 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
220 Init *Arg = Dag->getArg(i);
221 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
222 Children.push_back(std::make_pair(ParseTreePattern(DI),
223 Dag->getArgName(i)));
224 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
225 Record *R = DefI->getDef();
226 // Direct reference to a leaf DagNode? Turn it into a DagNode if its own.
227 if (R->isSubClassOf("DagNode")) {
228 Dag->setArg(i, new DagInit(R,
229 std::vector<std::pair<Init*, std::string> >()));
230 --i; // Revisit this node...
232 Children.push_back(std::make_pair(new TreePatternNode(DefI),
233 Dag->getArgName(i)));
234 // If it's a regclass or something else known, set the type.
235 Children.back().first->setType(getIntrinsicType(R));
239 error("Unknown leaf value for tree pattern!");
243 return new TreePatternNode(Operator, Children);
246 void Pattern::InferAllTypes() {
247 bool MadeChange, AnyUnset;
250 AnyUnset = InferTypes(Tree, MadeChange);
251 } while ((AnyUnset || MadeChange) && !(AnyUnset && !MadeChange));
252 Resolved = !AnyUnset;
256 // InferTypes - Perform type inference on the tree, returning true if there
257 // are any remaining untyped nodes and setting MadeChange if any changes were
259 bool Pattern::InferTypes(TreePatternNode *N, bool &MadeChange) {
260 if (N->isLeaf()) return N->getType() == MVT::Other;
262 bool AnyUnset = false;
263 Record *Operator = N->getOperator();
264 const NodeType &NT = ISE.getNodeType(Operator);
266 // Check to see if we can infer anything about the argument types from the
268 if (N->getNumChildren() != NT.ArgTypes.size())
269 error("Incorrect number of children for " + Operator->getName() + " node!");
271 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
272 TreePatternNode *Child = N->getChild(i);
273 AnyUnset |= InferTypes(Child, MadeChange);
275 switch (NT.ArgTypes[i]) {
277 MadeChange |= Child->updateNodeType(N->getChild(0)->getType(),
278 TheRecord->getName());
281 if (Child->getType() == MVT::isVoid)
282 error("Inferred a void node in an illegal place!");
285 MadeChange |= Child->updateNodeType(ISE.getTarget().getPointerType(),
286 TheRecord->getName());
288 default: assert(0 && "Invalid argument ArgType!");
292 // See if we can infer anything about the return type now...
293 switch (NT.ResultType) {
295 MadeChange |= N->updateNodeType(MVT::isVoid, TheRecord->getName());
298 MadeChange |= N->updateNodeType(N->getChild(0)->getType(),
299 TheRecord->getName());
303 MadeChange |= N->updateNodeType(ISE.getTarget().getPointerType(),
304 TheRecord->getName());
307 if (N->getType() == MVT::isVoid)
308 error("Inferred a void node in an illegal place!");
311 assert(0 && "Unhandled type constraint!");
315 return AnyUnset | N->getType() == MVT::Other;
318 /// clone - This method is used to make an exact copy of the current pattern,
319 /// then change the "TheRecord" instance variable to the specified record.
321 Pattern *Pattern::clone(Record *R) const {
322 assert(PTy == Nonterminal && "Can only clone nonterminals");
323 return new Pattern(Tree->clone(), R, Resolved, ISE);
328 std::ostream &operator<<(std::ostream &OS, const Pattern &P) {
329 switch (P.getPatternType()) {
330 case Pattern::Nonterminal: OS << "Nonterminal pattern "; break;
331 case Pattern::Instruction: OS << "Instruction pattern "; break;
332 case Pattern::Expander: OS << "Expander pattern "; break;
335 OS << P.getRecord()->getName() << ":\t";
337 if (Record *Result = P.getResult())
338 OS << Result->getName() << " = ";
342 OS << " [not completely resolved]";
346 void Pattern::dump() const { std::cerr << *this; }
350 /// getSlotName - If this is a leaf node, return the slot name that the operand
352 std::string Pattern::getSlotName() const {
353 if (getPatternType() == Pattern::Nonterminal) {
354 // Just use the nonterminal name, which will already include the type if
355 // it has been cloned.
356 return getRecord()->getName();
358 std::string SlotName;
360 SlotName = getResult()->getName()+"_";
363 return SlotName + getName(getTree()->getType());
367 /// getSlotName - If this is a leaf node, return the slot name that the
368 /// operand will update.
369 std::string Pattern::getSlotName(Record *R) {
370 if (R->isSubClassOf("Nonterminal")) {
371 // Just use the nonterminal name, which will already include the type if
372 // it has been cloned.
374 } else if (R->isSubClassOf("RegisterClass")) {
375 MVT::ValueType Ty = getValueType(R->getValueAsDef("RegType"));
376 return R->getName() + "_" + getName(Ty);
378 assert(0 && "Don't know how to get a slot name for this!");
382 //===----------------------------------------------------------------------===//
383 // PatternOrganizer implementation
386 /// addPattern - Add the specified pattern to the appropriate location in the
388 void PatternOrganizer::addPattern(Pattern *P) {
389 NodesForSlot &Nodes = AllPatterns[P->getSlotName()];
390 if (!P->getTree()->isLeaf())
391 Nodes[P->getTree()->getOperator()].push_back(P);
393 // Right now we only support DefInit's with node types...
394 Nodes[P->getTree()->getValueRecord()].push_back(P);
400 //===----------------------------------------------------------------------===//
401 // InstrSelectorEmitter implementation
404 /// ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
405 /// turning them into the more accessible NodeTypes data structure.
407 void InstrSelectorEmitter::ReadNodeTypes() {
408 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("DagNode");
409 DEBUG(std::cerr << "Getting node types: ");
410 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
411 Record *Node = Nodes[i];
413 // Translate the return type...
414 NodeType::ArgResultTypes RetTy =
415 NodeType::Translate(Node->getValueAsDef("RetType"));
417 // Translate the arguments...
418 ListInit *Args = Node->getValueAsListInit("ArgTypes");
419 std::vector<NodeType::ArgResultTypes> ArgTypes;
421 for (unsigned a = 0, e = Args->getSize(); a != e; ++a) {
422 if (DefInit *DI = dynamic_cast<DefInit*>(Args->getElement(a)))
423 ArgTypes.push_back(NodeType::Translate(DI->getDef()));
425 throw "In node " + Node->getName() + ", argument is not a Def!";
427 if (a == 0 && ArgTypes.back() == NodeType::Arg0)
428 throw "In node " + Node->getName() + ", arg 0 cannot have type 'arg0'!";
429 if (ArgTypes.back() == NodeType::Void)
430 throw "In node " + Node->getName() + ", args cannot be void type!";
432 if (RetTy == NodeType::Arg0 && Args->getSize() == 0)
433 throw "In node " + Node->getName() +
434 ", invalid return type for nullary node!";
436 // Add the node type mapping now...
437 NodeTypes[Node] = NodeType(RetTy, ArgTypes);
438 DEBUG(std::cerr << Node->getName() << ", ");
440 DEBUG(std::cerr << "DONE!\n");
443 Pattern *InstrSelectorEmitter::ReadNonterminal(Record *R) {
444 Pattern *&P = Patterns[R];
445 if (P) return P; // Don't reread it!
447 DagInit *DI = R->getValueAsDag("Pattern");
448 P = new Pattern(Pattern::Nonterminal, DI, R, *this);
449 DEBUG(std::cerr << "Parsed " << *P << "\n");
454 // ReadNonTerminals - Read in all nonterminals and incorporate them into our
456 void InstrSelectorEmitter::ReadNonterminals() {
457 std::vector<Record*> NTs = Records.getAllDerivedDefinitions("Nonterminal");
458 for (unsigned i = 0, e = NTs.size(); i != e; ++i)
459 ReadNonterminal(NTs[i]);
463 /// ReadInstructionPatterns - Read in all subclasses of Instruction, and process
464 /// those with a useful Pattern field.
466 void InstrSelectorEmitter::ReadInstructionPatterns() {
467 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
468 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
469 Record *Inst = Insts[i];
470 if (DagInit *DI = dynamic_cast<DagInit*>(Inst->getValueInit("Pattern"))) {
471 Patterns[Inst] = new Pattern(Pattern::Instruction, DI, Inst, *this);
472 DEBUG(std::cerr << "Parsed " << *Patterns[Inst] << "\n");
477 /// ReadExpanderPatterns - Read in all expander patterns...
479 void InstrSelectorEmitter::ReadExpanderPatterns() {
480 std::vector<Record*> Expanders = Records.getAllDerivedDefinitions("Expander");
481 for (unsigned i = 0, e = Expanders.size(); i != e; ++i) {
482 Record *Expander = Expanders[i];
483 DagInit *DI = Expander->getValueAsDag("Pattern");
484 Patterns[Expander] = new Pattern(Pattern::Expander, DI, Expander, *this);
485 DEBUG(std::cerr << "Parsed " << *Patterns[Expander] << "\n");
490 // InstantiateNonterminals - Instantiate any unresolved nonterminals with
491 // information from the context that they are used in.
493 void InstrSelectorEmitter::InstantiateNonterminals() {
494 DEBUG(std::cerr << "Instantiating nonterminals:\n");
495 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
496 E = Patterns.end(); I != E; ++I)
497 if (I->second->isResolved())
498 I->second->InstantiateNonterminals();
501 /// InstantiateNonterminal - This method takes the nonterminal specified by
502 /// NT, which should not be completely resolved, clones it, applies ResultTy
503 /// to its root, then runs the type inference stuff on it. This should
504 /// produce a newly resolved nonterminal, which we make a record for and
505 /// return. To be extra fancy and efficient, this only makes one clone for
506 /// each type it is instantiated with.
507 Record *InstrSelectorEmitter::InstantiateNonterminal(Pattern *NT,
508 MVT::ValueType ResultTy) {
509 assert(!NT->isResolved() && "Nonterminal is already resolved!");
511 // Check to see if we have already instantiated this pair...
512 Record* &Slot = InstantiatedNTs[std::make_pair(NT, ResultTy)];
513 if (Slot) return Slot;
515 Record *New = new Record(NT->getRecord()->getName()+"_"+getName(ResultTy));
517 // Copy over the superclasses...
518 const std::vector<Record*> &SCs = NT->getRecord()->getSuperClasses();
519 for (unsigned i = 0, e = SCs.size(); i != e; ++i)
520 New->addSuperClass(SCs[i]);
522 DEBUG(std::cerr << " Nonterminal '" << NT->getRecord()->getName()
523 << "' for type '" << getName(ResultTy) << "', producing '"
524 << New->getName() << "'\n");
526 // Copy the pattern...
527 Pattern *NewPat = NT->clone(New);
529 // Apply the type to the root...
530 NewPat->getTree()->updateNodeType(ResultTy, New->getName());
533 NewPat->InferAllTypes();
535 // Make sure everything is good to go now...
536 if (!NewPat->isResolved())
537 NewPat->error("Instantiating nonterminal did not resolve all types!");
539 // Add the pattern to the patterns map, add the record to the RecordKeeper,
540 // return the new record.
541 Patterns[New] = NewPat;
546 // CalculateComputableValues - Fill in the ComputableValues map through
547 // analysis of the patterns we are playing with.
548 void InstrSelectorEmitter::CalculateComputableValues() {
549 // Loop over all of the patterns, adding them to the ComputableValues map
550 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
551 E = Patterns.end(); I != E; ++I)
552 if (I->second->isResolved()) {
553 // We don't want to add patterns like R32 = R32. This is a hack working
554 // around a special case of a general problem, but for now we explicitly
555 // forbid these patterns. They can never match anyway.
556 Pattern *P = I->second;
557 if (!P->getResult() || !P->getTree()->isLeaf() ||
558 P->getResult() != P->getTree()->getValueRecord())
559 ComputableValues.addPattern(P);
564 // MoveIdenticalPatterns - Given a tree pattern 'P', move all of the tree
565 // patterns which have the same top-level structure as P from the 'From' list to
567 static void MoveIdenticalPatterns(TreePatternNode *P,
568 std::vector<std::pair<Pattern*, TreePatternNode*> > &From,
569 std::vector<std::pair<Pattern*, TreePatternNode*> > &To) {
570 assert(!P->isLeaf() && "All leaves are identical!");
572 const std::vector<TreePatternNode*> &PChildren = P->getChildren();
573 for (unsigned i = 0; i != From.size(); ++i) {
574 TreePatternNode *N = From[i].second;
575 assert(P->getOperator() == N->getOperator() &&"Differing operators?");
576 assert(PChildren.size() == N->getChildren().size() &&
577 "Nodes with different arity??");
578 bool isDifferent = false;
579 for (unsigned c = 0, e = PChildren.size(); c != e; ++c) {
580 TreePatternNode *PC = PChildren[c];
581 TreePatternNode *NC = N->getChild(c);
582 if (PC->isLeaf() != NC->isLeaf()) {
588 if (PC->getOperator() != NC->getOperator()) {
592 } else { // It's a leaf!
593 if (PC->getValueRecord() != NC->getValueRecord()) {
599 // If it's the same as the reference one, move it over now...
601 To.push_back(std::make_pair(From[i].first, N));
602 From.erase(From.begin()+i);
603 --i; // Don't skip an entry...
609 static std::string getNodeName(Record *R) {
610 RecordVal *RV = R->getValue("EnumName");
612 if (Init *I = RV->getValue())
613 if (StringInit *SI = dynamic_cast<StringInit*>(I))
614 return SI->getValue();
619 static void EmitPatternPredicates(TreePatternNode *Tree,
620 const std::string &VarName, std::ostream &OS){
621 OS << " && " << VarName << "->getNodeType() == ISD::"
622 << getNodeName(Tree->getOperator());
624 for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
625 if (!Tree->getChild(c)->isLeaf())
626 EmitPatternPredicates(Tree->getChild(c),
627 VarName + "->getUse(" + utostr(c)+")", OS);
630 static void EmitPatternCosts(TreePatternNode *Tree, const std::string &VarName,
632 for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
633 if (Tree->getChild(c)->isLeaf()) {
635 << Pattern::getSlotName(Tree->getChild(c)->getValueRecord()) << "("
636 << VarName << "->getUse(" << c << "))";
638 EmitPatternCosts(Tree->getChild(c),
639 VarName + "->getUse(" + utostr(c) + ")", OS);
644 // EmitMatchCosters - Given a list of patterns, which all have the same root
645 // pattern operator, emit an efficient decision tree to decide which one to
646 // pick. This is structured this way to avoid reevaluations of non-obvious
648 void InstrSelectorEmitter::EmitMatchCosters(std::ostream &OS,
649 const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
650 const std::string &VarPrefix,
651 unsigned IndentAmt) {
652 assert(!Patterns.empty() && "No patterns to emit matchers for!");
653 std::string Indent(IndentAmt, ' ');
655 // Load all of the operands of the root node into scalars for fast access
656 const NodeType &ONT = getNodeType(Patterns[0].second->getOperator());
657 for (unsigned i = 0, e = ONT.ArgTypes.size(); i != e; ++i)
658 OS << Indent << "SelectionDAGNode *" << VarPrefix << "_Op" << i
659 << " = N->getUse(" << i << ");\n";
661 // Compute the costs of computing the various nonterminals/registers, which
662 // are directly used at this level.
663 OS << "\n" << Indent << "// Operand matching costs...\n";
664 std::set<std::string> ComputedValues; // Avoid duplicate computations...
665 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
666 TreePatternNode *NParent = Patterns[i].second;
667 for (unsigned c = 0, e = NParent->getNumChildren(); c != e; ++c) {
668 TreePatternNode *N = NParent->getChild(c);
670 Record *VR = N->getValueRecord();
671 const std::string &LeafName = VR->getName();
672 std::string OpName = VarPrefix + "_Op" + utostr(c);
673 std::string ValName = OpName + "_" + LeafName + "_Cost";
674 if (!ComputedValues.count(ValName)) {
675 OS << Indent << "unsigned " << ValName << " = Match_"
676 << Pattern::getSlotName(VR) << "(" << OpName << ");\n";
677 ComputedValues.insert(ValName);
685 std::string LocCostName = VarPrefix + "_Cost";
686 OS << Indent << "unsigned " << LocCostName << "Min = ~0U >> 1;\n"
687 << Indent << "unsigned " << VarPrefix << "_PatternMin = NoMatchPattern;\n";
690 // Separate out all of the patterns into groups based on what their top-level
691 // signature looks like...
692 std::vector<std::pair<Pattern*, TreePatternNode*> > PatternsLeft(Patterns);
693 while (!PatternsLeft.empty()) {
694 // Process all of the patterns that have the same signature as the last
696 std::vector<std::pair<Pattern*, TreePatternNode*> > Group;
697 MoveIdenticalPatterns(PatternsLeft.back().second, PatternsLeft, Group);
698 assert(!Group.empty() && "Didn't at least pick the source pattern?");
701 OS << "PROCESSING GROUP:\n";
702 for (unsigned i = 0, e = Group.size(); i != e; ++i)
703 OS << " " << *Group[i].first << "\n";
707 OS << Indent << "{ // ";
709 if (Group.size() != 1) {
710 OS << Group.size() << " size group...\n";
711 OS << Indent << " unsigned " << VarPrefix << "_Pattern = NoMatch;\n";
713 OS << *Group[0].first << "\n";
714 OS << Indent << " unsigned " << VarPrefix << "_Pattern = "
715 << Group[0].first->getRecord()->getName() << "_Pattern;\n";
718 OS << Indent << " unsigned " << LocCostName << " = ";
719 if (Group.size() == 1)
720 OS << "1;\n"; // Add inst cost if at individual rec
724 // Loop over all of the operands, adding in their costs...
725 TreePatternNode *N = Group[0].second;
726 const std::vector<TreePatternNode*> &Children = N->getChildren();
728 // If necessary, emit conditionals to check for the appropriate tree
730 for (unsigned i = 0, e = Children.size(); i != e; ++i) {
731 TreePatternNode *C = Children[i];
733 // We already calculated the cost for this leaf, add it in now...
734 OS << Indent << " " << LocCostName << " += "
735 << VarPrefix << "_Op" << utostr(i) << "_"
736 << C->getValueRecord()->getName() << "_Cost;\n";
738 // If it's not a leaf, we have to check to make sure that the current
739 // node has the appropriate structure, then recurse into it...
740 OS << Indent << " if (" << VarPrefix << "_Op" << i
741 << "->getNodeType() == ISD::" << getNodeName(C->getOperator())
743 std::vector<std::pair<Pattern*, TreePatternNode*> > SubPatterns;
744 for (unsigned n = 0, e = Group.size(); n != e; ++n)
745 SubPatterns.push_back(std::make_pair(Group[n].first,
746 Group[n].second->getChild(i)));
747 EmitMatchCosters(OS, SubPatterns, VarPrefix+"_Op"+utostr(i),
749 OS << Indent << " }\n";
753 // If the cost for this match is less than the minimum computed cost so far,
754 // update the minimum cost and selected pattern.
755 OS << Indent << " if (" << LocCostName << " < " << LocCostName << "Min) { "
756 << LocCostName << "Min = " << LocCostName << "; " << VarPrefix
757 << "_PatternMin = " << VarPrefix << "_Pattern; }\n";
759 OS << Indent << "}\n";
763 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
764 Pattern *P = Patterns[i].first;
765 TreePatternNode *PTree = P->getTree();
766 unsigned PatternCost = 1;
768 // Check to see if there are any non-leaf elements in the pattern. If so,
769 // we need to emit a predicate for this match.
770 bool AnyNonLeaf = false;
771 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
772 if (!PTree->getChild(c)->isLeaf()) {
777 if (!AnyNonLeaf) { // No predicate necessary, just output a scope...
778 OS << " {// " << *P << "\n";
780 // We need to emit a predicate to make sure the tree pattern matches, do
783 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
784 if (!PTree->getChild(c)->isLeaf())
785 EmitPatternPredicates(PTree->getChild(c),
786 VarPrefix + "_Op" + utostr(c), OS);
788 OS << ") {\n // " << *P << "\n";
791 OS << " unsigned PatCost = " << PatternCost;
793 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
794 if (PTree->getChild(c)->isLeaf()) {
795 OS << " + " << VarPrefix << "_Op" << c << "_"
796 << PTree->getChild(c)->getValueRecord()->getName() << "_Cost";
798 EmitPatternCosts(PTree->getChild(c), VarPrefix + "_Op" + utostr(c), OS);
801 OS << " if (PatCost < MinCost) { MinCost = PatCost; Pattern = "
802 << P->getRecord()->getName() << "_Pattern; }\n"
807 static void ReduceAllOperands(TreePatternNode *N, const std::string &Name,
808 std::vector<std::pair<TreePatternNode*, std::string> > &Operands,
811 // If this is a leaf, register or nonterminal reference...
812 std::string SlotName = Pattern::getSlotName(N->getValueRecord());
813 OS << " ReducedValue_" << SlotName << " *" << Name << "Val = Reduce_"
814 << SlotName << "(" << Name << ", MBB);\n";
815 Operands.push_back(std::make_pair(N, Name+"Val"));
816 } else if (N->getNumChildren() == 0) {
817 // This is a reference to a leaf tree node, like an immediate or frame
819 if (N->getType() != MVT::isVoid) {
820 std::string SlotName =
821 getNodeName(N->getOperator()) + "_" + getName(N->getType());
822 OS << " ReducedValue_" << SlotName << " *" << Name << "Val = "
823 << Name << "->getValue<ReducedValue_" << SlotName << ">(ISD::"
824 << SlotName << "_Slot);\n";
825 Operands.push_back(std::make_pair(N, Name+"Val"));
828 // Otherwise this is an interior node...
829 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
830 std::string ChildName = Name + "_Op" + utostr(i);
831 OS << " SelectionDAGNode *" << ChildName << " = " << Name
832 << "->getUse(" << i << ");\n";
833 ReduceAllOperands(N->getChild(i), ChildName, Operands, OS);
838 /// PrintExpanderOperand - Print out Arg as part of the instruction emission
839 /// process for the expander pattern P. This argument may be referencing some
840 /// values defined in P, or may just be physical register references or
841 /// something like that. If PrintArg is true, we are printing out arguments to
842 /// the BuildMI call. If it is false, we are printing the result register
844 void InstrSelectorEmitter::PrintExpanderOperand(Init *Arg,
845 const std::string &NameVar,
847 Pattern *P, bool PrintArg,
849 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
850 Record *Arg = DI->getDef();
851 if (Arg->isSubClassOf("Register")) {
852 // This is a physical register reference... make sure that the instruction
853 // requested a register!
854 if (!ArgDecl->isSubClassOf("RegisterClass"))
855 P->error("Argument mismatch for instruction pattern!");
857 // FIXME: This should check to see if the register is in the specified
859 if (PrintArg) OS << ".addReg(";
860 OS << getQualifiedName(Arg);
861 if (PrintArg) OS << ")";
863 } else if (Arg->isSubClassOf("RegisterClass")) {
864 // If this is a symbolic register class reference, we must be using a
866 if (NameVar.empty()) P->error("Did not specify WHICH register to pass!");
867 if (Arg != ArgDecl) P->error("Instruction pattern mismatch!");
869 if (PrintArg) OS << ".addReg(";
871 if (PrintArg) OS << ")";
874 P->error("Unknown operand type '" + Arg->getName() + "' to expander!");
876 P->error("Unknown operand type to expander!");
879 static std::string getArgName(Pattern *P, const std::string &ArgName,
880 const std::vector<std::pair<TreePatternNode*, std::string> > &Operands) {
881 assert(P->getNumArgs() == Operands.size() &&"Argument computation mismatch!");
882 if (ArgName.empty()) return "";
884 for (unsigned i = 0, e = P->getNumArgs(); i != e; ++i)
885 if (P->getArgName(i) == ArgName)
886 return Operands[i].second + "->Val";
887 P->error("Pattern does not define a value named $" + ArgName + "!");
892 void InstrSelectorEmitter::run(std::ostream &OS) {
893 // Type-check all of the node types to ensure we "understand" them.
896 // Read in all of the nonterminals, instructions, and expanders...
898 ReadInstructionPatterns();
899 ReadExpanderPatterns();
901 // Instantiate any unresolved nonterminals with information from the context
902 // that they are used in.
903 InstantiateNonterminals();
905 // Clear InstantiatedNTs, we don't need it anymore...
906 InstantiatedNTs.clear();
908 DEBUG(std::cerr << "Patterns acquired:\n");
909 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
910 E = Patterns.end(); I != E; ++I)
911 if (I->second->isResolved())
912 DEBUG(std::cerr << " " << *I->second << "\n");
914 CalculateComputableValues();
916 EmitSourceFileHeader("Instruction Selector for the " + Target.getName() +
918 OS << "#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n";
920 // Output the slot number enums...
921 OS << "\nenum { // Slot numbers...\n"
922 << " LastBuiltinSlot = ISD::NumBuiltinSlots-1, // Start numbering here\n";
923 for (PatternOrganizer::iterator I = ComputableValues.begin(),
924 E = ComputableValues.end(); I != E; ++I)
925 OS << " " << I->first << "_Slot,\n";
926 OS << " NumSlots\n};\n\n// Reduction value typedefs...\n";
928 // Output the reduction value typedefs...
929 for (PatternOrganizer::iterator I = ComputableValues.begin(),
930 E = ComputableValues.end(); I != E; ++I) {
932 OS << "typedef ReducedValue<unsigned, " << I->first
933 << "_Slot> ReducedValue_" << I->first << ";\n";
936 // Output the pattern enums...
938 << "enum { // Patterns...\n"
939 << " NotComputed = 0,\n"
940 << " NoMatchPattern, \n";
941 for (PatternOrganizer::iterator I = ComputableValues.begin(),
942 E = ComputableValues.end(); I != E; ++I) {
943 OS << " // " << I->first << " patterns...\n";
944 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
945 E = I->second.end(); J != E; ++J)
946 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
947 OS << " " << J->second[i]->getRecord()->getName() << "_Pattern,\n";
951 //===--------------------------------------------------------------------===//
952 // Emit the class definition...
954 OS << "namespace {\n"
955 << " class " << Target.getName() << "ISel {\n"
956 << " SelectionDAG &DAG;\n"
958 << " X86ISel(SelectionDAG &D) : DAG(D) {}\n"
959 << " void generateCode();\n"
961 << " unsigned makeAnotherReg(const TargetRegisterClass *RC) {\n"
962 << " return DAG.getMachineFunction().getSSARegMap()->createVirt"
965 << " // DAG matching methods for classes... all of these methods"
967 << " // of producing a value of the specified class and type, which"
969 << " // added to the DAG node.\n";
971 // Output all of the matching prototypes for slots...
972 for (PatternOrganizer::iterator I = ComputableValues.begin(),
973 E = ComputableValues.end(); I != E; ++I)
974 OS << " unsigned Match_" << I->first << "(SelectionDAGNode *N);\n";
975 OS << "\n // DAG matching methods for DAG nodes...\n";
977 // Output all of the matching prototypes for slot/node pairs
978 for (PatternOrganizer::iterator I = ComputableValues.begin(),
979 E = ComputableValues.end(); I != E; ++I)
980 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
981 E = I->second.end(); J != E; ++J)
982 OS << " unsigned Match_" << I->first << "_" << getNodeName(J->first)
983 << "(SelectionDAGNode *N);\n";
985 // Output all of the dag reduction methods prototypes...
986 OS << "\n // DAG reduction methods...\n";
987 for (PatternOrganizer::iterator I = ComputableValues.begin(),
988 E = ComputableValues.end(); I != E; ++I)
989 OS << " ReducedValue_" << I->first << " *Reduce_" << I->first
990 << "(SelectionDAGNode *N,\n" << std::string(27+2*I->first.size(), ' ')
991 << "MachineBasicBlock *MBB);\n";
994 // Emit the generateCode entry-point...
995 OS << "void X86ISel::generateCode() {\n"
996 << " SelectionDAGNode *Root = DAG.getRoot();\n"
997 << " assert(Root->getValueType() == MVT::isVoid && "
998 "\"Root of DAG produces value??\");\n\n"
999 << " std::cerr << \"\\n\";\n"
1000 << " unsigned Cost = Match_Void_void(Root);\n"
1001 << " if (Cost >= ~0U >> 1) {\n"
1002 << " std::cerr << \"Match failed!\\n\";\n"
1003 << " Root->dump();\n"
1006 << " std::cerr << \"Total DAG Cost: \" << Cost << \"\\n\\n\";\n\n"
1007 << " Reduce_Void_void(Root, 0);\n"
1009 << "//===" << std::string(70, '-') << "===//\n"
1010 << "// Matching methods...\n"
1013 //===--------------------------------------------------------------------===//
1014 // Emit all of the matcher methods...
1016 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1017 E = ComputableValues.end(); I != E; ++I) {
1018 const std::string &SlotName = I->first;
1019 OS << "unsigned " << Target.getName() << "ISel::Match_" << SlotName
1020 << "(SelectionDAGNode *N) {\n"
1021 << " assert(N->getValueType() == MVT::"
1022 << getEnumName((*I->second.begin()).second[0]->getTree()->getType())
1023 << ");\n" << " // If we already have a cost available for " << SlotName
1025 << " if (N->getPatternFor(" << SlotName << "_Slot))\n"
1026 << " return N->getCostFor(" << SlotName << "_Slot);\n\n"
1027 << " unsigned Cost;\n"
1028 << " switch (N->getNodeType()) {\n"
1029 << " default: assert(0 && \"Unhandled node type for " << SlotName
1032 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1033 E = I->second.end(); J != E; ++J)
1034 if (!J->first->isSubClassOf("Nonterminal"))
1035 OS << " case ISD::" << getNodeName(J->first) << ":\tCost = Match_"
1036 << SlotName << "_" << getNodeName(J->first) << "(N); break;\n";
1037 OS << " }\n"; // End of the switch statement
1039 // Emit any patterns which have a nonterminal leaf as the RHS. These may
1040 // match multiple root nodes, so they cannot be handled with the switch...
1041 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1042 E = I->second.end(); J != E; ++J)
1043 if (J->first->isSubClassOf("Nonterminal")) {
1044 OS << " unsigned " << J->first->getName() << "_Cost = Match_"
1045 << getNodeName(J->first) << "(N);\n"
1046 << " if (" << getNodeName(J->first) << "_Cost < Cost) Cost = "
1047 << getNodeName(J->first) << "_Cost;\n";
1050 OS << " return Cost;\n}\n\n";
1052 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1053 E = I->second.end(); J != E; ++J) {
1054 Record *Operator = J->first;
1055 bool isNonterm = Operator->isSubClassOf("Nonterminal");
1057 OS << "unsigned " << Target.getName() << "ISel::Match_";
1058 if (!isNonterm) OS << SlotName << "_";
1059 OS << getNodeName(Operator) << "(SelectionDAGNode *N) {\n"
1060 << " unsigned Pattern = NoMatchPattern;\n"
1061 << " unsigned MinCost = ~0U >> 1;\n";
1063 std::vector<std::pair<Pattern*, TreePatternNode*> > Patterns;
1064 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
1065 Patterns.push_back(std::make_pair(J->second[i],
1066 J->second[i]->getTree()));
1067 EmitMatchCosters(OS, Patterns, "N", 2);
1069 OS << "\n N->setPatternCostFor(" << SlotName
1070 << "_Slot, Pattern, MinCost, NumSlots);\n"
1071 << " return MinCost;\n"
1077 //===--------------------------------------------------------------------===//
1078 // Emit all of the reducer methods...
1080 OS << "\n\n//===" << std::string(70, '-') << "===//\n"
1081 << "// Reducer methods...\n"
1084 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1085 E = ComputableValues.end(); I != E; ++I) {
1086 const std::string &SlotName = I->first;
1087 OS << "ReducedValue_" << SlotName << " *" << Target.getName()
1088 << "ISel::Reduce_" << SlotName
1089 << "(SelectionDAGNode *N, MachineBasicBlock *MBB) {\n"
1090 << " ReducedValue_" << SlotName << " *Val = N->hasValue<ReducedValue_"
1091 << SlotName << ">(" << SlotName << "_Slot);\n"
1092 << " if (Val) return Val;\n"
1093 << " if (N->getBB()) MBB = N->getBB();\n\n"
1094 << " switch (N->getPatternFor(" << SlotName << "_Slot)) {\n";
1096 // Loop over all of the patterns that can produce a value for this slot...
1097 PatternOrganizer::NodesForSlot &NodesForSlot = I->second;
1098 for (PatternOrganizer::NodesForSlot::iterator J = NodesForSlot.begin(),
1099 E = NodesForSlot.end(); J != E; ++J)
1100 for (unsigned i = 0, e = J->second.size(); i != e; ++i) {
1101 Pattern *P = J->second[i];
1102 OS << " case " << P->getRecord()->getName() << "_Pattern: {\n"
1103 << " // " << *P << "\n";
1104 // Loop over the operands, reducing them...
1105 std::vector<std::pair<TreePatternNode*, std::string> > Operands;
1106 ReduceAllOperands(P->getTree(), "N", Operands, OS);
1108 // Now that we have reduced all of our operands, and have the values
1109 // that reduction produces, perform the reduction action for this
1113 // If the pattern produces a register result, generate a new register
1115 if (Record *R = P->getResult()) {
1116 assert(R->isSubClassOf("RegisterClass") &&
1117 "Only handle register class results so far!");
1118 OS << " unsigned NewReg = makeAnotherReg(" << Target.getName()
1119 << "::" << R->getName() << "RegisterClass);\n";
1121 DEBUG(OS << " std::cerr << \"%reg\" << NewReg << \" =\t\";\n");
1123 DEBUG(OS << " std::cerr << \"\t\t\";\n");
1127 // Print out the pattern that matched...
1128 DEBUG(OS << " std::cerr << \" " << P->getRecord()->getName() <<'"');
1129 DEBUG(for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1130 if (Operands[i].first->isLeaf()) {
1131 Record *RV = Operands[i].first->getValueRecord();
1132 assert(RV->isSubClassOf("RegisterClass") &&
1133 "Only handles registers here so far!");
1134 OS << " << \" %reg\" << " << Operands[i].second
1137 OS << " << ' ' << " << Operands[i].second
1140 DEBUG(OS << " << \"\\n\";\n");
1142 // Generate the reduction code appropriate to the particular type of
1143 // pattern that this is...
1144 switch (P->getPatternType()) {
1145 case Pattern::Instruction:
1146 // Instruction patterns just emit a single MachineInstr, using BuildMI
1147 OS << " BuildMI(MBB, " << Target.getName() << "::"
1148 << P->getRecord()->getName() << ", " << Operands.size();
1149 if (P->getResult()) OS << ", NewReg";
1152 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1153 if (Operands[i].first->isLeaf()) {
1154 Record *RV = Operands[i].first->getValueRecord();
1155 assert(RV->isSubClassOf("RegisterClass") &&
1156 "Only handles registers here so far!");
1157 OS << ".addReg(" << Operands[i].second << "->Val)";
1159 OS << ".addZImm(" << Operands[i].second << "->Val)";
1163 case Pattern::Expander: {
1164 // Expander patterns emit one machine instr for each instruction in
1165 // the list of instructions expanded to.
1166 ListInit *Insts = P->getRecord()->getValueAsListInit("Result");
1167 for (unsigned IN = 0, e = Insts->getSize(); IN != e; ++IN) {
1168 DagInit *DIInst = dynamic_cast<DagInit*>(Insts->getElement(IN));
1169 if (!DIInst) P->error("Result list must contain instructions!");
1170 Pattern *InstPat = getPattern(DIInst->getNodeType());
1171 if (!InstPat || InstPat->getPatternType() != Pattern::Instruction)
1172 P->error("Instruction list must contain Instruction patterns!");
1174 bool hasResult = InstPat->getResult() != 0;
1175 if (InstPat->getNumArgs() != DIInst->getNumArgs()-hasResult) {
1176 P->error("Incorrect number of arguments specified for inst '" +
1177 InstPat->getRecord()->getName() + "' in result list!");
1180 // Start emission of the instruction...
1181 OS << " BuildMI(MBB, " << Target.getName() << "::"
1182 << InstPat->getRecord()->getName() << ", "
1183 << DIInst->getNumArgs()-hasResult;
1184 // Emit register result if necessary..
1185 if (Record *R = InstPat->getResult()) {
1186 std::string ArgNameVal =
1187 getArgName(P, DIInst->getArgName(0), Operands);
1188 PrintExpanderOperand(DIInst->getArg(0), ArgNameVal,
1189 R, P, false, OS << ", ");
1193 for (unsigned i = hasResult, e = DIInst->getNumArgs(); i != e; ++i){
1194 std::string ArgNameVal =
1195 getArgName(P, DIInst->getArgName(i), Operands);
1197 PrintExpanderOperand(DIInst->getArg(i), ArgNameVal,
1198 InstPat->getArgRec(i-hasResult), P, true, OS);
1206 assert(0 && "Reduction of this type of pattern not implemented!");
1209 OS << " Val = new ReducedValue_" << SlotName << "(" << Result<<");\n"
1215 OS << " default: assert(0 && \"Unknown " << SlotName << " pattern!\");\n"
1216 << " }\n\n N->addValue(Val); // Do not ever recalculate this\n"
1217 << " return Val;\n}\n\n";