Finish the matcher!
[oota-llvm.git] / utils / TableGen / InstrSelectorEmitter.cpp
1 //===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
2 //
3 // This tablegen backend is responsible for emitting a description of the target
4 // instruction set for the code generator.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "InstrSelectorEmitter.h"
9 #include "CodeGenWrappers.h"
10 #include "Record.h"
11 #include "Support/Debug.h"
12 #include "Support/StringExtras.h"
13 #include <set>
14
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 + "'!";
22 }
23
24
25 //===----------------------------------------------------------------------===//
26 // TreePatternNode implementation
27 //
28
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!");
34   return DI->getDef();
35 }
36
37
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
40 //
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) {
45     setType(VT);
46     return true;
47   }
48
49   throw "Type inferfence contradiction found for pattern " + RecName;
50 }
51
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.
55 ///
56 void TreePatternNode::InstantiateNonterminals(InstrSelectorEmitter &ISE) {
57   if (!isLeaf()) {
58     for (unsigned i = 0, e = Children.size(); i != e; ++i)
59       Children[i]->InstantiateNonterminals(ISE);
60     return;
61   }
62   
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,
70       // nonterminal.
71       
72       Value = new DefInit(ISE.InstantiateNonterminal(NT, getType()));
73     }
74   }
75 }
76
77
78 /// clone - Make a copy of this tree and all of its children.
79 ///
80 TreePatternNode *TreePatternNode::clone() const {
81   TreePatternNode *New;
82   if (isLeaf()) {
83     New = new TreePatternNode(Value);
84   } else {
85     std::vector<TreePatternNode*> CChildren(Children.size());
86     for (unsigned i = 0, e = Children.size(); i != e; ++i)
87       CChildren[i] = Children[i]->clone();
88     New = new TreePatternNode(Operator, CChildren);
89   }
90   New->setType(Type);
91   return New;
92 }
93
94 std::ostream &operator<<(std::ostream &OS, const TreePatternNode &N) {
95   if (N.isLeaf())
96     return OS << N.getType() << ":" << *N.getValue();
97   OS << "(" << N.getType() << ":";
98   OS << N.getOperator()->getName();
99   
100   const std::vector<TreePatternNode*> &Children = N.getChildren();
101   if (!Children.empty()) {
102     OS << " " << *Children[0];
103     for (unsigned i = 1, e = Children.size(); i != e; ++i)
104       OS << ", " << *Children[i];
105   }  
106   return OS << ")";
107 }
108
109 void TreePatternNode::dump() const { std::cerr << *this; }
110
111 //===----------------------------------------------------------------------===//
112 // Pattern implementation
113 //
114
115 // Parse the specified DagInit into a TreePattern which we can use.
116 //
117 Pattern::Pattern(PatternType pty, DagInit *RawPat, Record *TheRec,
118                  InstrSelectorEmitter &ise)
119   : PTy(pty), TheRecord(TheRec), ISE(ise) {
120
121   // First, parse the pattern...
122   Tree = ParseTreePattern(RawPat);
123
124   // Run the type-inference engine...
125   InferAllTypes();
126
127   if (PTy == Instruction || PTy == Expander) {
128     // Check to make sure there is not any unset types in the tree pattern...
129     if (!isResolved()) {
130       std::cerr << "In pattern: " << *Tree << "\n";
131       error("Could not infer all types!");
132     }
133
134     // Check to see if we have a top-level (set) of a register.
135     if (Tree->getOperator()->getName() == "set") {
136       assert(Tree->getChildren().size() == 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);
141     }
142   }
143 }
144
145 void Pattern::error(const std::string &Msg) const {
146   std::string M = "In ";
147   switch (PTy) {
148   case Nonterminal: M += "nonterminal "; break;
149   case Instruction: M += "instruction "; break;
150   case Expander   : M += "expander "; break;
151   }
152   throw M + TheRecord->getName() + ": " + Msg;  
153 }
154
155 /// getIntrinsicType - Check to see if the specified record has an intrinsic
156 /// type which should be applied to it.  This infer the type of register
157 /// references from the register file information, for example.
158 ///
159 MVT::ValueType Pattern::getIntrinsicType(Record *R) const {
160   // Check to see if this is a register or a register class...
161   if (R->isSubClassOf("RegisterClass"))
162     return getValueType(R->getValueAsDef("RegType"));
163   else if (R->isSubClassOf("Nonterminal"))
164     return ISE.ReadNonterminal(R)->getTree()->getType();
165   else if (R->isSubClassOf("Register")) {
166     std::cerr << "WARNING: Explicit registers not handled yet!\n";
167     return MVT::Other;
168   }
169
170   throw "Error: Unknown value used: " + R->getName();
171 }
172
173 TreePatternNode *Pattern::ParseTreePattern(DagInit *DI) {
174   Record *Operator = DI->getNodeType();
175   const std::vector<Init*> &Args = DI->getArgs();
176
177   if (Operator->isSubClassOf("ValueType")) {
178     // If the operator is a ValueType, then this must be "type cast" of a leaf
179     // node.
180     if (Args.size() != 1)
181       error("Type cast only valid for a leaf node!");
182     
183     Init *Arg = Args[0];
184     TreePatternNode *New;
185     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
186       New = new TreePatternNode(DI);
187       // If it's a regclass or something else known, set the type.
188       New->setType(getIntrinsicType(DI->getDef()));
189     } else {
190       Arg->dump();
191       error("Unknown leaf value for tree pattern!");
192     }
193
194     // Apply the type cast...
195     New->updateNodeType(getValueType(Operator), TheRecord->getName());
196     return New;
197   }
198
199   if (!ISE.getNodeTypes().count(Operator))
200     error("Unrecognized node '" + Operator->getName() + "'!");
201
202   std::vector<TreePatternNode*> Children;
203   
204   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
205     Init *Arg = Args[i];
206     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
207       Children.push_back(ParseTreePattern(DI));
208     } else if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
209       Children.push_back(new TreePatternNode(DI));
210       // If it's a regclass or something else known, set the type.
211       Children.back()->setType(getIntrinsicType(DI->getDef()));
212     } else {
213       Arg->dump();
214       error("Unknown leaf value for tree pattern!");
215     }
216   }
217
218   return new TreePatternNode(Operator, Children);
219 }
220
221 void Pattern::InferAllTypes() {
222   bool MadeChange, AnyUnset;
223   do {
224     MadeChange = false;
225     AnyUnset = InferTypes(Tree, MadeChange);
226   } while ((AnyUnset || MadeChange) && !(AnyUnset && !MadeChange));
227   Resolved = !AnyUnset;
228 }
229
230
231 // InferTypes - Perform type inference on the tree, returning true if there
232 // are any remaining untyped nodes and setting MadeChange if any changes were
233 // made.
234 bool Pattern::InferTypes(TreePatternNode *N, bool &MadeChange) {
235   if (N->isLeaf()) return N->getType() == MVT::Other;
236
237   bool AnyUnset = false;
238   Record *Operator = N->getOperator();
239   const NodeType &NT = ISE.getNodeType(Operator);
240
241   // Check to see if we can infer anything about the argument types from the
242   // return types...
243   const std::vector<TreePatternNode*> &Children = N->getChildren();
244   if (Children.size() != NT.ArgTypes.size())
245     error("Incorrect number of children for " + Operator->getName() + " node!");
246
247   for (unsigned i = 0, e = Children.size(); i != e; ++i) {
248     TreePatternNode *Child = Children[i];
249     AnyUnset |= InferTypes(Child, MadeChange);
250
251     switch (NT.ArgTypes[i]) {
252     case NodeType::Arg0:
253       MadeChange |= Child->updateNodeType(Children[0]->getType(),
254                                           TheRecord->getName());
255       break;
256     case NodeType::Val:
257       if (Child->getType() == MVT::isVoid)
258         error("Inferred a void node in an illegal place!");
259       break;
260     case NodeType::Ptr:
261       MadeChange |= Child->updateNodeType(ISE.getTarget().getPointerType(),
262                                           TheRecord->getName());
263       break;
264     default: assert(0 && "Invalid argument ArgType!");
265     }
266   }
267
268   // See if we can infer anything about the return type now...
269   switch (NT.ResultType) {
270   case NodeType::Void:
271     MadeChange |= N->updateNodeType(MVT::isVoid, TheRecord->getName());
272     break;
273   case NodeType::Arg0:
274     MadeChange |= N->updateNodeType(Children[0]->getType(),
275                                     TheRecord->getName());
276     break;
277
278   case NodeType::Ptr:
279     MadeChange |= N->updateNodeType(ISE.getTarget().getPointerType(),
280                                     TheRecord->getName());
281     break;
282   case NodeType::Val:
283     if (N->getType() == MVT::isVoid)
284       error("Inferred a void node in an illegal place!");
285     break;
286   default:
287     assert(0 && "Unhandled type constraint!");
288     break;
289   }
290
291   return AnyUnset | N->getType() == MVT::Other;
292 }
293
294 /// clone - This method is used to make an exact copy of the current pattern,
295 /// then change the "TheRecord" instance variable to the specified record.
296 ///
297 Pattern *Pattern::clone(Record *R) const {
298   assert(PTy == Nonterminal && "Can only clone nonterminals");
299   return new Pattern(Tree->clone(), R, Resolved, ISE);
300 }
301
302
303
304 std::ostream &operator<<(std::ostream &OS, const Pattern &P) {
305   switch (P.getPatternType()) {
306   case Pattern::Nonterminal: OS << "Nonterminal pattern "; break;
307   case Pattern::Instruction: OS << "Instruction pattern "; break;
308   case Pattern::Expander:    OS << "Expander pattern    "; break;
309   }
310
311   OS << P.getRecord()->getName() << ":\t";
312
313   if (Record *Result = P.getResult())
314     OS << Result->getName() << " = ";
315   OS << *P.getTree();
316
317   if (!P.isResolved())
318     OS << " [not completely resolved]";
319   return OS;
320 }
321
322 void Pattern::dump() const { std::cerr << *this; }
323
324
325
326 /// getSlotName - If this is a leaf node, return the slot name that the operand
327 /// will update.
328 std::string Pattern::getSlotName() const {
329   if (getPatternType() == Pattern::Nonterminal) {
330     // Just use the nonterminal name, which will already include the type if
331     // it has been cloned.
332     return getRecord()->getName();
333   } else {
334     std::string SlotName;
335     if (getResult())
336       SlotName = getResult()->getName()+"_";
337     else
338       SlotName = "Void_";
339     return SlotName + getName(getTree()->getType());
340   }
341 }
342
343 /// getSlotName - If this is a leaf node, return the slot name that the
344 /// operand will update.
345 std::string Pattern::getSlotName(Record *R) {
346   if (R->isSubClassOf("Nonterminal")) {
347     // Just use the nonterminal name, which will already include the type if
348     // it has been cloned.
349     return R->getName();
350   } else if (R->isSubClassOf("RegisterClass")) {
351     MVT::ValueType Ty = getValueType(R->getValueAsDef("RegType"));
352     return R->getName() + "_" + getName(Ty);
353   } else {
354     assert(0 && "Don't know how to get a slot name for this!");
355   }
356 }
357
358 //===----------------------------------------------------------------------===//
359 // PatternOrganizer implementation
360 //
361
362 /// addPattern - Add the specified pattern to the appropriate location in the
363 /// collection.
364 void PatternOrganizer::addPattern(Pattern *P) {
365   NodesForSlot &Nodes = AllPatterns[P->getSlotName()];
366   if (!P->getTree()->isLeaf())
367     Nodes[P->getTree()->getOperator()].push_back(P);
368   else {
369     // Right now we only support DefInit's with node types...
370     Nodes[P->getTree()->getValueRecord()].push_back(P);
371   }
372 }
373
374
375
376 //===----------------------------------------------------------------------===//
377 // InstrSelectorEmitter implementation
378 //
379
380 /// ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
381 /// turning them into the more accessible NodeTypes data structure.
382 ///
383 void InstrSelectorEmitter::ReadNodeTypes() {
384   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("DagNode");
385   DEBUG(std::cerr << "Getting node types: ");
386   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
387     Record *Node = Nodes[i];
388     
389     // Translate the return type...
390     NodeType::ArgResultTypes RetTy =
391       NodeType::Translate(Node->getValueAsDef("RetType"));
392
393     // Translate the arguments...
394     ListInit *Args = Node->getValueAsListInit("ArgTypes");
395     std::vector<NodeType::ArgResultTypes> ArgTypes;
396
397     for (unsigned a = 0, e = Args->getSize(); a != e; ++a) {
398       if (DefInit *DI = dynamic_cast<DefInit*>(Args->getElement(a)))
399         ArgTypes.push_back(NodeType::Translate(DI->getDef()));
400       else
401         throw "In node " + Node->getName() + ", argument is not a Def!";
402
403       if (a == 0 && ArgTypes.back() == NodeType::Arg0)
404         throw "In node " + Node->getName() + ", arg 0 cannot have type 'arg0'!";
405       if (ArgTypes.back() == NodeType::Void)
406         throw "In node " + Node->getName() + ", args cannot be void type!";
407     }
408     if (RetTy == NodeType::Arg0 && Args->getSize() == 0)
409       throw "In node " + Node->getName() +
410             ", invalid return type for nullary node!";
411
412     // Add the node type mapping now...
413     NodeTypes[Node] = NodeType(RetTy, ArgTypes);
414     DEBUG(std::cerr << Node->getName() << ", ");
415   }
416   DEBUG(std::cerr << "DONE!\n");
417 }
418
419 Pattern *InstrSelectorEmitter::ReadNonterminal(Record *R) {
420   Pattern *&P = Patterns[R];
421   if (P) return P;  // Don't reread it!
422
423   DagInit *DI = R->getValueAsDag("Pattern");
424   P = new Pattern(Pattern::Nonterminal, DI, R, *this);
425   DEBUG(std::cerr << "Parsed " << *P << "\n");
426   return P;
427 }
428
429
430 // ReadNonTerminals - Read in all nonterminals and incorporate them into our
431 // pattern database.
432 void InstrSelectorEmitter::ReadNonterminals() {
433   std::vector<Record*> NTs = Records.getAllDerivedDefinitions("Nonterminal");
434   for (unsigned i = 0, e = NTs.size(); i != e; ++i)
435     ReadNonterminal(NTs[i]);
436 }
437
438
439 /// ReadInstructionPatterns - Read in all subclasses of Instruction, and process
440 /// those with a useful Pattern field.
441 ///
442 void InstrSelectorEmitter::ReadInstructionPatterns() {
443   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
444   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
445     Record *Inst = Insts[i];
446     if (DagInit *DI = dynamic_cast<DagInit*>(Inst->getValueInit("Pattern"))) {
447       Patterns[Inst] = new Pattern(Pattern::Instruction, DI, Inst, *this);
448       DEBUG(std::cerr << "Parsed " << *Patterns[Inst] << "\n");
449     }
450   }
451 }
452
453 /// ReadExpanderPatterns - Read in all expander patterns...
454 ///
455 void InstrSelectorEmitter::ReadExpanderPatterns() {
456   std::vector<Record*> Expanders = Records.getAllDerivedDefinitions("Expander");
457   for (unsigned i = 0, e = Expanders.size(); i != e; ++i) {
458     Record *Expander = Expanders[i];
459     DagInit *DI = Expander->getValueAsDag("Pattern");
460     Patterns[Expander] = new Pattern(Pattern::Expander, DI, Expander, *this);
461     DEBUG(std::cerr << "Parsed " << *Patterns[Expander] << "\n");
462   }
463 }
464
465
466 // InstantiateNonterminals - Instantiate any unresolved nonterminals with
467 // information from the context that they are used in.
468 //
469 void InstrSelectorEmitter::InstantiateNonterminals() {
470   DEBUG(std::cerr << "Instantiating nonterminals:\n");
471   for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
472          E = Patterns.end(); I != E; ++I)
473     if (I->second->isResolved())
474       I->second->InstantiateNonterminals();
475 }
476
477 /// InstantiateNonterminal - This method takes the nonterminal specified by
478 /// NT, which should not be completely resolved, clones it, applies ResultTy
479 /// to its root, then runs the type inference stuff on it.  This should
480 /// produce a newly resolved nonterminal, which we make a record for and
481 /// return.  To be extra fancy and efficient, this only makes one clone for
482 /// each type it is instantiated with.
483 Record *InstrSelectorEmitter::InstantiateNonterminal(Pattern *NT,
484                                                      MVT::ValueType ResultTy) {
485   assert(!NT->isResolved() && "Nonterminal is already resolved!");
486
487   // Check to see if we have already instantiated this pair...
488   Record* &Slot = InstantiatedNTs[std::make_pair(NT, ResultTy)];
489   if (Slot) return Slot;
490   
491   Record *New = new Record(NT->getRecord()->getName()+"_"+getName(ResultTy));
492
493   // Copy over the superclasses...
494   const std::vector<Record*> &SCs = NT->getRecord()->getSuperClasses();
495   for (unsigned i = 0, e = SCs.size(); i != e; ++i)
496     New->addSuperClass(SCs[i]);
497
498   DEBUG(std::cerr << "  Nonterminal '" << NT->getRecord()->getName()
499                   << "' for type '" << getName(ResultTy) << "', producing '"
500                   << New->getName() << "'\n");
501
502   // Copy the pattern...
503   Pattern *NewPat = NT->clone(New);
504
505   // Apply the type to the root...
506   NewPat->getTree()->updateNodeType(ResultTy, New->getName());
507
508   // Infer types...
509   NewPat->InferAllTypes();
510
511   // Make sure everything is good to go now...
512   if (!NewPat->isResolved())
513     NewPat->error("Instantiating nonterminal did not resolve all types!");
514
515   // Add the pattern to the patterns map, add the record to the RecordKeeper,
516   // return the new record.
517   Patterns[New] = NewPat;
518   Records.addDef(New);
519   return Slot = New;
520 }
521
522 // CalculateComputableValues - Fill in the ComputableValues map through
523 // analysis of the patterns we are playing with.
524 void InstrSelectorEmitter::CalculateComputableValues() {
525   // Loop over all of the patterns, adding them to the ComputableValues map
526   for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
527          E = Patterns.end(); I != E; ++I)
528     if (I->second->isResolved())
529       ComputableValues.addPattern(I->second);
530 }
531
532 #if 0
533 // MoveIdenticalPatterns - Given a tree pattern 'P', move all of the tree
534 // patterns which have the same top-level structure as P from the 'From' list to
535 // the 'To' list.
536 static void MoveIdenticalPatterns(TreePatternNode *P,
537                     std::vector<std::pair<Pattern*, TreePatternNode*> > &From,
538                     std::vector<std::pair<Pattern*, TreePatternNode*> > &To) {
539   assert(!P->isLeaf() && "All leaves are identical!");
540
541   const std::vector<TreePatternNode*> &PChildren = P->getChildren();
542   for (unsigned i = 0; i != From.size(); ++i) {
543     TreePatternNode *N = From[i].second;
544     assert(P->getOperator() == N->getOperator() &&"Differing operators?");
545     assert(PChildren.size() == N->getChildren().size() &&
546            "Nodes with different arity??");
547     bool isDifferent = false;
548     for (unsigned c = 0, e = PChildren.size(); c != e; ++c) {
549       TreePatternNode *PC = PChildren[c];
550       TreePatternNode *NC = N->getChild(c);
551       if (PC->isLeaf() != NC->isLeaf()) {
552         isDifferent = true;
553         break;
554       }
555
556       if (!PC->isLeaf()) {
557         if (PC->getOperator() != NC->getOperator()) {
558           isDifferent = true;
559           break;
560         }
561       } else {  // It's a leaf!
562         if (PC->getValueRecord() != NC->getValueRecord()) {
563           isDifferent = true;
564           break;
565         }
566       }
567     }
568     // If it's the same as the reference one, move it over now...
569     if (!isDifferent) {
570       To.push_back(std::make_pair(From[i].first, N));
571       From.erase(From.begin()+i);
572       --i;   // Don't skip an entry...
573     }
574   }
575 }
576 #endif
577
578 static std::string getNodeName(Record *R) {
579   RecordVal *RV = R->getValue("EnumName");
580   if (RV)
581     if (Init *I = RV->getValue())
582       if (StringInit *SI = dynamic_cast<StringInit*>(I))
583         return SI->getValue();
584   return R->getName();
585 }
586
587
588 static void EmitPatternPredicates(TreePatternNode *Tree,
589                                   const std::string &VarName, std::ostream &OS){
590   OS << " && " << VarName << "->getNodeType() == ISD::"
591      << getNodeName(Tree->getOperator());
592
593   for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
594     if (!Tree->getChild(c)->isLeaf())
595       EmitPatternPredicates(Tree->getChild(c),
596                             VarName + "->getUse(" + utostr(c)+")", OS);
597 }
598
599 static void EmitPatternCosts(TreePatternNode *Tree, const std::string &VarName,
600                              std::ostream &OS) {
601   for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
602     if (Tree->getChild(c)->isLeaf()) {
603       OS << " + Match_"
604          << Pattern::getSlotName(Tree->getChild(c)->getValueRecord()) << "("
605          << VarName << "->getUse(" << c << "))";
606     } else {
607       EmitPatternCosts(Tree->getChild(c),
608                        VarName + "->getUse(" + utostr(c) + ")", OS);
609     }
610 }
611
612
613 // EmitMatchCosters - Given a list of patterns, which all have the same root
614 // pattern operator, emit an efficient decision tree to decide which one to
615 // pick.  This is structured this way to avoid reevaluations of non-obvious
616 // subexpressions.
617 void InstrSelectorEmitter::EmitMatchCosters(std::ostream &OS,
618            const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
619                                             const std::string &VarPrefix,
620                                             unsigned IndentAmt) {
621   assert(!Patterns.empty() && "No patterns to emit matchers for!");
622   std::string Indent(IndentAmt, ' ');
623   
624   // Load all of the operands of the root node into scalars for fast access
625   const NodeType &ONT = getNodeType(Patterns[0].second->getOperator());
626   for (unsigned i = 0, e = ONT.ArgTypes.size(); i != e; ++i)
627     OS << Indent << "SelectionDAGNode *" << VarPrefix << "_Op" << i
628        << " = N->getUse(" << i << ");\n";
629
630   // Compute the costs of computing the various nonterminals/registers, which
631   // are directly used at this level.
632   OS << "\n" << Indent << "// Operand matching costs...\n";
633   std::set<std::string> ComputedValues;   // Avoid duplicate computations...
634   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
635     const std::vector<TreePatternNode*> &Children =
636       Patterns[i].second->getChildren();
637     for (unsigned c = 0, e = Children.size(); c != e; ++c) {
638       TreePatternNode *N = Children[c];
639       if (N->isLeaf()) {
640         Record *VR = N->getValueRecord();
641         const std::string &LeafName = VR->getName();
642         std::string OpName  = VarPrefix + "_Op" + utostr(c);
643         std::string ValName = OpName + "_" + LeafName + "_Cost";
644         if (!ComputedValues.count(ValName)) {
645           OS << Indent << "unsigned " << ValName << " = Match_"
646              << Pattern::getSlotName(VR) << "(" << OpName << ");\n";
647           ComputedValues.insert(ValName);
648         }
649       }
650     }
651   }
652   OS << "\n";
653
654
655   std::string LocCostName = VarPrefix + "_Cost";
656   OS << Indent << "unsigned " << LocCostName << "Min = ~0U >> 1;\n"
657      << Indent << "unsigned " << VarPrefix << "_PatternMin = NoMatchPattern;\n";
658   
659 #if 0
660   // Separate out all of the patterns into groups based on what their top-level
661   // signature looks like...
662   std::vector<std::pair<Pattern*, TreePatternNode*> > PatternsLeft(Patterns);
663   while (!PatternsLeft.empty()) {
664     // Process all of the patterns that have the same signature as the last
665     // element...
666     std::vector<std::pair<Pattern*, TreePatternNode*> > Group;
667     MoveIdenticalPatterns(PatternsLeft.back().second, PatternsLeft, Group);
668     assert(!Group.empty() && "Didn't at least pick the source pattern?");
669
670 #if 0
671     OS << "PROCESSING GROUP:\n";
672     for (unsigned i = 0, e = Group.size(); i != e; ++i)
673       OS << "  " << *Group[i].first << "\n";
674     OS << "\n\n";
675 #endif
676
677     OS << Indent << "{ // ";
678
679     if (Group.size() != 1) {
680       OS << Group.size() << " size group...\n";
681       OS << Indent << "  unsigned " << VarPrefix << "_Pattern = NoMatch;\n";
682     } else {
683       OS << *Group[0].first << "\n";
684       OS << Indent << "  unsigned " << VarPrefix << "_Pattern = "
685          << Group[0].first->getRecord()->getName() << "_Pattern;\n";
686     }
687
688     OS << Indent << "  unsigned " << LocCostName << " = ";
689     if (Group.size() == 1)
690       OS << "1;\n";    // Add inst cost if at individual rec
691     else
692       OS << "0;\n";
693
694     // Loop over all of the operands, adding in their costs...
695     TreePatternNode *N = Group[0].second;
696     const std::vector<TreePatternNode*> &Children = N->getChildren();
697
698     // If necessary, emit conditionals to check for the appropriate tree
699     // structure here...
700     for (unsigned i = 0, e = Children.size(); i != e; ++i) {
701       TreePatternNode *C = Children[i];
702       if (C->isLeaf()) {
703         // We already calculated the cost for this leaf, add it in now...
704         OS << Indent << "  " << LocCostName << " += "
705            << VarPrefix << "_Op" << utostr(i) << "_"
706            << C->getValueRecord()->getName() << "_Cost;\n";
707       } else {
708         // If it's not a leaf, we have to check to make sure that the current
709         // node has the appropriate structure, then recurse into it...
710         OS << Indent << "  if (" << VarPrefix << "_Op" << i
711            << "->getNodeType() == ISD::" << getNodeName(C->getOperator())
712            << ") {\n";
713         std::vector<std::pair<Pattern*, TreePatternNode*> > SubPatterns;
714         for (unsigned n = 0, e = Group.size(); n != e; ++n)
715           SubPatterns.push_back(std::make_pair(Group[n].first,
716                                                Group[n].second->getChild(i)));
717         EmitMatchCosters(OS, SubPatterns, VarPrefix+"_Op"+utostr(i),
718                          IndentAmt + 4);
719         OS << Indent << "  }\n";
720       }
721     }
722
723     // If the cost for this match is less than the minimum computed cost so far,
724     // update the minimum cost and selected pattern.
725     OS << Indent << "  if (" << LocCostName << " < " << LocCostName << "Min) { "
726        << LocCostName << "Min = " << LocCostName << "; " << VarPrefix
727        << "_PatternMin = " << VarPrefix << "_Pattern; }\n";
728     
729     OS << Indent << "}\n";
730   }
731 #endif
732
733   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
734     Pattern *P = Patterns[i].first;
735     TreePatternNode *PTree = P->getTree();
736     unsigned PatternCost = 1;
737
738     // Check to see if there are any non-leaf elements in the pattern.  If so,
739     // we need to emit a predicate for this match.
740     bool AnyNonLeaf = false;
741     for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
742       if (!PTree->getChild(c)->isLeaf()) {
743         AnyNonLeaf = true;
744         break;
745       }
746
747     if (!AnyNonLeaf) {   // No predicate necessary, just output a scope...
748       OS << "  {// " << *P << "\n";
749     } else {
750       // We need to emit a predicate to make sure the tree pattern matches, do
751       // so now...
752       OS << "  if (1";
753       for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
754         if (!PTree->getChild(c)->isLeaf())
755           EmitPatternPredicates(PTree->getChild(c),
756                                 VarPrefix + "_Op" + utostr(c), OS);
757
758       OS << ") {\n    // " << *P << "\n";
759     }
760
761     OS << "    unsigned PatCost = " << PatternCost;
762
763     for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
764       if (PTree->getChild(c)->isLeaf()) {
765         OS << " + " << VarPrefix << "_Op" << c << "_"
766            << PTree->getChild(c)->getValueRecord()->getName() << "_Cost";
767       } else {
768         EmitPatternCosts(PTree->getChild(c), VarPrefix + "_Op" + utostr(c), OS);
769       }
770     OS << ";\n";
771     OS << "    if (PatCost < MinCost) { MinCost = PatCost; Pattern = "
772        << P->getRecord()->getName() << "_Pattern; }\n"
773        << "  }\n";
774   }
775 }
776
777 void InstrSelectorEmitter::run(std::ostream &OS) {
778   // Type-check all of the node types to ensure we "understand" them.
779   ReadNodeTypes();
780   
781   // Read in all of the nonterminals, instructions, and expanders...
782   ReadNonterminals();
783   ReadInstructionPatterns();
784   ReadExpanderPatterns();
785
786   // Instantiate any unresolved nonterminals with information from the context
787   // that they are used in.
788   InstantiateNonterminals();
789
790   // Clear InstantiatedNTs, we don't need it anymore...
791   InstantiatedNTs.clear();
792
793   std::cerr << "Patterns aquired:\n";
794   for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
795          E = Patterns.end(); I != E; ++I)
796     if (I->second->isResolved())
797       std::cerr << "  " << *I->second << "\n";
798
799   CalculateComputableValues();
800   
801   EmitSourceFileHeader("Instruction Selector for the " + Target.getName() +
802                        " target", OS);
803
804   // Output the slot number enums...
805   OS << "\nenum { // Slot numbers...\n"
806      << "  LastBuiltinSlot = ISD::NumBuiltinSlots-1, // Start numbering here\n";
807   for (PatternOrganizer::iterator I = ComputableValues.begin(),
808          E = ComputableValues.end(); I != E; ++I)
809     OS << "  " << I->first << "_Slot,\n";
810   OS << "  NumSlots\n};\n\n// Reduction value typedefs...\n";
811
812   // Output the reduction value typedefs...
813   for (PatternOrganizer::iterator I = ComputableValues.begin(),
814          E = ComputableValues.end(); I != E; ++I) {
815
816     OS << "typedef ReducedValue<unsigned, " << I->first
817        << "_Slot> ReducedValue_" << I->first << ";\n";
818   }
819
820   // Output the pattern enums...
821   OS << "\n\n"
822      << "enum { // Patterns...\n"
823      << "  NotComputed = 0,\n"
824      << "  NoMatchPattern, \n";
825   for (PatternOrganizer::iterator I = ComputableValues.begin(),
826          E = ComputableValues.end(); I != E; ++I) {
827     OS << "  // " << I->first << " patterns...\n";
828     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
829            E = I->second.end(); J != E; ++J)
830       for (unsigned i = 0, e = J->second.size(); i != e; ++i)
831         OS << "  " << J->second[i]->getRecord()->getName() << "_Pattern,\n";
832   }
833   OS << "};\n\n";
834
835   // Start emitting the class...
836   OS << "namespace {\n"
837      << "  class " << Target.getName() << "ISel {\n"
838      << "    SelectionDAG &DAG;\n"
839      << "  public:\n"
840      << "    X86ISel(SelectionDAG &D) : DAG(D) {}\n"
841      << "    void generateCode();\n"
842      << "  private:\n"
843      << "    unsigned makeAnotherReg(const TargetRegisterClass *RC) {\n"
844      << "      return DAG.getMachineFunction().getSSARegMap()->createVirt"
845                                        "ualRegister(RC);\n"
846      << "    }\n\n"
847      << "    // DAG matching methods for classes... all of these methods"
848                                        " return the cost\n"
849      << "    // of producing a value of the specified class and type, which"
850                                        " also gets\n"
851      << "    // added to the DAG node.\n";
852
853   // Output all of the matching prototypes for slots...
854   for (PatternOrganizer::iterator I = ComputableValues.begin(),
855          E = ComputableValues.end(); I != E; ++I)
856     OS << "    unsigned Match_" << I->first << "(SelectionDAGNode *N);\n";
857   OS << "\n    // DAG matching methods for DAG nodes...\n";
858
859   // Output all of the matching prototypes for slot/node pairs
860   for (PatternOrganizer::iterator I = ComputableValues.begin(),
861          E = ComputableValues.end(); I != E; ++I)
862     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
863            E = I->second.end(); J != E; ++J)
864       OS << "    unsigned Match_" << I->first << "_" << getNodeName(J->first)
865          << "(SelectionDAGNode *N);\n";
866
867   // Output all of the dag reduction methods prototypes...
868   OS << "\n    // DAG reduction methods...\n";
869   for (PatternOrganizer::iterator I = ComputableValues.begin(),
870          E = ComputableValues.end(); I != E; ++I)
871     OS << "    ReducedValue_" << I->first << " *Reduce_" << I->first
872        << "(SelectionDAGNode *N,\n" << std::string(27+2*I->first.size(), ' ')
873        << "MachineBasicBlock *MBB);\n";
874   OS << "  };\n}\n\n";
875
876   OS << "void X86ISel::generateCode() {\n"
877      << "  SelectionDAGNode *Root = DAG.getRoot();\n"
878      << "  assert(Root->getValueType() == MVT::isVoid && "
879                                        "\"Root of DAG produces value??\");\n\n"
880      << "  std::cerr << \"\\n\";\n"
881      << "  unsigned Cost = Match_Void_void(Root);\n"
882      << "  if (Cost >= ~0U >> 1) {\n"
883      << "    std::cerr << \"Match failed!\\n\";\n"
884      << "    Root->dump();\n"
885      << "    abort();\n"
886      << "  }\n\n"
887      << "  std::cerr << \"Total DAG Cost: \" << Cost << \"\\n\\n\";\n\n"
888      << "  Reduce_Void_void(Root, 0);\n"
889      << "}\n\n"
890      << "//===" << std::string(70, '-') << "===//\n"
891      << "//  Matching methods...\n"
892      << "//\n\n";
893
894   for (PatternOrganizer::iterator I = ComputableValues.begin(),
895          E = ComputableValues.end(); I != E; ++I) {
896     const std::string &SlotName = I->first;
897     OS << "unsigned " << Target.getName() << "ISel::Match_" << SlotName
898        << "(SelectionDAGNode *N) {\n"
899        << "  assert(N->getValueType() == MVT::"
900        << getEnumName((*I->second.begin()).second[0]->getTree()->getType())
901        << ");\n" << "  // If we already have a cost available for " << SlotName
902        << " use it!\n"
903        << "  if (N->getPatternFor(" << SlotName << "_Slot))\n"
904        << "    return N->getCostFor(" << SlotName << "_Slot);\n\n"
905        << "  unsigned Cost;\n"
906        << "  switch (N->getNodeType()) {\n"
907        << "  default: assert(0 && \"Unhandled node type for " << SlotName
908        << "!\");\n";
909
910     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
911            E = I->second.end(); J != E; ++J)
912       if (!J->first->isSubClassOf("Nonterminal"))
913         OS << "  case ISD::" << getNodeName(J->first) << ":\tCost = Match_"
914            << SlotName << "_" << getNodeName(J->first) << "(N); break;\n";
915     OS << "  }\n";  // End of the switch statement
916
917     // Emit any patterns which have a nonterminal leaf as the RHS.  These may
918     // match multiple root nodes, so they cannot be handled with the switch...
919     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
920            E = I->second.end(); J != E; ++J)
921       if (J->first->isSubClassOf("Nonterminal")) {
922         OS << "  unsigned " << J->first->getName() << "_Cost = Match_"
923            << getNodeName(J->first) << "(N);\n"
924            << "  if (" << getNodeName(J->first) << "_Cost < Cost) Cost = "
925            << getNodeName(J->first) << "_Cost;\n";
926       }
927
928     OS << "  return Cost;\n}\n\n";
929
930     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
931            E = I->second.end(); J != E; ++J) {
932       Record *Operator = J->first;
933       bool isNonterm = Operator->isSubClassOf("Nonterminal");
934       if (!isNonterm) {
935         OS << "unsigned " << Target.getName() << "ISel::Match_";
936         if (!isNonterm) OS << SlotName << "_";
937         OS << getNodeName(Operator) << "(SelectionDAGNode *N) {\n"
938            << "  unsigned Pattern = NoMatchPattern;\n"
939            << "  unsigned MinCost = ~0U >> 1;\n";
940         
941         std::vector<std::pair<Pattern*, TreePatternNode*> > Patterns;
942         for (unsigned i = 0, e = J->second.size(); i != e; ++i)
943           Patterns.push_back(std::make_pair(J->second[i],
944                                             J->second[i]->getTree()));
945         EmitMatchCosters(OS, Patterns, "N", 2);
946         
947         OS << "\n  N->setPatternCostFor(" << SlotName
948            << "_Slot, Pattern, MinCost, NumSlots);\n"
949            << "  return MinCost;\n"
950            << "}\n";
951       }
952     }
953   }
954 }
955