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 throw "Unknown DagNodeValType '" + Name + "'!";
26 //===----------------------------------------------------------------------===//
27 // TreePatternNode implementation
30 /// getValueRecord - Returns the value of this tree node as a record. For now
31 /// we only allow DefInit's as our leaf values, so this is used.
32 Record *TreePatternNode::getValueRecord() const {
33 DefInit *DI = dynamic_cast<DefInit*>(getValue());
34 assert(DI && "Instruction Selector does not yet support non-def leaves!");
39 // updateNodeType - Set the node type of N to VT if VT contains information. If
40 // N already contains a conflicting type, then throw an exception
42 bool TreePatternNode::updateNodeType(MVT::ValueType VT,
43 const std::string &RecName) {
44 if (VT == MVT::Other || getType() == VT) return false;
45 if (getType() == MVT::Other) {
50 throw "Type inferfence contradiction found for pattern " + RecName;
53 /// InstantiateNonterminals - If this pattern refers to any nonterminals which
54 /// are not themselves completely resolved, clone the nonterminal and resolve it
55 /// with the using context we provide.
57 void TreePatternNode::InstantiateNonterminals(InstrSelectorEmitter &ISE) {
59 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
60 getChild(i)->InstantiateNonterminals(ISE);
64 // If this is a leaf, it might be a reference to a nonterminal! Check now.
65 Record *R = getValueRecord();
66 if (R->isSubClassOf("Nonterminal")) {
67 Pattern *NT = ISE.getPattern(R);
68 if (!NT->isResolved()) {
69 // We found an unresolved nonterminal reference. Ask the ISE to clone
70 // it for us, then update our reference to the fresh, new, resolved,
73 Value = new DefInit(ISE.InstantiateNonterminal(NT, getType()));
79 /// clone - Make a copy of this tree and all of its children.
81 TreePatternNode *TreePatternNode::clone() const {
84 New = new TreePatternNode(Value);
86 std::vector<std::pair<TreePatternNode*, std::string> > CChildren;
87 CChildren.reserve(Children.size());
88 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
89 CChildren.push_back(std::make_pair(getChild(i)->clone(),getChildName(i)));
90 New = new TreePatternNode(Operator, CChildren);
96 std::ostream &operator<<(std::ostream &OS, const TreePatternNode &N) {
98 return OS << N.getType() << ":" << *N.getValue();
99 OS << "(" << N.getType() << ":";
100 OS << N.getOperator()->getName();
102 if (N.getNumChildren() != 0) {
103 OS << " " << *N.getChild(0);
104 for (unsigned i = 1, e = N.getNumChildren(); i != e; ++i)
105 OS << ", " << *N.getChild(i);
110 void TreePatternNode::dump() const { std::cerr << *this; }
112 //===----------------------------------------------------------------------===//
113 // Pattern implementation
116 // Parse the specified DagInit into a TreePattern which we can use.
118 Pattern::Pattern(PatternType pty, DagInit *RawPat, Record *TheRec,
119 InstrSelectorEmitter &ise)
120 : PTy(pty), ResultNode(0), TheRecord(TheRec), ISE(ise) {
122 // First, parse the pattern...
123 Tree = ParseTreePattern(RawPat);
125 // Run the type-inference engine...
128 if (PTy == Instruction || PTy == Expander) {
129 // Check to make sure there is not any unset types in the tree pattern...
131 std::cerr << "In pattern: " << *Tree << "\n";
132 error("Could not infer all types!");
135 // Check to see if we have a top-level (set) of a register.
136 if (Tree->getOperator()->getName() == "set") {
137 assert(Tree->getNumChildren() == 2 && "Set with != 2 arguments?");
138 if (!Tree->getChild(0)->isLeaf())
139 error("Arg #0 of set should be a register or register class!");
140 ResultNode = Tree->getChild(0);
141 ResultName = Tree->getChildName(0);
142 Tree = Tree->getChild(1);
146 calculateArgs(Tree, "");
149 void Pattern::error(const std::string &Msg) const {
150 std::string M = "In ";
152 case Nonterminal: M += "nonterminal "; break;
153 case Instruction: M += "instruction "; break;
154 case Expander : M += "expander "; break;
156 throw M + TheRecord->getName() + ": " + Msg;
159 /// calculateArgs - Compute the list of all of the arguments to this pattern,
160 /// which are the non-void leaf nodes in this pattern.
162 void Pattern::calculateArgs(TreePatternNode *N, const std::string &Name) {
163 if (N->isLeaf() || N->getNumChildren() == 0) {
164 if (N->getType() != MVT::isVoid)
165 Args.push_back(std::make_pair(N, Name));
167 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
168 calculateArgs(N->getChild(i), N->getChildName(i));
172 /// getIntrinsicType - Check to see if the specified record has an intrinsic
173 /// type which should be applied to it. This infer the type of register
174 /// references from the register file information, for example.
176 MVT::ValueType Pattern::getIntrinsicType(Record *R) const {
177 // Check to see if this is a register or a register class...
178 if (R->isSubClassOf("RegisterClass"))
179 return getValueType(R->getValueAsDef("RegType"));
180 else if (R->isSubClassOf("Nonterminal"))
181 return ISE.ReadNonterminal(R)->getTree()->getType();
182 else if (R->isSubClassOf("Register")) {
183 std::cerr << "WARNING: Explicit registers not handled yet!\n";
187 error("Unknown value used: " + R->getName());
191 TreePatternNode *Pattern::ParseTreePattern(DagInit *Dag) {
192 Record *Operator = Dag->getNodeType();
194 if (Operator->isSubClassOf("ValueType")) {
195 // If the operator is a ValueType, then this must be "type cast" of a leaf
197 if (Dag->getNumArgs() != 1)
198 error("Type cast only valid for a leaf node!");
200 Init *Arg = Dag->getArg(0);
201 TreePatternNode *New;
202 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
203 New = new TreePatternNode(DI);
204 // If it's a regclass or something else known, set the type.
205 New->setType(getIntrinsicType(DI->getDef()));
208 error("Unknown leaf value for tree pattern!");
211 // Apply the type cast...
212 New->updateNodeType(getValueType(Operator), TheRecord->getName());
216 if (!ISE.getNodeTypes().count(Operator))
217 error("Unrecognized node '" + Operator->getName() + "'!");
219 std::vector<std::pair<TreePatternNode*, std::string> > Children;
221 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
222 Init *Arg = Dag->getArg(i);
223 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
224 Children.push_back(std::make_pair(ParseTreePattern(DI),
225 Dag->getArgName(i)));
226 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
227 Record *R = DefI->getDef();
228 // Direct reference to a leaf DagNode? Turn it into a DagNode if its own.
229 if (R->isSubClassOf("DagNode")) {
230 Dag->setArg(i, new DagInit(R,
231 std::vector<std::pair<Init*, std::string> >()));
232 --i; // Revisit this node...
234 Children.push_back(std::make_pair(new TreePatternNode(DefI),
235 Dag->getArgName(i)));
236 // If it's a regclass or something else known, set the type.
237 Children.back().first->setType(getIntrinsicType(R));
241 error("Unknown leaf value for tree pattern!");
245 return new TreePatternNode(Operator, Children);
248 void Pattern::InferAllTypes() {
249 bool MadeChange, AnyUnset;
252 AnyUnset = InferTypes(Tree, MadeChange);
253 } while ((AnyUnset || MadeChange) && !(AnyUnset && !MadeChange));
254 Resolved = !AnyUnset;
258 // InferTypes - Perform type inference on the tree, returning true if there
259 // are any remaining untyped nodes and setting MadeChange if any changes were
261 bool Pattern::InferTypes(TreePatternNode *N, bool &MadeChange) {
262 if (N->isLeaf()) return N->getType() == MVT::Other;
264 bool AnyUnset = false;
265 Record *Operator = N->getOperator();
266 const NodeType &NT = ISE.getNodeType(Operator);
268 // Check to see if we can infer anything about the argument types from the
270 if (N->getNumChildren() != NT.ArgTypes.size())
271 error("Incorrect number of children for " + Operator->getName() + " node!");
273 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
274 TreePatternNode *Child = N->getChild(i);
275 AnyUnset |= InferTypes(Child, MadeChange);
277 switch (NT.ArgTypes[i]) {
279 MadeChange |= Child->updateNodeType(N->getChild(0)->getType(),
280 TheRecord->getName());
283 MadeChange |= Child->updateNodeType(N->getChild(1)->getType(),
284 TheRecord->getName());
287 if (Child->getType() == MVT::isVoid)
288 error("Inferred a void node in an illegal place!");
291 MadeChange |= Child->updateNodeType(ISE.getTarget().getPointerType(),
292 TheRecord->getName());
294 default: assert(0 && "Invalid argument ArgType!");
298 // See if we can infer anything about the return type now...
299 switch (NT.ResultType) {
301 MadeChange |= N->updateNodeType(MVT::isVoid, TheRecord->getName());
304 MadeChange |= N->updateNodeType(N->getChild(0)->getType(),
305 TheRecord->getName());
308 MadeChange |= N->updateNodeType(N->getChild(1)->getType(),
309 TheRecord->getName());
312 MadeChange |= N->updateNodeType(ISE.getTarget().getPointerType(),
313 TheRecord->getName());
316 if (N->getType() == MVT::isVoid)
317 error("Inferred a void node in an illegal place!");
320 assert(0 && "Unhandled type constraint!");
324 return AnyUnset | N->getType() == MVT::Other;
327 /// clone - This method is used to make an exact copy of the current pattern,
328 /// then change the "TheRecord" instance variable to the specified record.
330 Pattern *Pattern::clone(Record *R) const {
331 assert(PTy == Nonterminal && "Can only clone nonterminals");
332 return new Pattern(Tree->clone(), R, Resolved, ISE);
337 std::ostream &operator<<(std::ostream &OS, const Pattern &P) {
338 switch (P.getPatternType()) {
339 case Pattern::Nonterminal: OS << "Nonterminal pattern "; break;
340 case Pattern::Instruction: OS << "Instruction pattern "; break;
341 case Pattern::Expander: OS << "Expander pattern "; break;
344 OS << P.getRecord()->getName() << ":\t";
346 if (Record *Result = P.getResult())
347 OS << Result->getName() << " = ";
351 OS << " [not completely resolved]";
355 void Pattern::dump() const { std::cerr << *this; }
359 /// getSlotName - If this is a leaf node, return the slot name that the operand
361 std::string Pattern::getSlotName() const {
362 if (getPatternType() == Pattern::Nonterminal) {
363 // Just use the nonterminal name, which will already include the type if
364 // it has been cloned.
365 return getRecord()->getName();
367 std::string SlotName;
369 SlotName = getResult()->getName()+"_";
372 return SlotName + getName(getTree()->getType());
376 /// getSlotName - If this is a leaf node, return the slot name that the
377 /// operand will update.
378 std::string Pattern::getSlotName(Record *R) {
379 if (R->isSubClassOf("Nonterminal")) {
380 // Just use the nonterminal name, which will already include the type if
381 // it has been cloned.
383 } else if (R->isSubClassOf("RegisterClass")) {
384 MVT::ValueType Ty = getValueType(R->getValueAsDef("RegType"));
385 return R->getName() + "_" + getName(Ty);
387 assert(0 && "Don't know how to get a slot name for this!");
391 //===----------------------------------------------------------------------===//
392 // PatternOrganizer implementation
395 /// addPattern - Add the specified pattern to the appropriate location in the
397 void PatternOrganizer::addPattern(Pattern *P) {
398 NodesForSlot &Nodes = AllPatterns[P->getSlotName()];
399 if (!P->getTree()->isLeaf())
400 Nodes[P->getTree()->getOperator()].push_back(P);
402 // Right now we only support DefInit's with node types...
403 Nodes[P->getTree()->getValueRecord()].push_back(P);
409 //===----------------------------------------------------------------------===//
410 // InstrSelectorEmitter implementation
413 /// ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
414 /// turning them into the more accessible NodeTypes data structure.
416 void InstrSelectorEmitter::ReadNodeTypes() {
417 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("DagNode");
418 DEBUG(std::cerr << "Getting node types: ");
419 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
420 Record *Node = Nodes[i];
422 // Translate the return type...
423 NodeType::ArgResultTypes RetTy =
424 NodeType::Translate(Node->getValueAsDef("RetType"));
426 // Translate the arguments...
427 ListInit *Args = Node->getValueAsListInit("ArgTypes");
428 std::vector<NodeType::ArgResultTypes> ArgTypes;
430 for (unsigned a = 0, e = Args->getSize(); a != e; ++a) {
431 if (DefInit *DI = dynamic_cast<DefInit*>(Args->getElement(a)))
432 ArgTypes.push_back(NodeType::Translate(DI->getDef()));
434 throw "In node " + Node->getName() + ", argument is not a Def!";
436 if (a == 0 && ArgTypes.back() == NodeType::Arg0)
437 throw "In node " + Node->getName() + ", arg 0 cannot have type 'arg0'!";
438 if (a == 1 && ArgTypes.back() == NodeType::Arg1)
439 throw "In node " + Node->getName() + ", arg 1 cannot have type 'arg1'!";
440 if (ArgTypes.back() == NodeType::Void)
441 throw "In node " + Node->getName() + ", args cannot be void type!";
443 if ((RetTy == NodeType::Arg0 && Args->getSize() == 0) ||
444 (RetTy == NodeType::Arg1 && Args->getSize() < 2))
445 throw "In node " + Node->getName() +
446 ", invalid return type for node with this many operands!";
448 // Add the node type mapping now...
449 NodeTypes[Node] = NodeType(RetTy, ArgTypes);
450 DEBUG(std::cerr << Node->getName() << ", ");
452 DEBUG(std::cerr << "DONE!\n");
455 Pattern *InstrSelectorEmitter::ReadNonterminal(Record *R) {
456 Pattern *&P = Patterns[R];
457 if (P) return P; // Don't reread it!
459 DagInit *DI = R->getValueAsDag("Pattern");
460 P = new Pattern(Pattern::Nonterminal, DI, R, *this);
461 DEBUG(std::cerr << "Parsed " << *P << "\n");
466 // ReadNonTerminals - Read in all nonterminals and incorporate them into our
468 void InstrSelectorEmitter::ReadNonterminals() {
469 std::vector<Record*> NTs = Records.getAllDerivedDefinitions("Nonterminal");
470 for (unsigned i = 0, e = NTs.size(); i != e; ++i)
471 ReadNonterminal(NTs[i]);
475 /// ReadInstructionPatterns - Read in all subclasses of Instruction, and process
476 /// those with a useful Pattern field.
478 void InstrSelectorEmitter::ReadInstructionPatterns() {
479 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
480 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
481 Record *Inst = Insts[i];
482 if (DagInit *DI = dynamic_cast<DagInit*>(Inst->getValueInit("Pattern"))) {
483 Patterns[Inst] = new Pattern(Pattern::Instruction, DI, Inst, *this);
484 DEBUG(std::cerr << "Parsed " << *Patterns[Inst] << "\n");
489 /// ReadExpanderPatterns - Read in all expander patterns...
491 void InstrSelectorEmitter::ReadExpanderPatterns() {
492 std::vector<Record*> Expanders = Records.getAllDerivedDefinitions("Expander");
493 for (unsigned i = 0, e = Expanders.size(); i != e; ++i) {
494 Record *Expander = Expanders[i];
495 DagInit *DI = Expander->getValueAsDag("Pattern");
496 Patterns[Expander] = new Pattern(Pattern::Expander, DI, Expander, *this);
497 DEBUG(std::cerr << "Parsed " << *Patterns[Expander] << "\n");
502 // InstantiateNonterminals - Instantiate any unresolved nonterminals with
503 // information from the context that they are used in.
505 void InstrSelectorEmitter::InstantiateNonterminals() {
506 DEBUG(std::cerr << "Instantiating nonterminals:\n");
507 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
508 E = Patterns.end(); I != E; ++I)
509 if (I->second->isResolved())
510 I->second->InstantiateNonterminals();
513 /// InstantiateNonterminal - This method takes the nonterminal specified by
514 /// NT, which should not be completely resolved, clones it, applies ResultTy
515 /// to its root, then runs the type inference stuff on it. This should
516 /// produce a newly resolved nonterminal, which we make a record for and
517 /// return. To be extra fancy and efficient, this only makes one clone for
518 /// each type it is instantiated with.
519 Record *InstrSelectorEmitter::InstantiateNonterminal(Pattern *NT,
520 MVT::ValueType ResultTy) {
521 assert(!NT->isResolved() && "Nonterminal is already resolved!");
523 // Check to see if we have already instantiated this pair...
524 Record* &Slot = InstantiatedNTs[std::make_pair(NT, ResultTy)];
525 if (Slot) return Slot;
527 Record *New = new Record(NT->getRecord()->getName()+"_"+getName(ResultTy));
529 // Copy over the superclasses...
530 const std::vector<Record*> &SCs = NT->getRecord()->getSuperClasses();
531 for (unsigned i = 0, e = SCs.size(); i != e; ++i)
532 New->addSuperClass(SCs[i]);
534 DEBUG(std::cerr << " Nonterminal '" << NT->getRecord()->getName()
535 << "' for type '" << getName(ResultTy) << "', producing '"
536 << New->getName() << "'\n");
538 // Copy the pattern...
539 Pattern *NewPat = NT->clone(New);
541 // Apply the type to the root...
542 NewPat->getTree()->updateNodeType(ResultTy, New->getName());
545 NewPat->InferAllTypes();
547 // Make sure everything is good to go now...
548 if (!NewPat->isResolved())
549 NewPat->error("Instantiating nonterminal did not resolve all types!");
551 // Add the pattern to the patterns map, add the record to the RecordKeeper,
552 // return the new record.
553 Patterns[New] = NewPat;
558 // CalculateComputableValues - Fill in the ComputableValues map through
559 // analysis of the patterns we are playing with.
560 void InstrSelectorEmitter::CalculateComputableValues() {
561 // Loop over all of the patterns, adding them to the ComputableValues map
562 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
563 E = Patterns.end(); I != E; ++I)
564 if (I->second->isResolved()) {
565 // We don't want to add patterns like R32 = R32. This is a hack working
566 // around a special case of a general problem, but for now we explicitly
567 // forbid these patterns. They can never match anyway.
568 Pattern *P = I->second;
569 if (!P->getResult() || !P->getTree()->isLeaf() ||
570 P->getResult() != P->getTree()->getValueRecord())
571 ComputableValues.addPattern(P);
576 // MoveIdenticalPatterns - Given a tree pattern 'P', move all of the tree
577 // patterns which have the same top-level structure as P from the 'From' list to
579 static void MoveIdenticalPatterns(TreePatternNode *P,
580 std::vector<std::pair<Pattern*, TreePatternNode*> > &From,
581 std::vector<std::pair<Pattern*, TreePatternNode*> > &To) {
582 assert(!P->isLeaf() && "All leaves are identical!");
584 const std::vector<TreePatternNode*> &PChildren = P->getChildren();
585 for (unsigned i = 0; i != From.size(); ++i) {
586 TreePatternNode *N = From[i].second;
587 assert(P->getOperator() == N->getOperator() &&"Differing operators?");
588 assert(PChildren.size() == N->getChildren().size() &&
589 "Nodes with different arity??");
590 bool isDifferent = false;
591 for (unsigned c = 0, e = PChildren.size(); c != e; ++c) {
592 TreePatternNode *PC = PChildren[c];
593 TreePatternNode *NC = N->getChild(c);
594 if (PC->isLeaf() != NC->isLeaf()) {
600 if (PC->getOperator() != NC->getOperator()) {
604 } else { // It's a leaf!
605 if (PC->getValueRecord() != NC->getValueRecord()) {
611 // If it's the same as the reference one, move it over now...
613 To.push_back(std::make_pair(From[i].first, N));
614 From.erase(From.begin()+i);
615 --i; // Don't skip an entry...
621 static std::string getNodeName(Record *R) {
622 RecordVal *RV = R->getValue("EnumName");
624 if (Init *I = RV->getValue())
625 if (StringInit *SI = dynamic_cast<StringInit*>(I))
626 return SI->getValue();
631 static void EmitPatternPredicates(TreePatternNode *Tree,
632 const std::string &VarName, std::ostream &OS){
633 OS << " && " << VarName << "->getNodeType() == ISD::"
634 << getNodeName(Tree->getOperator());
636 for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
637 if (!Tree->getChild(c)->isLeaf())
638 EmitPatternPredicates(Tree->getChild(c),
639 VarName + "->getUse(" + utostr(c)+")", OS);
642 static void EmitPatternCosts(TreePatternNode *Tree, const std::string &VarName,
644 for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
645 if (Tree->getChild(c)->isLeaf()) {
647 << Pattern::getSlotName(Tree->getChild(c)->getValueRecord()) << "("
648 << VarName << "->getUse(" << c << "))";
650 EmitPatternCosts(Tree->getChild(c),
651 VarName + "->getUse(" + utostr(c) + ")", OS);
656 // EmitMatchCosters - Given a list of patterns, which all have the same root
657 // pattern operator, emit an efficient decision tree to decide which one to
658 // pick. This is structured this way to avoid reevaluations of non-obvious
660 void InstrSelectorEmitter::EmitMatchCosters(std::ostream &OS,
661 const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
662 const std::string &VarPrefix,
663 unsigned IndentAmt) {
664 assert(!Patterns.empty() && "No patterns to emit matchers for!");
665 std::string Indent(IndentAmt, ' ');
667 // Load all of the operands of the root node into scalars for fast access
668 const NodeType &ONT = getNodeType(Patterns[0].second->getOperator());
669 for (unsigned i = 0, e = ONT.ArgTypes.size(); i != e; ++i)
670 OS << Indent << "SelectionDAGNode *" << VarPrefix << "_Op" << i
671 << " = N->getUse(" << i << ");\n";
673 // Compute the costs of computing the various nonterminals/registers, which
674 // are directly used at this level.
675 OS << "\n" << Indent << "// Operand matching costs...\n";
676 std::set<std::string> ComputedValues; // Avoid duplicate computations...
677 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
678 TreePatternNode *NParent = Patterns[i].second;
679 for (unsigned c = 0, e = NParent->getNumChildren(); c != e; ++c) {
680 TreePatternNode *N = NParent->getChild(c);
682 Record *VR = N->getValueRecord();
683 const std::string &LeafName = VR->getName();
684 std::string OpName = VarPrefix + "_Op" + utostr(c);
685 std::string ValName = OpName + "_" + LeafName + "_Cost";
686 if (!ComputedValues.count(ValName)) {
687 OS << Indent << "unsigned " << ValName << " = Match_"
688 << Pattern::getSlotName(VR) << "(" << OpName << ");\n";
689 ComputedValues.insert(ValName);
697 std::string LocCostName = VarPrefix + "_Cost";
698 OS << Indent << "unsigned " << LocCostName << "Min = ~0U >> 1;\n"
699 << Indent << "unsigned " << VarPrefix << "_PatternMin = NoMatchPattern;\n";
702 // Separate out all of the patterns into groups based on what their top-level
703 // signature looks like...
704 std::vector<std::pair<Pattern*, TreePatternNode*> > PatternsLeft(Patterns);
705 while (!PatternsLeft.empty()) {
706 // Process all of the patterns that have the same signature as the last
708 std::vector<std::pair<Pattern*, TreePatternNode*> > Group;
709 MoveIdenticalPatterns(PatternsLeft.back().second, PatternsLeft, Group);
710 assert(!Group.empty() && "Didn't at least pick the source pattern?");
713 OS << "PROCESSING GROUP:\n";
714 for (unsigned i = 0, e = Group.size(); i != e; ++i)
715 OS << " " << *Group[i].first << "\n";
719 OS << Indent << "{ // ";
721 if (Group.size() != 1) {
722 OS << Group.size() << " size group...\n";
723 OS << Indent << " unsigned " << VarPrefix << "_Pattern = NoMatch;\n";
725 OS << *Group[0].first << "\n";
726 OS << Indent << " unsigned " << VarPrefix << "_Pattern = "
727 << Group[0].first->getRecord()->getName() << "_Pattern;\n";
730 OS << Indent << " unsigned " << LocCostName << " = ";
731 if (Group.size() == 1)
732 OS << "1;\n"; // Add inst cost if at individual rec
736 // Loop over all of the operands, adding in their costs...
737 TreePatternNode *N = Group[0].second;
738 const std::vector<TreePatternNode*> &Children = N->getChildren();
740 // If necessary, emit conditionals to check for the appropriate tree
742 for (unsigned i = 0, e = Children.size(); i != e; ++i) {
743 TreePatternNode *C = Children[i];
745 // We already calculated the cost for this leaf, add it in now...
746 OS << Indent << " " << LocCostName << " += "
747 << VarPrefix << "_Op" << utostr(i) << "_"
748 << C->getValueRecord()->getName() << "_Cost;\n";
750 // If it's not a leaf, we have to check to make sure that the current
751 // node has the appropriate structure, then recurse into it...
752 OS << Indent << " if (" << VarPrefix << "_Op" << i
753 << "->getNodeType() == ISD::" << getNodeName(C->getOperator())
755 std::vector<std::pair<Pattern*, TreePatternNode*> > SubPatterns;
756 for (unsigned n = 0, e = Group.size(); n != e; ++n)
757 SubPatterns.push_back(std::make_pair(Group[n].first,
758 Group[n].second->getChild(i)));
759 EmitMatchCosters(OS, SubPatterns, VarPrefix+"_Op"+utostr(i),
761 OS << Indent << " }\n";
765 // If the cost for this match is less than the minimum computed cost so far,
766 // update the minimum cost and selected pattern.
767 OS << Indent << " if (" << LocCostName << " < " << LocCostName << "Min) { "
768 << LocCostName << "Min = " << LocCostName << "; " << VarPrefix
769 << "_PatternMin = " << VarPrefix << "_Pattern; }\n";
771 OS << Indent << "}\n";
775 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
776 Pattern *P = Patterns[i].first;
777 TreePatternNode *PTree = P->getTree();
778 unsigned PatternCost = 1;
780 // Check to see if there are any non-leaf elements in the pattern. If so,
781 // we need to emit a predicate for this match.
782 bool AnyNonLeaf = false;
783 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
784 if (!PTree->getChild(c)->isLeaf()) {
789 if (!AnyNonLeaf) { // No predicate necessary, just output a scope...
790 OS << " {// " << *P << "\n";
792 // We need to emit a predicate to make sure the tree pattern matches, do
795 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
796 if (!PTree->getChild(c)->isLeaf())
797 EmitPatternPredicates(PTree->getChild(c),
798 VarPrefix + "_Op" + utostr(c), OS);
800 OS << ") {\n // " << *P << "\n";
803 OS << " unsigned PatCost = " << PatternCost;
805 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
806 if (PTree->getChild(c)->isLeaf()) {
807 OS << " + " << VarPrefix << "_Op" << c << "_"
808 << PTree->getChild(c)->getValueRecord()->getName() << "_Cost";
810 EmitPatternCosts(PTree->getChild(c), VarPrefix + "_Op" + utostr(c), OS);
813 OS << " if (PatCost < MinCost) { MinCost = PatCost; Pattern = "
814 << P->getRecord()->getName() << "_Pattern; }\n"
819 static void ReduceAllOperands(TreePatternNode *N, const std::string &Name,
820 std::vector<std::pair<TreePatternNode*, std::string> > &Operands,
823 // If this is a leaf, register or nonterminal reference...
824 std::string SlotName = Pattern::getSlotName(N->getValueRecord());
825 OS << " ReducedValue_" << SlotName << " *" << Name << "Val = Reduce_"
826 << SlotName << "(" << Name << ", MBB);\n";
827 Operands.push_back(std::make_pair(N, Name+"Val"));
828 } else if (N->getNumChildren() == 0) {
829 // This is a reference to a leaf tree node, like an immediate or frame
831 if (N->getType() != MVT::isVoid) {
832 std::string SlotName =
833 getNodeName(N->getOperator()) + "_" + getName(N->getType());
834 OS << " ReducedValue_" << SlotName << " *" << Name << "Val = "
835 << Name << "->getValue<ReducedValue_" << SlotName << ">(ISD::"
836 << SlotName << "_Slot);\n";
837 Operands.push_back(std::make_pair(N, Name+"Val"));
840 // Otherwise this is an interior node...
841 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
842 std::string ChildName = Name + "_Op" + utostr(i);
843 OS << " SelectionDAGNode *" << ChildName << " = " << Name
844 << "->getUse(" << i << ");\n";
845 ReduceAllOperands(N->getChild(i), ChildName, Operands, OS);
850 /// PrintExpanderOperand - Print out Arg as part of the instruction emission
851 /// process for the expander pattern P. This argument may be referencing some
852 /// values defined in P, or may just be physical register references or
853 /// something like that. If PrintArg is true, we are printing out arguments to
854 /// the BuildMI call. If it is false, we are printing the result register
856 void InstrSelectorEmitter::PrintExpanderOperand(Init *Arg,
857 const std::string &NameVar,
858 TreePatternNode *ArgDeclNode,
859 Pattern *P, bool PrintArg,
861 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
862 Record *Arg = DI->getDef();
863 if (!ArgDeclNode->isLeaf())
864 P->error("Expected leaf node as argument!");
865 Record *ArgDecl = ArgDeclNode->getValueRecord();
866 if (Arg->isSubClassOf("Register")) {
867 // This is a physical register reference... make sure that the instruction
868 // requested a register!
869 if (!ArgDecl->isSubClassOf("RegisterClass"))
870 P->error("Argument mismatch for instruction pattern!");
872 // FIXME: This should check to see if the register is in the specified
874 if (PrintArg) OS << ".addReg(";
875 OS << getQualifiedName(Arg);
876 if (PrintArg) OS << ")";
878 } else if (Arg->isSubClassOf("RegisterClass")) {
879 // If this is a symbolic register class reference, we must be using a
881 if (NameVar.empty()) P->error("Did not specify WHICH register to pass!");
882 if (Arg != ArgDecl) P->error("Instruction pattern mismatch!");
884 if (PrintArg) OS << ".addReg(";
886 if (PrintArg) OS << ")";
888 } else if (Arg->getName() == "frameidx") {
889 if (!PrintArg) P->error("Cannot define a new frameidx value!");
890 OS << ".addFrameIndex(" << NameVar << ")";
893 P->error("Unknown operand type '" + Arg->getName() + "' to expander!");
894 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
895 if (!NameVar.empty())
896 P->error("Illegal to specify a name for a constant initializer arg!");
898 // Hack this check to allow R32 values with 0 as the initializer for memory
899 // references... FIXME!
900 if (ArgDeclNode->isLeaf() && II->getValue() == 0 &&
901 ArgDeclNode->getValueRecord()->getName() == "R32") {
904 if (ArgDeclNode->isLeaf() || ArgDeclNode->getOperator()->getName()!="imm")
905 P->error("Illegal immediate int value '" + itostr(II->getValue()) +
907 OS << ".addZImm(" << II->getValue() << ")";
911 P->error("Unknown operand type to expander!");
914 static std::string getArgName(Pattern *P, const std::string &ArgName,
915 const std::vector<std::pair<TreePatternNode*, std::string> > &Operands) {
916 assert(P->getNumArgs() == Operands.size() &&"Argument computation mismatch!");
917 if (ArgName.empty()) return "";
919 for (unsigned i = 0, e = P->getNumArgs(); i != e; ++i)
920 if (P->getArgName(i) == ArgName)
921 return Operands[i].second + "->Val";
923 if (ArgName == P->getResultName())
925 P->error("Pattern does not define a value named $" + ArgName + "!");
930 void InstrSelectorEmitter::run(std::ostream &OS) {
931 // Type-check all of the node types to ensure we "understand" them.
934 // Read in all of the nonterminals, instructions, and expanders...
936 ReadInstructionPatterns();
937 ReadExpanderPatterns();
939 // Instantiate any unresolved nonterminals with information from the context
940 // that they are used in.
941 InstantiateNonterminals();
943 // Clear InstantiatedNTs, we don't need it anymore...
944 InstantiatedNTs.clear();
946 DEBUG(std::cerr << "Patterns acquired:\n");
947 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
948 E = Patterns.end(); I != E; ++I)
949 if (I->second->isResolved())
950 DEBUG(std::cerr << " " << *I->second << "\n");
952 CalculateComputableValues();
954 EmitSourceFileHeader("Instruction Selector for the " + Target.getName() +
956 OS << "#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n";
958 // Output the slot number enums...
959 OS << "\nenum { // Slot numbers...\n"
960 << " LastBuiltinSlot = ISD::NumBuiltinSlots-1, // Start numbering here\n";
961 for (PatternOrganizer::iterator I = ComputableValues.begin(),
962 E = ComputableValues.end(); I != E; ++I)
963 OS << " " << I->first << "_Slot,\n";
964 OS << " NumSlots\n};\n\n// Reduction value typedefs...\n";
966 // Output the reduction value typedefs...
967 for (PatternOrganizer::iterator I = ComputableValues.begin(),
968 E = ComputableValues.end(); I != E; ++I) {
970 OS << "typedef ReducedValue<unsigned, " << I->first
971 << "_Slot> ReducedValue_" << I->first << ";\n";
974 // Output the pattern enums...
976 << "enum { // Patterns...\n"
977 << " NotComputed = 0,\n"
978 << " NoMatchPattern, \n";
979 for (PatternOrganizer::iterator I = ComputableValues.begin(),
980 E = ComputableValues.end(); I != E; ++I) {
981 OS << " // " << I->first << " patterns...\n";
982 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
983 E = I->second.end(); J != E; ++J)
984 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
985 OS << " " << J->second[i]->getRecord()->getName() << "_Pattern,\n";
989 //===--------------------------------------------------------------------===//
990 // Emit the class definition...
992 OS << "namespace {\n"
993 << " class " << Target.getName() << "ISel {\n"
994 << " SelectionDAG &DAG;\n"
996 << " X86ISel(SelectionDAG &D) : DAG(D) {}\n"
997 << " void generateCode();\n"
999 << " unsigned makeAnotherReg(const TargetRegisterClass *RC) {\n"
1000 << " return DAG.getMachineFunction().getSSARegMap()->createVirt"
1001 "ualRegister(RC);\n"
1003 << " // DAG matching methods for classes... all of these methods"
1004 " return the cost\n"
1005 << " // of producing a value of the specified class and type, which"
1007 << " // added to the DAG node.\n";
1009 // Output all of the matching prototypes for slots...
1010 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1011 E = ComputableValues.end(); I != E; ++I)
1012 OS << " unsigned Match_" << I->first << "(SelectionDAGNode *N);\n";
1013 OS << "\n // DAG matching methods for DAG nodes...\n";
1015 // Output all of the matching prototypes for slot/node pairs
1016 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1017 E = ComputableValues.end(); I != E; ++I)
1018 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1019 E = I->second.end(); J != E; ++J)
1020 OS << " unsigned Match_" << I->first << "_" << getNodeName(J->first)
1021 << "(SelectionDAGNode *N);\n";
1023 // Output all of the dag reduction methods prototypes...
1024 OS << "\n // DAG reduction methods...\n";
1025 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1026 E = ComputableValues.end(); I != E; ++I)
1027 OS << " ReducedValue_" << I->first << " *Reduce_" << I->first
1028 << "(SelectionDAGNode *N,\n" << std::string(27+2*I->first.size(), ' ')
1029 << "MachineBasicBlock *MBB);\n";
1032 // Emit the generateCode entry-point...
1033 OS << "void X86ISel::generateCode() {\n"
1034 << " SelectionDAGNode *Root = DAG.getRoot();\n"
1035 << " assert(Root->getValueType() == MVT::isVoid && "
1036 "\"Root of DAG produces value??\");\n\n"
1037 << " std::cerr << \"\\n\";\n"
1038 << " unsigned Cost = Match_Void_void(Root);\n"
1039 << " if (Cost >= ~0U >> 1) {\n"
1040 << " std::cerr << \"Match failed!\\n\";\n"
1041 << " Root->dump();\n"
1044 << " std::cerr << \"Total DAG Cost: \" << Cost << \"\\n\\n\";\n\n"
1045 << " Reduce_Void_void(Root, 0);\n"
1047 << "//===" << std::string(70, '-') << "===//\n"
1048 << "// Matching methods...\n"
1051 //===--------------------------------------------------------------------===//
1052 // Emit all of the matcher methods...
1054 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1055 E = ComputableValues.end(); I != E; ++I) {
1056 const std::string &SlotName = I->first;
1057 OS << "unsigned " << Target.getName() << "ISel::Match_" << SlotName
1058 << "(SelectionDAGNode *N) {\n"
1059 << " assert(N->getValueType() == MVT::"
1060 << getEnumName((*I->second.begin()).second[0]->getTree()->getType())
1061 << ");\n" << " // If we already have a cost available for " << SlotName
1063 << " if (N->getPatternFor(" << SlotName << "_Slot))\n"
1064 << " return N->getCostFor(" << SlotName << "_Slot);\n\n"
1065 << " unsigned Cost;\n"
1066 << " switch (N->getNodeType()) {\n"
1067 << " default: Cost = ~0U >> 1; // Match failed\n"
1068 << " N->setPatternCostFor(" << SlotName << "_Slot, NoMatchPattern, Cost, NumSlots);\n"
1071 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1072 E = I->second.end(); J != E; ++J)
1073 if (!J->first->isSubClassOf("Nonterminal"))
1074 OS << " case ISD::" << getNodeName(J->first) << ":\tCost = Match_"
1075 << SlotName << "_" << getNodeName(J->first) << "(N); break;\n";
1076 OS << " }\n"; // End of the switch statement
1078 // Emit any patterns which have a nonterminal leaf as the RHS. These may
1079 // match multiple root nodes, so they cannot be handled with the switch...
1080 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1081 E = I->second.end(); J != E; ++J)
1082 if (J->first->isSubClassOf("Nonterminal")) {
1083 OS << " unsigned " << J->first->getName() << "_Cost = Match_"
1084 << getNodeName(J->first) << "(N);\n"
1085 << " if (" << getNodeName(J->first) << "_Cost < Cost) Cost = "
1086 << getNodeName(J->first) << "_Cost;\n";
1089 OS << " return Cost;\n}\n\n";
1091 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1092 E = I->second.end(); J != E; ++J) {
1093 Record *Operator = J->first;
1094 bool isNonterm = Operator->isSubClassOf("Nonterminal");
1096 OS << "unsigned " << Target.getName() << "ISel::Match_";
1097 if (!isNonterm) OS << SlotName << "_";
1098 OS << getNodeName(Operator) << "(SelectionDAGNode *N) {\n"
1099 << " unsigned Pattern = NoMatchPattern;\n"
1100 << " unsigned MinCost = ~0U >> 1;\n";
1102 std::vector<std::pair<Pattern*, TreePatternNode*> > Patterns;
1103 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
1104 Patterns.push_back(std::make_pair(J->second[i],
1105 J->second[i]->getTree()));
1106 EmitMatchCosters(OS, Patterns, "N", 2);
1108 OS << "\n N->setPatternCostFor(" << SlotName
1109 << "_Slot, Pattern, MinCost, NumSlots);\n"
1110 << " return MinCost;\n"
1116 //===--------------------------------------------------------------------===//
1117 // Emit all of the reducer methods...
1119 OS << "\n\n//===" << std::string(70, '-') << "===//\n"
1120 << "// Reducer methods...\n"
1123 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1124 E = ComputableValues.end(); I != E; ++I) {
1125 const std::string &SlotName = I->first;
1126 OS << "ReducedValue_" << SlotName << " *" << Target.getName()
1127 << "ISel::Reduce_" << SlotName
1128 << "(SelectionDAGNode *N, MachineBasicBlock *MBB) {\n"
1129 << " ReducedValue_" << SlotName << " *Val = N->hasValue<ReducedValue_"
1130 << SlotName << ">(" << SlotName << "_Slot);\n"
1131 << " if (Val) return Val;\n"
1132 << " if (N->getBB()) MBB = N->getBB();\n\n"
1133 << " switch (N->getPatternFor(" << SlotName << "_Slot)) {\n";
1135 // Loop over all of the patterns that can produce a value for this slot...
1136 PatternOrganizer::NodesForSlot &NodesForSlot = I->second;
1137 for (PatternOrganizer::NodesForSlot::iterator J = NodesForSlot.begin(),
1138 E = NodesForSlot.end(); J != E; ++J)
1139 for (unsigned i = 0, e = J->second.size(); i != e; ++i) {
1140 Pattern *P = J->second[i];
1141 OS << " case " << P->getRecord()->getName() << "_Pattern: {\n"
1142 << " // " << *P << "\n";
1143 // Loop over the operands, reducing them...
1144 std::vector<std::pair<TreePatternNode*, std::string> > Operands;
1145 ReduceAllOperands(P->getTree(), "N", Operands, OS);
1147 // Now that we have reduced all of our operands, and have the values
1148 // that reduction produces, perform the reduction action for this
1152 // If the pattern produces a register result, generate a new register
1154 if (Record *R = P->getResult()) {
1155 assert(R->isSubClassOf("RegisterClass") &&
1156 "Only handle register class results so far!");
1157 OS << " unsigned NewReg = makeAnotherReg(" << Target.getName()
1158 << "::" << R->getName() << "RegisterClass);\n";
1160 DEBUG(OS << " std::cerr << \"%reg\" << NewReg << \" =\t\";\n");
1162 DEBUG(OS << " std::cerr << \"\t\t\";\n");
1166 // Print out the pattern that matched...
1167 DEBUG(OS << " std::cerr << \" " << P->getRecord()->getName() <<'"');
1168 DEBUG(for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1169 if (Operands[i].first->isLeaf()) {
1170 Record *RV = Operands[i].first->getValueRecord();
1171 assert(RV->isSubClassOf("RegisterClass") &&
1172 "Only handles registers here so far!");
1173 OS << " << \" %reg\" << " << Operands[i].second
1176 OS << " << ' ' << " << Operands[i].second
1179 DEBUG(OS << " << \"\\n\";\n");
1181 // Generate the reduction code appropriate to the particular type of
1182 // pattern that this is...
1183 switch (P->getPatternType()) {
1184 case Pattern::Instruction:
1185 // Instruction patterns just emit a single MachineInstr, using BuildMI
1186 OS << " BuildMI(MBB, " << Target.getName() << "::"
1187 << P->getRecord()->getName() << ", " << Operands.size();
1188 if (P->getResult()) OS << ", NewReg";
1191 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1192 if (Operands[i].first->isLeaf()) {
1193 Record *RV = Operands[i].first->getValueRecord();
1194 assert(RV->isSubClassOf("RegisterClass") &&
1195 "Only handles registers here so far!");
1196 OS << ".addReg(" << Operands[i].second << "->Val)";
1198 OS << ".addZImm(" << Operands[i].second << "->Val)";
1202 case Pattern::Expander: {
1203 // Expander patterns emit one machine instr for each instruction in
1204 // the list of instructions expanded to.
1205 ListInit *Insts = P->getRecord()->getValueAsListInit("Result");
1206 for (unsigned IN = 0, e = Insts->getSize(); IN != e; ++IN) {
1207 DagInit *DIInst = dynamic_cast<DagInit*>(Insts->getElement(IN));
1208 if (!DIInst) P->error("Result list must contain instructions!");
1209 Pattern *InstPat = getPattern(DIInst->getNodeType());
1210 if (!InstPat || InstPat->getPatternType() != Pattern::Instruction)
1211 P->error("Instruction list must contain Instruction patterns!");
1213 bool hasResult = InstPat->getResult() != 0;
1214 if (InstPat->getNumArgs() != DIInst->getNumArgs()-hasResult) {
1215 P->error("Incorrect number of arguments specified for inst '" +
1216 InstPat->getRecord()->getName() + "' in result list!");
1219 // Start emission of the instruction...
1220 OS << " BuildMI(MBB, " << Target.getName() << "::"
1221 << InstPat->getRecord()->getName() << ", "
1222 << DIInst->getNumArgs()-hasResult;
1223 // Emit register result if necessary..
1224 if (Record *R = InstPat->getResult()) {
1225 std::string ArgNameVal =
1226 getArgName(P, DIInst->getArgName(0), Operands);
1227 PrintExpanderOperand(DIInst->getArg(0), ArgNameVal,
1228 InstPat->getResultNode(), P, false,
1233 for (unsigned i = hasResult, e = DIInst->getNumArgs(); i != e; ++i){
1234 std::string ArgNameVal =
1235 getArgName(P, DIInst->getArgName(i), Operands);
1237 PrintExpanderOperand(DIInst->getArg(i), ArgNameVal,
1238 InstPat->getArg(i-hasResult), P, true, OS);
1246 assert(0 && "Reduction of this type of pattern not implemented!");
1249 OS << " Val = new ReducedValue_" << SlotName << "(" << Result<<");\n"
1255 OS << " default: assert(0 && \"Unknown " << SlotName << " pattern!\");\n"
1256 << " }\n\n N->addValue(Val); // Do not ever recalculate this\n"
1257 << " return Val;\n}\n\n";