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