2db6da4bd2ff67d674bbfc821a863f2a2a3dac1c
[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_any")  return Any;
18   if (Name == "DNVT_void") return Void;
19   if (Name == "DNVT_val" ) return Val;
20   if (Name == "DNVT_arg0") return Arg0;
21   if (Name == "DNVT_arg1") return Arg1;
22   if (Name == "DNVT_ptr" ) return Ptr;
23   if (Name == "DNVT_i8"  ) return I8;
24   throw "Unknown DagNodeValType '" + Name + "'!";
25 }
26
27
28 //===----------------------------------------------------------------------===//
29 // TreePatternNode implementation
30 //
31
32 /// getValueRecord - Returns the value of this tree node as a record.  For now
33 /// we only allow DefInit's as our leaf values, so this is used.
34 Record *TreePatternNode::getValueRecord() const {
35   DefInit *DI = dynamic_cast<DefInit*>(getValue());
36   assert(DI && "Instruction Selector does not yet support non-def leaves!");
37   return DI->getDef();
38 }
39
40
41 // updateNodeType - Set the node type of N to VT if VT contains information.  If
42 // N already contains a conflicting type, then throw an exception
43 //
44 bool TreePatternNode::updateNodeType(MVT::ValueType VT,
45                                      const std::string &RecName) {
46   if (VT == MVT::Other || getType() == VT) return false;
47   if (getType() == MVT::Other) {
48     setType(VT);
49     return true;
50   }
51
52   throw "Type inferfence contradiction found for pattern " + RecName;
53 }
54
55 /// InstantiateNonterminals - If this pattern refers to any nonterminals which
56 /// are not themselves completely resolved, clone the nonterminal and resolve it
57 /// with the using context we provide.
58 ///
59 void TreePatternNode::InstantiateNonterminals(InstrSelectorEmitter &ISE) {
60   if (!isLeaf()) {
61     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
62       getChild(i)->InstantiateNonterminals(ISE);
63     return;
64   }
65   
66   // If this is a leaf, it might be a reference to a nonterminal!  Check now.
67   Record *R = getValueRecord();
68   if (R->isSubClassOf("Nonterminal")) {
69     Pattern *NT = ISE.getPattern(R);
70     if (!NT->isResolved()) {
71       // We found an unresolved nonterminal reference.  Ask the ISE to clone
72       // it for us, then update our reference to the fresh, new, resolved,
73       // nonterminal.
74       
75       Value = new DefInit(ISE.InstantiateNonterminal(NT, getType()));
76     }
77   }
78 }
79
80
81 /// clone - Make a copy of this tree and all of its children.
82 ///
83 TreePatternNode *TreePatternNode::clone() const {
84   TreePatternNode *New;
85   if (isLeaf()) {
86     New = new TreePatternNode(Value);
87   } else {
88     std::vector<std::pair<TreePatternNode*, std::string> > CChildren;
89     CChildren.reserve(Children.size());
90     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
91       CChildren.push_back(std::make_pair(getChild(i)->clone(),getChildName(i)));
92     New = new TreePatternNode(Operator, CChildren);
93   }
94   New->setType(Type);
95   return New;
96 }
97
98 std::ostream &operator<<(std::ostream &OS, const TreePatternNode &N) {
99   if (N.isLeaf())
100     return OS << N.getType() << ":" << *N.getValue();
101   OS << "(" << N.getType() << ":";
102   OS << N.getOperator()->getName();
103   
104   if (N.getNumChildren() != 0) {
105     OS << " " << *N.getChild(0);
106     for (unsigned i = 1, e = N.getNumChildren(); i != e; ++i)
107       OS << ", " << *N.getChild(i);
108   }  
109   return OS << ")";
110 }
111
112 void TreePatternNode::dump() const { std::cerr << *this; }
113
114 //===----------------------------------------------------------------------===//
115 // Pattern implementation
116 //
117
118 // Parse the specified DagInit into a TreePattern which we can use.
119 //
120 Pattern::Pattern(PatternType pty, DagInit *RawPat, Record *TheRec,
121                  InstrSelectorEmitter &ise)
122   : PTy(pty), ResultNode(0), TheRecord(TheRec), ISE(ise) {
123
124   // First, parse the pattern...
125   Tree = ParseTreePattern(RawPat);
126
127   // Run the type-inference engine...
128   InferAllTypes();
129
130   if (PTy == Instruction || PTy == Expander) {
131     // Check to make sure there is not any unset types in the tree pattern...
132     if (!isResolved()) {
133       std::cerr << "In pattern: " << *Tree << "\n";
134       error("Could not infer all types!");
135     }
136
137     // Check to see if we have a top-level (set) of a register.
138     if (Tree->getOperator()->getName() == "set") {
139       assert(Tree->getNumChildren() == 2 && "Set with != 2 arguments?");
140       if (!Tree->getChild(0)->isLeaf())
141         error("Arg #0 of set should be a register or register class!");
142       ResultNode = Tree->getChild(0);
143       ResultName = Tree->getChildName(0);
144       Tree = Tree->getChild(1);
145     }
146   }
147
148   calculateArgs(Tree, "");
149 }
150
151 void Pattern::error(const std::string &Msg) const {
152   std::string M = "In ";
153   switch (PTy) {
154   case Nonterminal: M += "nonterminal "; break;
155   case Instruction: M += "instruction "; break;
156   case Expander   : M += "expander "; break;
157   }
158   throw M + TheRecord->getName() + ": " + Msg;  
159 }
160
161 /// calculateArgs - Compute the list of all of the arguments to this pattern,
162 /// which are the non-void leaf nodes in this pattern.
163 ///
164 void Pattern::calculateArgs(TreePatternNode *N, const std::string &Name) {
165   if (N->isLeaf() || N->getNumChildren() == 0) {
166     if (N->getType() != MVT::isVoid)
167       Args.push_back(std::make_pair(N, Name));
168   } else {
169     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
170       calculateArgs(N->getChild(i), N->getChildName(i));
171   }
172 }
173
174 /// getIntrinsicType - Check to see if the specified record has an intrinsic
175 /// type which should be applied to it.  This infer the type of register
176 /// references from the register file information, for example.
177 ///
178 MVT::ValueType Pattern::getIntrinsicType(Record *R) const {
179   // Check to see if this is a register or a register class...
180   if (R->isSubClassOf("RegisterClass"))
181     return getValueType(R->getValueAsDef("RegType"));
182   else if (R->isSubClassOf("Nonterminal"))
183     return ISE.ReadNonterminal(R)->getTree()->getType();
184   else if (R->isSubClassOf("Register")) {
185     std::cerr << "WARNING: Explicit registers not handled yet!\n";
186     return MVT::Other;
187   }
188
189   error("Unknown value used: " + R->getName());
190   return MVT::Other;
191 }
192
193 TreePatternNode *Pattern::ParseTreePattern(DagInit *Dag) {
194   Record *Operator = Dag->getNodeType();
195
196   if (Operator->isSubClassOf("ValueType")) {
197     // If the operator is a ValueType, then this must be "type cast" of a leaf
198     // node.
199     if (Dag->getNumArgs() != 1)
200       error("Type cast only valid for a leaf node!");
201     
202     Init *Arg = Dag->getArg(0);
203     TreePatternNode *New;
204     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
205       New = new TreePatternNode(DI);
206       // If it's a regclass or something else known, set the type.
207       New->setType(getIntrinsicType(DI->getDef()));
208     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
209       New = ParseTreePattern(DI);
210     } else {
211       Arg->dump();
212       error("Unknown leaf value for tree pattern!");
213     }
214
215     // Apply the type cast...
216     New->updateNodeType(getValueType(Operator), TheRecord->getName());
217     return New;
218   }
219
220   if (!ISE.getNodeTypes().count(Operator))
221     error("Unrecognized node '" + Operator->getName() + "'!");
222
223   std::vector<std::pair<TreePatternNode*, std::string> > Children;
224   
225   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
226     Init *Arg = Dag->getArg(i);
227     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
228       Children.push_back(std::make_pair(ParseTreePattern(DI),
229                                         Dag->getArgName(i)));
230     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
231       Record *R = DefI->getDef();
232       // Direct reference to a leaf DagNode?  Turn it into a DagNode if its own.
233       if (R->isSubClassOf("DagNode")) {
234         Dag->setArg(i, new DagInit(R,
235                                 std::vector<std::pair<Init*, std::string> >()));
236         --i;  // Revisit this node...
237       } else {
238         Children.push_back(std::make_pair(new TreePatternNode(DefI),
239                                           Dag->getArgName(i)));
240         // If it's a regclass or something else known, set the type.
241         Children.back().first->setType(getIntrinsicType(R));
242       }
243     } else {
244       Arg->dump();
245       error("Unknown leaf value for tree pattern!");
246     }
247   }
248
249   return new TreePatternNode(Operator, Children);
250 }
251
252 void Pattern::InferAllTypes() {
253   bool MadeChange, AnyUnset;
254   do {
255     MadeChange = false;
256     AnyUnset = InferTypes(Tree, MadeChange);
257   } while ((AnyUnset || MadeChange) && !(AnyUnset && !MadeChange));
258   Resolved = !AnyUnset;
259 }
260
261
262 // InferTypes - Perform type inference on the tree, returning true if there
263 // are any remaining untyped nodes and setting MadeChange if any changes were
264 // made.
265 bool Pattern::InferTypes(TreePatternNode *N, bool &MadeChange) {
266   if (N->isLeaf()) return N->getType() == MVT::Other;
267
268   bool AnyUnset = false;
269   Record *Operator = N->getOperator();
270   const NodeType &NT = ISE.getNodeType(Operator);
271
272   // Check to see if we can infer anything about the argument types from the
273   // return types...
274   if (N->getNumChildren() != NT.ArgTypes.size())
275     error("Incorrect number of children for " + Operator->getName() + " node!");
276
277   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
278     TreePatternNode *Child = N->getChild(i);
279     AnyUnset |= InferTypes(Child, MadeChange);
280
281     switch (NT.ArgTypes[i]) {
282     case NodeType::Any: break;
283     case NodeType::I8:
284       MadeChange |= Child->updateNodeType(MVT::i1, TheRecord->getName());
285       break;
286     case NodeType::Arg0:
287       MadeChange |= Child->updateNodeType(N->getChild(0)->getType(),
288                                           TheRecord->getName());
289       break;
290     case NodeType::Arg1:
291       MadeChange |= Child->updateNodeType(N->getChild(1)->getType(),
292                                           TheRecord->getName());
293       break;
294     case NodeType::Val:
295       if (Child->getType() == MVT::isVoid)
296         error("Inferred a void node in an illegal place!");
297       break;
298     case NodeType::Ptr:
299       MadeChange |= Child->updateNodeType(ISE.getTarget().getPointerType(),
300                                           TheRecord->getName());
301       break;
302     case NodeType::Void:
303       MadeChange |= Child->updateNodeType(MVT::isVoid, TheRecord->getName());
304       break;
305     default: assert(0 && "Invalid argument ArgType!");
306     }
307   }
308
309   // See if we can infer anything about the return type now...
310   switch (NT.ResultType) {
311   case NodeType::Any: break;
312   case NodeType::Void:
313     MadeChange |= N->updateNodeType(MVT::isVoid, TheRecord->getName());
314     break;
315   case NodeType::I8:
316     MadeChange |= N->updateNodeType(MVT::i1, TheRecord->getName());
317     break;
318   case NodeType::Arg0:
319     MadeChange |= N->updateNodeType(N->getChild(0)->getType(),
320                                     TheRecord->getName());
321     break;
322   case NodeType::Arg1:
323     MadeChange |= N->updateNodeType(N->getChild(1)->getType(),
324                                     TheRecord->getName());
325     break;
326   case NodeType::Ptr:
327     MadeChange |= N->updateNodeType(ISE.getTarget().getPointerType(),
328                                     TheRecord->getName());
329     break;
330   case NodeType::Val:
331     if (N->getType() == MVT::isVoid)
332       error("Inferred a void node in an illegal place!");
333     break;
334   default:
335     assert(0 && "Unhandled type constraint!");
336     break;
337   }
338
339   return AnyUnset | N->getType() == MVT::Other;
340 }
341
342 /// clone - This method is used to make an exact copy of the current pattern,
343 /// then change the "TheRecord" instance variable to the specified record.
344 ///
345 Pattern *Pattern::clone(Record *R) const {
346   assert(PTy == Nonterminal && "Can only clone nonterminals");
347   return new Pattern(Tree->clone(), R, Resolved, ISE);
348 }
349
350
351
352 std::ostream &operator<<(std::ostream &OS, const Pattern &P) {
353   switch (P.getPatternType()) {
354   case Pattern::Nonterminal: OS << "Nonterminal pattern "; break;
355   case Pattern::Instruction: OS << "Instruction pattern "; break;
356   case Pattern::Expander:    OS << "Expander pattern    "; break;
357   }
358
359   OS << P.getRecord()->getName() << ":\t";
360
361   if (Record *Result = P.getResult())
362     OS << Result->getName() << " = ";
363   OS << *P.getTree();
364
365   if (!P.isResolved())
366     OS << " [not completely resolved]";
367   return OS;
368 }
369
370 void Pattern::dump() const { std::cerr << *this; }
371
372
373
374 /// getSlotName - If this is a leaf node, return the slot name that the operand
375 /// will update.
376 std::string Pattern::getSlotName() const {
377   if (getPatternType() == Pattern::Nonterminal) {
378     // Just use the nonterminal name, which will already include the type if
379     // it has been cloned.
380     return getRecord()->getName();
381   } else {
382     std::string SlotName;
383     if (getResult())
384       SlotName = getResult()->getName()+"_";
385     else
386       SlotName = "Void_";
387     return SlotName + getName(getTree()->getType());
388   }
389 }
390
391 /// getSlotName - If this is a leaf node, return the slot name that the
392 /// operand will update.
393 std::string Pattern::getSlotName(Record *R) {
394   if (R->isSubClassOf("Nonterminal")) {
395     // Just use the nonterminal name, which will already include the type if
396     // it has been cloned.
397     return R->getName();
398   } else if (R->isSubClassOf("RegisterClass")) {
399     MVT::ValueType Ty = getValueType(R->getValueAsDef("RegType"));
400     return R->getName() + "_" + getName(Ty);
401   } else {
402     assert(0 && "Don't know how to get a slot name for this!");
403   }
404 }
405
406 //===----------------------------------------------------------------------===//
407 // PatternOrganizer implementation
408 //
409
410 /// addPattern - Add the specified pattern to the appropriate location in the
411 /// collection.
412 void PatternOrganizer::addPattern(Pattern *P) {
413   NodesForSlot &Nodes = AllPatterns[P->getSlotName()];
414   if (!P->getTree()->isLeaf())
415     Nodes[P->getTree()->getOperator()].push_back(P);
416   else {
417     // Right now we only support DefInit's with node types...
418     Nodes[P->getTree()->getValueRecord()].push_back(P);
419   }
420 }
421
422
423
424 //===----------------------------------------------------------------------===//
425 // InstrSelectorEmitter implementation
426 //
427
428 /// ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
429 /// turning them into the more accessible NodeTypes data structure.
430 ///
431 void InstrSelectorEmitter::ReadNodeTypes() {
432   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("DagNode");
433   DEBUG(std::cerr << "Getting node types: ");
434   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
435     Record *Node = Nodes[i];
436     
437     // Translate the return type...
438     NodeType::ArgResultTypes RetTy =
439       NodeType::Translate(Node->getValueAsDef("RetType"));
440
441     // Translate the arguments...
442     ListInit *Args = Node->getValueAsListInit("ArgTypes");
443     std::vector<NodeType::ArgResultTypes> ArgTypes;
444
445     for (unsigned a = 0, e = Args->getSize(); a != e; ++a) {
446       if (DefInit *DI = dynamic_cast<DefInit*>(Args->getElement(a)))
447         ArgTypes.push_back(NodeType::Translate(DI->getDef()));
448       else
449         throw "In node " + Node->getName() + ", argument is not a Def!";
450
451       if (a == 0 && ArgTypes.back() == NodeType::Arg0)
452         throw "In node " + Node->getName() + ", arg 0 cannot have type 'arg0'!";
453       if (a == 1 && ArgTypes.back() == NodeType::Arg1)
454         throw "In node " + Node->getName() + ", arg 1 cannot have type 'arg1'!";
455     }
456     if ((RetTy == NodeType::Arg0 && Args->getSize() == 0) ||
457         (RetTy == NodeType::Arg1 && Args->getSize() < 2))
458       throw "In node " + Node->getName() +
459             ", invalid return type for node with this many operands!";
460
461     // Add the node type mapping now...
462     NodeTypes[Node] = NodeType(RetTy, ArgTypes);
463     DEBUG(std::cerr << Node->getName() << ", ");
464   }
465   DEBUG(std::cerr << "DONE!\n");
466 }
467
468 Pattern *InstrSelectorEmitter::ReadNonterminal(Record *R) {
469   Pattern *&P = Patterns[R];
470   if (P) return P;  // Don't reread it!
471
472   DagInit *DI = R->getValueAsDag("Pattern");
473   P = new Pattern(Pattern::Nonterminal, DI, R, *this);
474   DEBUG(std::cerr << "Parsed " << *P << "\n");
475   return P;
476 }
477
478
479 // ReadNonTerminals - Read in all nonterminals and incorporate them into our
480 // pattern database.
481 void InstrSelectorEmitter::ReadNonterminals() {
482   std::vector<Record*> NTs = Records.getAllDerivedDefinitions("Nonterminal");
483   for (unsigned i = 0, e = NTs.size(); i != e; ++i)
484     ReadNonterminal(NTs[i]);
485 }
486
487
488 /// ReadInstructionPatterns - Read in all subclasses of Instruction, and process
489 /// those with a useful Pattern field.
490 ///
491 void InstrSelectorEmitter::ReadInstructionPatterns() {
492   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
493   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
494     Record *Inst = Insts[i];
495     if (DagInit *DI = dynamic_cast<DagInit*>(Inst->getValueInit("Pattern"))) {
496       Patterns[Inst] = new Pattern(Pattern::Instruction, DI, Inst, *this);
497       DEBUG(std::cerr << "Parsed " << *Patterns[Inst] << "\n");
498     }
499   }
500 }
501
502 /// ReadExpanderPatterns - Read in all expander patterns...
503 ///
504 void InstrSelectorEmitter::ReadExpanderPatterns() {
505   std::vector<Record*> Expanders = Records.getAllDerivedDefinitions("Expander");
506   for (unsigned i = 0, e = Expanders.size(); i != e; ++i) {
507     Record *Expander = Expanders[i];
508     DagInit *DI = Expander->getValueAsDag("Pattern");
509     Patterns[Expander] = new Pattern(Pattern::Expander, DI, Expander, *this);
510     DEBUG(std::cerr << "Parsed " << *Patterns[Expander] << "\n");
511   }
512 }
513
514
515 // InstantiateNonterminals - Instantiate any unresolved nonterminals with
516 // information from the context that they are used in.
517 //
518 void InstrSelectorEmitter::InstantiateNonterminals() {
519   DEBUG(std::cerr << "Instantiating nonterminals:\n");
520   for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
521          E = Patterns.end(); I != E; ++I)
522     if (I->second->isResolved())
523       I->second->InstantiateNonterminals();
524 }
525
526 /// InstantiateNonterminal - This method takes the nonterminal specified by
527 /// NT, which should not be completely resolved, clones it, applies ResultTy
528 /// to its root, then runs the type inference stuff on it.  This should
529 /// produce a newly resolved nonterminal, which we make a record for and
530 /// return.  To be extra fancy and efficient, this only makes one clone for
531 /// each type it is instantiated with.
532 Record *InstrSelectorEmitter::InstantiateNonterminal(Pattern *NT,
533                                                      MVT::ValueType ResultTy) {
534   assert(!NT->isResolved() && "Nonterminal is already resolved!");
535
536   // Check to see if we have already instantiated this pair...
537   Record* &Slot = InstantiatedNTs[std::make_pair(NT, ResultTy)];
538   if (Slot) return Slot;
539   
540   Record *New = new Record(NT->getRecord()->getName()+"_"+getName(ResultTy));
541
542   // Copy over the superclasses...
543   const std::vector<Record*> &SCs = NT->getRecord()->getSuperClasses();
544   for (unsigned i = 0, e = SCs.size(); i != e; ++i)
545     New->addSuperClass(SCs[i]);
546
547   DEBUG(std::cerr << "  Nonterminal '" << NT->getRecord()->getName()
548                   << "' for type '" << getName(ResultTy) << "', producing '"
549                   << New->getName() << "'\n");
550
551   // Copy the pattern...
552   Pattern *NewPat = NT->clone(New);
553
554   // Apply the type to the root...
555   NewPat->getTree()->updateNodeType(ResultTy, New->getName());
556
557   // Infer types...
558   NewPat->InferAllTypes();
559
560   // Make sure everything is good to go now...
561   if (!NewPat->isResolved())
562     NewPat->error("Instantiating nonterminal did not resolve all types!");
563
564   // Add the pattern to the patterns map, add the record to the RecordKeeper,
565   // return the new record.
566   Patterns[New] = NewPat;
567   Records.addDef(New);
568   return Slot = New;
569 }
570
571 // CalculateComputableValues - Fill in the ComputableValues map through
572 // analysis of the patterns we are playing with.
573 void InstrSelectorEmitter::CalculateComputableValues() {
574   // Loop over all of the patterns, adding them to the ComputableValues map
575   for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
576          E = Patterns.end(); I != E; ++I)
577     if (I->second->isResolved()) {
578       // We don't want to add patterns like R32 = R32.  This is a hack working
579       // around a special case of a general problem, but for now we explicitly
580       // forbid these patterns.  They can never match anyway.
581       Pattern *P = I->second;
582       if (!P->getResult() || !P->getTree()->isLeaf() ||
583           P->getResult() != P->getTree()->getValueRecord())
584         ComputableValues.addPattern(P);
585     }
586 }
587
588 #if 0
589 // MoveIdenticalPatterns - Given a tree pattern 'P', move all of the tree
590 // patterns which have the same top-level structure as P from the 'From' list to
591 // the 'To' list.
592 static void MoveIdenticalPatterns(TreePatternNode *P,
593                     std::vector<std::pair<Pattern*, TreePatternNode*> > &From,
594                     std::vector<std::pair<Pattern*, TreePatternNode*> > &To) {
595   assert(!P->isLeaf() && "All leaves are identical!");
596
597   const std::vector<TreePatternNode*> &PChildren = P->getChildren();
598   for (unsigned i = 0; i != From.size(); ++i) {
599     TreePatternNode *N = From[i].second;
600     assert(P->getOperator() == N->getOperator() &&"Differing operators?");
601     assert(PChildren.size() == N->getChildren().size() &&
602            "Nodes with different arity??");
603     bool isDifferent = false;
604     for (unsigned c = 0, e = PChildren.size(); c != e; ++c) {
605       TreePatternNode *PC = PChildren[c];
606       TreePatternNode *NC = N->getChild(c);
607       if (PC->isLeaf() != NC->isLeaf()) {
608         isDifferent = true;
609         break;
610       }
611
612       if (!PC->isLeaf()) {
613         if (PC->getOperator() != NC->getOperator()) {
614           isDifferent = true;
615           break;
616         }
617       } else {  // It's a leaf!
618         if (PC->getValueRecord() != NC->getValueRecord()) {
619           isDifferent = true;
620           break;
621         }
622       }
623     }
624     // If it's the same as the reference one, move it over now...
625     if (!isDifferent) {
626       To.push_back(std::make_pair(From[i].first, N));
627       From.erase(From.begin()+i);
628       --i;   // Don't skip an entry...
629     }
630   }
631 }
632 #endif
633
634 static std::string getNodeName(Record *R) {
635   RecordVal *RV = R->getValue("EnumName");
636   if (RV)
637     if (Init *I = RV->getValue())
638       if (StringInit *SI = dynamic_cast<StringInit*>(I))
639         return SI->getValue();
640   return R->getName();
641 }
642
643
644 static void EmitPatternPredicates(TreePatternNode *Tree,
645                                   const std::string &VarName, std::ostream &OS){
646   OS << " && " << VarName << "->getNodeType() == ISD::"
647      << getNodeName(Tree->getOperator());
648
649   for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
650     if (!Tree->getChild(c)->isLeaf())
651       EmitPatternPredicates(Tree->getChild(c),
652                             VarName + "->getUse(" + utostr(c)+")", OS);
653 }
654
655 static void EmitPatternCosts(TreePatternNode *Tree, const std::string &VarName,
656                              std::ostream &OS) {
657   for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
658     if (Tree->getChild(c)->isLeaf()) {
659       OS << " + Match_"
660          << Pattern::getSlotName(Tree->getChild(c)->getValueRecord()) << "("
661          << VarName << "->getUse(" << c << "))";
662     } else {
663       EmitPatternCosts(Tree->getChild(c),
664                        VarName + "->getUse(" + utostr(c) + ")", OS);
665     }
666 }
667
668
669 // EmitMatchCosters - Given a list of patterns, which all have the same root
670 // pattern operator, emit an efficient decision tree to decide which one to
671 // pick.  This is structured this way to avoid reevaluations of non-obvious
672 // subexpressions.
673 void InstrSelectorEmitter::EmitMatchCosters(std::ostream &OS,
674            const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
675                                             const std::string &VarPrefix,
676                                             unsigned IndentAmt) {
677   assert(!Patterns.empty() && "No patterns to emit matchers for!");
678   std::string Indent(IndentAmt, ' ');
679   
680   // Load all of the operands of the root node into scalars for fast access
681   const NodeType &ONT = getNodeType(Patterns[0].second->getOperator());
682   for (unsigned i = 0, e = ONT.ArgTypes.size(); i != e; ++i)
683     OS << Indent << "SelectionDAGNode *" << VarPrefix << "_Op" << i
684        << " = N->getUse(" << i << ");\n";
685
686   // Compute the costs of computing the various nonterminals/registers, which
687   // are directly used at this level.
688   OS << "\n" << Indent << "// Operand matching costs...\n";
689   std::set<std::string> ComputedValues;   // Avoid duplicate computations...
690   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
691     TreePatternNode *NParent = Patterns[i].second;
692     for (unsigned c = 0, e = NParent->getNumChildren(); c != e; ++c) {
693       TreePatternNode *N = NParent->getChild(c);
694       if (N->isLeaf()) {
695         Record *VR = N->getValueRecord();
696         const std::string &LeafName = VR->getName();
697         std::string OpName  = VarPrefix + "_Op" + utostr(c);
698         std::string ValName = OpName + "_" + LeafName + "_Cost";
699         if (!ComputedValues.count(ValName)) {
700           OS << Indent << "unsigned " << ValName << " = Match_"
701              << Pattern::getSlotName(VR) << "(" << OpName << ");\n";
702           ComputedValues.insert(ValName);
703         }
704       }
705     }
706   }
707   OS << "\n";
708
709
710   std::string LocCostName = VarPrefix + "_Cost";
711   OS << Indent << "unsigned " << LocCostName << "Min = ~0U >> 1;\n"
712      << Indent << "unsigned " << VarPrefix << "_PatternMin = NoMatchPattern;\n";
713   
714 #if 0
715   // Separate out all of the patterns into groups based on what their top-level
716   // signature looks like...
717   std::vector<std::pair<Pattern*, TreePatternNode*> > PatternsLeft(Patterns);
718   while (!PatternsLeft.empty()) {
719     // Process all of the patterns that have the same signature as the last
720     // element...
721     std::vector<std::pair<Pattern*, TreePatternNode*> > Group;
722     MoveIdenticalPatterns(PatternsLeft.back().second, PatternsLeft, Group);
723     assert(!Group.empty() && "Didn't at least pick the source pattern?");
724
725 #if 0
726     OS << "PROCESSING GROUP:\n";
727     for (unsigned i = 0, e = Group.size(); i != e; ++i)
728       OS << "  " << *Group[i].first << "\n";
729     OS << "\n\n";
730 #endif
731
732     OS << Indent << "{ // ";
733
734     if (Group.size() != 1) {
735       OS << Group.size() << " size group...\n";
736       OS << Indent << "  unsigned " << VarPrefix << "_Pattern = NoMatch;\n";
737     } else {
738       OS << *Group[0].first << "\n";
739       OS << Indent << "  unsigned " << VarPrefix << "_Pattern = "
740          << Group[0].first->getRecord()->getName() << "_Pattern;\n";
741     }
742
743     OS << Indent << "  unsigned " << LocCostName << " = ";
744     if (Group.size() == 1)
745       OS << "1;\n";    // Add inst cost if at individual rec
746     else
747       OS << "0;\n";
748
749     // Loop over all of the operands, adding in their costs...
750     TreePatternNode *N = Group[0].second;
751     const std::vector<TreePatternNode*> &Children = N->getChildren();
752
753     // If necessary, emit conditionals to check for the appropriate tree
754     // structure here...
755     for (unsigned i = 0, e = Children.size(); i != e; ++i) {
756       TreePatternNode *C = Children[i];
757       if (C->isLeaf()) {
758         // We already calculated the cost for this leaf, add it in now...
759         OS << Indent << "  " << LocCostName << " += "
760            << VarPrefix << "_Op" << utostr(i) << "_"
761            << C->getValueRecord()->getName() << "_Cost;\n";
762       } else {
763         // If it's not a leaf, we have to check to make sure that the current
764         // node has the appropriate structure, then recurse into it...
765         OS << Indent << "  if (" << VarPrefix << "_Op" << i
766            << "->getNodeType() == ISD::" << getNodeName(C->getOperator())
767            << ") {\n";
768         std::vector<std::pair<Pattern*, TreePatternNode*> > SubPatterns;
769         for (unsigned n = 0, e = Group.size(); n != e; ++n)
770           SubPatterns.push_back(std::make_pair(Group[n].first,
771                                                Group[n].second->getChild(i)));
772         EmitMatchCosters(OS, SubPatterns, VarPrefix+"_Op"+utostr(i),
773                          IndentAmt + 4);
774         OS << Indent << "  }\n";
775       }
776     }
777
778     // If the cost for this match is less than the minimum computed cost so far,
779     // update the minimum cost and selected pattern.
780     OS << Indent << "  if (" << LocCostName << " < " << LocCostName << "Min) { "
781        << LocCostName << "Min = " << LocCostName << "; " << VarPrefix
782        << "_PatternMin = " << VarPrefix << "_Pattern; }\n";
783     
784     OS << Indent << "}\n";
785   }
786 #endif
787
788   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
789     Pattern *P = Patterns[i].first;
790     TreePatternNode *PTree = P->getTree();
791     unsigned PatternCost = 1;
792
793     // Check to see if there are any non-leaf elements in the pattern.  If so,
794     // we need to emit a predicate for this match.
795     bool AnyNonLeaf = false;
796     for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
797       if (!PTree->getChild(c)->isLeaf()) {
798         AnyNonLeaf = true;
799         break;
800       }
801
802     if (!AnyNonLeaf) {   // No predicate necessary, just output a scope...
803       OS << "  {// " << *P << "\n";
804     } else {
805       // We need to emit a predicate to make sure the tree pattern matches, do
806       // so now...
807       OS << "  if (1";
808       for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
809         if (!PTree->getChild(c)->isLeaf())
810           EmitPatternPredicates(PTree->getChild(c),
811                                 VarPrefix + "_Op" + utostr(c), OS);
812
813       OS << ") {\n    // " << *P << "\n";
814     }
815
816     OS << "    unsigned PatCost = " << PatternCost;
817
818     for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
819       if (PTree->getChild(c)->isLeaf()) {
820         OS << " + " << VarPrefix << "_Op" << c << "_"
821            << PTree->getChild(c)->getValueRecord()->getName() << "_Cost";
822       } else {
823         EmitPatternCosts(PTree->getChild(c), VarPrefix + "_Op" + utostr(c), OS);
824       }
825     OS << ";\n";
826     OS << "    if (PatCost < MinCost) { MinCost = PatCost; Pattern = "
827        << P->getRecord()->getName() << "_Pattern; }\n"
828        << "  }\n";
829   }
830 }
831
832 static void ReduceAllOperands(TreePatternNode *N, const std::string &Name,
833              std::vector<std::pair<TreePatternNode*, std::string> > &Operands,
834                               std::ostream &OS) {
835   if (N->isLeaf()) {
836     // If this is a leaf, register or nonterminal reference...
837     std::string SlotName = Pattern::getSlotName(N->getValueRecord());
838     OS << "    ReducedValue_" << SlotName << " *" << Name << "Val = Reduce_"
839        << SlotName << "(" << Name << ", MBB);\n";
840     Operands.push_back(std::make_pair(N, Name+"Val"));
841   } else if (N->getNumChildren() == 0) {
842     // This is a reference to a leaf tree node, like an immediate or frame
843     // index.
844     if (N->getType() != MVT::isVoid) {
845       std::string SlotName =
846         getNodeName(N->getOperator()) + "_" + getName(N->getType());
847       OS << "    ReducedValue_" << SlotName << " *" << Name << "Val = "
848          << Name << "->getValue<ReducedValue_" << SlotName << ">(ISD::"
849          << SlotName << "_Slot);\n";
850       Operands.push_back(std::make_pair(N, Name+"Val"));
851     }
852   } else {
853     // Otherwise this is an interior node...
854     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
855       std::string ChildName = Name + "_Op" + utostr(i);
856       OS << "    SelectionDAGNode *" << ChildName << " = " << Name
857          << "->getUse(" << i << ");\n";
858       ReduceAllOperands(N->getChild(i), ChildName, Operands, OS);
859     }
860   }
861 }
862
863 /// PrintExpanderOperand - Print out Arg as part of the instruction emission
864 /// process for the expander pattern P.  This argument may be referencing some
865 /// values defined in P, or may just be physical register references or
866 /// something like that.  If PrintArg is true, we are printing out arguments to
867 /// the BuildMI call.  If it is false, we are printing the result register
868 /// name.
869 void InstrSelectorEmitter::PrintExpanderOperand(Init *Arg,
870                                                 const std::string &NameVar,
871                                                 TreePatternNode *ArgDeclNode,
872                                                 Pattern *P, bool PrintArg,
873                                                 std::ostream &OS) {
874   if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
875     Record *Arg = DI->getDef();
876     if (!ArgDeclNode->isLeaf() && ArgDeclNode->getNumChildren() != 0)
877       P->error("Expected leaf node as argument!");
878     Record *ArgDecl = ArgDeclNode->isLeaf() ? ArgDeclNode->getValueRecord() :
879                       ArgDeclNode->getOperator();
880     if (Arg->isSubClassOf("Register")) {
881       // This is a physical register reference... make sure that the instruction
882       // requested a register!
883       if (!ArgDecl->isSubClassOf("RegisterClass"))
884         P->error("Argument mismatch for instruction pattern!");
885
886       // FIXME: This should check to see if the register is in the specified
887       // register class!
888       if (PrintArg) OS << ".addReg(";
889       OS << getQualifiedName(Arg);
890       if (PrintArg) OS << ")";
891       return;
892     } else if (Arg->isSubClassOf("RegisterClass")) {
893       // If this is a symbolic register class reference, we must be using a
894       // named value.
895       if (NameVar.empty()) P->error("Did not specify WHICH register to pass!");
896       if (Arg != ArgDecl) P->error("Instruction pattern mismatch!");
897
898       if (PrintArg) OS << ".addReg(";
899       OS << NameVar;
900       if (PrintArg) OS << ")";
901       return;
902     } else if (Arg->getName() == "frameidx") {
903       if (!PrintArg) P->error("Cannot define a new frameidx value!");
904       OS << ".addFrameIndex(" << NameVar << ")";
905       return;
906     } else if (Arg->getName() == "basicblock") {
907       if (!PrintArg) P->error("Cannot define a new basicblock value!");
908       OS << ".addMBB(" << NameVar << ")";
909       return;
910     }
911     P->error("Unknown operand type '" + Arg->getName() + "' to expander!");
912   } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
913     if (!NameVar.empty())
914       P->error("Illegal to specify a name for a constant initializer arg!");
915
916     // Hack this check to allow R32 values with 0 as the initializer for memory
917     // references... FIXME!
918     if (ArgDeclNode->isLeaf() && II->getValue() == 0 &&
919         ArgDeclNode->getValueRecord()->getName() == "R32") {
920       OS << ".addReg(0)";
921     } else {
922       if (ArgDeclNode->isLeaf() || ArgDeclNode->getOperator()->getName()!="imm")
923         P->error("Illegal immediate int value '" + itostr(II->getValue()) +
924                  "' operand!");
925       OS << ".addZImm(" << II->getValue() << ")";
926     }
927     return;
928   }
929   P->error("Unknown operand type to expander!");
930 }
931
932 static std::string getArgName(Pattern *P, const std::string &ArgName, 
933        const std::vector<std::pair<TreePatternNode*, std::string> > &Operands) {
934   assert(P->getNumArgs() == Operands.size() &&"Argument computation mismatch!");
935   if (ArgName.empty()) return "";
936
937   for (unsigned i = 0, e = P->getNumArgs(); i != e; ++i)
938     if (P->getArgName(i) == ArgName)
939       return Operands[i].second + "->Val";
940
941   if (ArgName == P->getResultName())
942     return "NewReg";
943   P->error("Pattern does not define a value named $" + ArgName + "!");
944   return "";
945 }
946
947
948 void InstrSelectorEmitter::run(std::ostream &OS) {
949   // Type-check all of the node types to ensure we "understand" them.
950   ReadNodeTypes();
951   
952   // Read in all of the nonterminals, instructions, and expanders...
953   ReadNonterminals();
954   ReadInstructionPatterns();
955   ReadExpanderPatterns();
956
957   // Instantiate any unresolved nonterminals with information from the context
958   // that they are used in.
959   InstantiateNonterminals();
960
961   // Clear InstantiatedNTs, we don't need it anymore...
962   InstantiatedNTs.clear();
963
964   DEBUG(std::cerr << "Patterns acquired:\n");
965   for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
966          E = Patterns.end(); I != E; ++I)
967     if (I->second->isResolved())
968       DEBUG(std::cerr << "  " << *I->second << "\n");
969
970   CalculateComputableValues();
971   
972   EmitSourceFileHeader("Instruction Selector for the " + Target.getName() +
973                        " target", OS);
974   OS << "#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n";
975
976   // Output the slot number enums...
977   OS << "\nenum { // Slot numbers...\n"
978      << "  LastBuiltinSlot = ISD::NumBuiltinSlots-1, // Start numbering here\n";
979   for (PatternOrganizer::iterator I = ComputableValues.begin(),
980          E = ComputableValues.end(); I != E; ++I)
981     OS << "  " << I->first << "_Slot,\n";
982   OS << "  NumSlots\n};\n\n// Reduction value typedefs...\n";
983
984   // Output the reduction value typedefs...
985   for (PatternOrganizer::iterator I = ComputableValues.begin(),
986          E = ComputableValues.end(); I != E; ++I) {
987
988     OS << "typedef ReducedValue<unsigned, " << I->first
989        << "_Slot> ReducedValue_" << I->first << ";\n";
990   }
991
992   // Output the pattern enums...
993   OS << "\n\n"
994      << "enum { // Patterns...\n"
995      << "  NotComputed = 0,\n"
996      << "  NoMatchPattern, \n";
997   for (PatternOrganizer::iterator I = ComputableValues.begin(),
998          E = ComputableValues.end(); I != E; ++I) {
999     OS << "  // " << I->first << " patterns...\n";
1000     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1001            E = I->second.end(); J != E; ++J)
1002       for (unsigned i = 0, e = J->second.size(); i != e; ++i)
1003         OS << "  " << J->second[i]->getRecord()->getName() << "_Pattern,\n";
1004   }
1005   OS << "};\n\n";
1006
1007   //===--------------------------------------------------------------------===//
1008   // Emit the class definition...
1009   //
1010   OS << "namespace {\n"
1011      << "  class " << Target.getName() << "ISel {\n"
1012      << "    SelectionDAG &DAG;\n"
1013      << "  public:\n"
1014      << "    X86ISel(SelectionDAG &D) : DAG(D) {}\n"
1015      << "    void generateCode();\n"
1016      << "  private:\n"
1017      << "    unsigned makeAnotherReg(const TargetRegisterClass *RC) {\n"
1018      << "      return DAG.getMachineFunction().getSSARegMap()->createVirt"
1019                                        "ualRegister(RC);\n"
1020      << "    }\n\n"
1021      << "    // DAG matching methods for classes... all of these methods"
1022                                        " return the cost\n"
1023      << "    // of producing a value of the specified class and type, which"
1024                                        " also gets\n"
1025      << "    // added to the DAG node.\n";
1026
1027   // Output all of the matching prototypes for slots...
1028   for (PatternOrganizer::iterator I = ComputableValues.begin(),
1029          E = ComputableValues.end(); I != E; ++I)
1030     OS << "    unsigned Match_" << I->first << "(SelectionDAGNode *N);\n";
1031   OS << "\n    // DAG matching methods for DAG nodes...\n";
1032
1033   // Output all of the matching prototypes for slot/node pairs
1034   for (PatternOrganizer::iterator I = ComputableValues.begin(),
1035          E = ComputableValues.end(); I != E; ++I)
1036     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1037            E = I->second.end(); J != E; ++J)
1038       OS << "    unsigned Match_" << I->first << "_" << getNodeName(J->first)
1039          << "(SelectionDAGNode *N);\n";
1040
1041   // Output all of the dag reduction methods prototypes...
1042   OS << "\n    // DAG reduction methods...\n";
1043   for (PatternOrganizer::iterator I = ComputableValues.begin(),
1044          E = ComputableValues.end(); I != E; ++I)
1045     OS << "    ReducedValue_" << I->first << " *Reduce_" << I->first
1046        << "(SelectionDAGNode *N,\n" << std::string(27+2*I->first.size(), ' ')
1047        << "MachineBasicBlock *MBB);\n";
1048   OS << "  };\n}\n\n";
1049
1050   // Emit the generateCode entry-point...
1051   OS << "void X86ISel::generateCode() {\n"
1052      << "  SelectionDAGNode *Root = DAG.getRoot();\n"
1053      << "  assert(Root->getValueType() == MVT::isVoid && "
1054                                        "\"Root of DAG produces value??\");\n\n"
1055      << "  std::cerr << \"\\n\";\n"
1056      << "  unsigned Cost = Match_Void_void(Root);\n"
1057      << "  if (Cost >= ~0U >> 1) {\n"
1058      << "    std::cerr << \"Match failed!\\n\";\n"
1059      << "    Root->dump();\n"
1060      << "    abort();\n"
1061      << "  }\n\n"
1062      << "  std::cerr << \"Total DAG Cost: \" << Cost << \"\\n\\n\";\n\n"
1063      << "  Reduce_Void_void(Root, 0);\n"
1064      << "}\n\n"
1065      << "//===" << std::string(70, '-') << "===//\n"
1066      << "//  Matching methods...\n"
1067      << "//\n\n";
1068
1069   //===--------------------------------------------------------------------===//
1070   // Emit all of the matcher methods...
1071   //
1072   for (PatternOrganizer::iterator I = ComputableValues.begin(),
1073          E = ComputableValues.end(); I != E; ++I) {
1074     const std::string &SlotName = I->first;
1075     OS << "unsigned " << Target.getName() << "ISel::Match_" << SlotName
1076        << "(SelectionDAGNode *N) {\n"
1077        << "  assert(N->getValueType() == MVT::"
1078        << getEnumName((*I->second.begin()).second[0]->getTree()->getType())
1079        << ");\n" << "  // If we already have a cost available for " << SlotName
1080        << " use it!\n"
1081        << "  if (N->getPatternFor(" << SlotName << "_Slot))\n"
1082        << "    return N->getCostFor(" << SlotName << "_Slot);\n\n"
1083        << "  unsigned Cost;\n"
1084        << "  switch (N->getNodeType()) {\n"
1085        << "  default: Cost = ~0U >> 1;   // Match failed\n"
1086        << "           N->setPatternCostFor(" << SlotName << "_Slot, NoMatchPattern, Cost, NumSlots);\n"
1087        << "           break;\n";
1088
1089     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1090            E = I->second.end(); J != E; ++J)
1091       if (!J->first->isSubClassOf("Nonterminal"))
1092         OS << "  case ISD::" << getNodeName(J->first) << ":\tCost = Match_"
1093            << SlotName << "_" << getNodeName(J->first) << "(N); break;\n";
1094     OS << "  }\n";  // End of the switch statement
1095
1096     // Emit any patterns which have a nonterminal leaf as the RHS.  These may
1097     // match multiple root nodes, so they cannot be handled with the switch...
1098     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1099            E = I->second.end(); J != E; ++J)
1100       if (J->first->isSubClassOf("Nonterminal")) {
1101         OS << "  unsigned " << J->first->getName() << "_Cost = Match_"
1102            << getNodeName(J->first) << "(N);\n"
1103            << "  if (" << getNodeName(J->first) << "_Cost < Cost) Cost = "
1104            << getNodeName(J->first) << "_Cost;\n";
1105       }
1106
1107     OS << "  return Cost;\n}\n\n";
1108
1109     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1110            E = I->second.end(); J != E; ++J) {
1111       Record *Operator = J->first;
1112       bool isNonterm = Operator->isSubClassOf("Nonterminal");
1113       if (!isNonterm) {
1114         OS << "unsigned " << Target.getName() << "ISel::Match_";
1115         if (!isNonterm) OS << SlotName << "_";
1116         OS << getNodeName(Operator) << "(SelectionDAGNode *N) {\n"
1117            << "  unsigned Pattern = NoMatchPattern;\n"
1118            << "  unsigned MinCost = ~0U >> 1;\n";
1119         
1120         std::vector<std::pair<Pattern*, TreePatternNode*> > Patterns;
1121         for (unsigned i = 0, e = J->second.size(); i != e; ++i)
1122           Patterns.push_back(std::make_pair(J->second[i],
1123                                             J->second[i]->getTree()));
1124         EmitMatchCosters(OS, Patterns, "N", 2);
1125         
1126         OS << "\n  N->setPatternCostFor(" << SlotName
1127            << "_Slot, Pattern, MinCost, NumSlots);\n"
1128            << "  return MinCost;\n"
1129            << "}\n";
1130       }
1131     }
1132   }
1133
1134   //===--------------------------------------------------------------------===//
1135   // Emit all of the reducer methods...
1136   //
1137   OS << "\n\n//===" << std::string(70, '-') << "===//\n"
1138      << "// Reducer methods...\n"
1139      << "//\n";
1140
1141   for (PatternOrganizer::iterator I = ComputableValues.begin(),
1142          E = ComputableValues.end(); I != E; ++I) {
1143     const std::string &SlotName = I->first;
1144     OS << "ReducedValue_" << SlotName << " *" << Target.getName()
1145        << "ISel::Reduce_" << SlotName
1146        << "(SelectionDAGNode *N, MachineBasicBlock *MBB) {\n"
1147        << "  ReducedValue_" << SlotName << " *Val = N->hasValue<ReducedValue_"
1148        << SlotName << ">(" << SlotName << "_Slot);\n"
1149        << "  if (Val) return Val;\n"
1150        << "  if (N->getBB()) MBB = N->getBB();\n\n"
1151        << "  switch (N->getPatternFor(" << SlotName << "_Slot)) {\n";
1152
1153     // Loop over all of the patterns that can produce a value for this slot...
1154     PatternOrganizer::NodesForSlot &NodesForSlot = I->second;
1155     for (PatternOrganizer::NodesForSlot::iterator J = NodesForSlot.begin(),
1156            E = NodesForSlot.end(); J != E; ++J)
1157       for (unsigned i = 0, e = J->second.size(); i != e; ++i) {
1158         Pattern *P = J->second[i];
1159         OS << "  case " << P->getRecord()->getName() << "_Pattern: {\n"
1160            << "    // " << *P << "\n";
1161         // Loop over the operands, reducing them...
1162         std::vector<std::pair<TreePatternNode*, std::string> > Operands;
1163         ReduceAllOperands(P->getTree(), "N", Operands, OS);
1164         
1165         // Now that we have reduced all of our operands, and have the values
1166         // that reduction produces, perform the reduction action for this
1167         // pattern.
1168         std::string Result;
1169
1170         // If the pattern produces a register result, generate a new register
1171         // now.
1172         if (Record *R = P->getResult()) {
1173           assert(R->isSubClassOf("RegisterClass") &&
1174                  "Only handle register class results so far!");
1175           OS << "    unsigned NewReg = makeAnotherReg(" << Target.getName()
1176              << "::" << R->getName() << "RegisterClass);\n";
1177           Result = "NewReg";
1178           DEBUG(OS << "    std::cerr << \"%reg\" << NewReg << \" =\t\";\n");
1179         } else {
1180           DEBUG(OS << "    std::cerr << \"\t\t\";\n");
1181           Result = "0";
1182         }
1183
1184         // Print out the pattern that matched...
1185         DEBUG(OS << "    std::cerr << \"  " << P->getRecord()->getName() <<'"');
1186         DEBUG(for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1187                 if (Operands[i].first->isLeaf()) {
1188                   Record *RV = Operands[i].first->getValueRecord();
1189                   assert(RV->isSubClassOf("RegisterClass") &&
1190                          "Only handles registers here so far!");
1191                   OS << " << \" %reg\" << " << Operands[i].second
1192                      << "->Val";
1193                 } else {
1194                   OS << " << ' ' << " << Operands[i].second
1195                      << "->Val";
1196                 });
1197         DEBUG(OS << " << \"\\n\";\n");
1198         
1199         // Generate the reduction code appropriate to the particular type of
1200         // pattern that this is...
1201         switch (P->getPatternType()) {
1202         case Pattern::Instruction:
1203           // Instruction patterns just emit a single MachineInstr, using BuildMI
1204           OS << "    BuildMI(MBB, " << Target.getName() << "::"
1205              << P->getRecord()->getName() << ", " << Operands.size();
1206           if (P->getResult()) OS << ", NewReg";
1207           OS << ")";
1208
1209           for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
1210             TreePatternNode *Op = Operands[i].first;
1211             if (Op->isLeaf()) {
1212               Record *RV = Op->getValueRecord();
1213               assert(RV->isSubClassOf("RegisterClass") &&
1214                      "Only handles registers here so far!");
1215               OS << ".addReg(" << Operands[i].second << "->Val)";
1216             } else if (Op->getOperator()->getName() == "imm") {
1217               OS << ".addZImm(" << Operands[i].second << "->Val)";
1218             } else if (Op->getOperator()->getName() == "basicblock") {
1219               OS << ".addMBB(" << Operands[i].second << "->Val)";
1220             } else {
1221               assert(0 && "Unknown value type!");
1222             }
1223           }
1224           OS << ";\n";
1225           break;
1226         case Pattern::Expander: {
1227           // Expander patterns emit one machine instr for each instruction in
1228           // the list of instructions expanded to.
1229           ListInit *Insts = P->getRecord()->getValueAsListInit("Result");
1230           for (unsigned IN = 0, e = Insts->getSize(); IN != e; ++IN) {
1231             DagInit *DIInst = dynamic_cast<DagInit*>(Insts->getElement(IN));
1232             if (!DIInst) P->error("Result list must contain instructions!");
1233             Record *InstRec  = DIInst->getNodeType();
1234             Pattern *InstPat = getPattern(InstRec);
1235             if (!InstPat || InstPat->getPatternType() != Pattern::Instruction)
1236               P->error("Instruction list must contain Instruction patterns!");
1237             
1238             bool hasResult = InstPat->getResult() != 0;
1239             if (InstPat->getNumArgs() != DIInst->getNumArgs()-hasResult) {
1240               P->error("Incorrect number of arguments specified for inst '" +
1241                        InstPat->getRecord()->getName() + "' in result list!");
1242             }
1243
1244             // Start emission of the instruction...
1245             OS << "    BuildMI(MBB, " << Target.getName() << "::"
1246                << InstRec->getName() << ", "
1247                << DIInst->getNumArgs()-hasResult;
1248             // Emit register result if necessary..
1249             if (hasResult) {
1250               std::string ArgNameVal =
1251                 getArgName(P, DIInst->getArgName(0), Operands);
1252               PrintExpanderOperand(DIInst->getArg(0), ArgNameVal,
1253                                    InstPat->getResultNode(), P, false,
1254                                    OS << ", ");
1255             }
1256             OS << ")";
1257
1258             for (unsigned i = hasResult, e = DIInst->getNumArgs(); i != e; ++i){
1259               std::string ArgNameVal =
1260                 getArgName(P, DIInst->getArgName(i), Operands);
1261
1262               PrintExpanderOperand(DIInst->getArg(i), ArgNameVal,
1263                                    InstPat->getArg(i-hasResult), P, true, OS);
1264             }
1265
1266             OS << ";\n";
1267           }
1268           break;
1269         }
1270         default:
1271           assert(0 && "Reduction of this type of pattern not implemented!");
1272         }
1273
1274         OS << "    Val = new ReducedValue_" << SlotName << "(" << Result<<");\n"
1275            << "    break;\n"
1276            << "  }\n";
1277       }
1278     
1279     
1280     OS << "  default: assert(0 && \"Unknown " << SlotName << " pattern!\");\n"
1281        << "  }\n\n  N->addValue(Val);  // Do not ever recalculate this\n"
1282        << "  return Val;\n}\n\n";
1283   }
1284 }
1285