8bc8f611dd2b50420d75d7cf54b260f23b0998c1
[oota-llvm.git] / support / tools / 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   return "";
405 }
406
407 //===----------------------------------------------------------------------===//
408 // PatternOrganizer implementation
409 //
410
411 /// addPattern - Add the specified pattern to the appropriate location in the
412 /// collection.
413 void PatternOrganizer::addPattern(Pattern *P) {
414   NodesForSlot &Nodes = AllPatterns[P->getSlotName()];
415   if (!P->getTree()->isLeaf())
416     Nodes[P->getTree()->getOperator()].push_back(P);
417   else {
418     // Right now we only support DefInit's with node types...
419     Nodes[P->getTree()->getValueRecord()].push_back(P);
420   }
421 }
422
423
424
425 //===----------------------------------------------------------------------===//
426 // InstrSelectorEmitter implementation
427 //
428
429 /// ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
430 /// turning them into the more accessible NodeTypes data structure.
431 ///
432 void InstrSelectorEmitter::ReadNodeTypes() {
433   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("DagNode");
434   DEBUG(std::cerr << "Getting node types: ");
435   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
436     Record *Node = Nodes[i];
437     
438     // Translate the return type...
439     NodeType::ArgResultTypes RetTy =
440       NodeType::Translate(Node->getValueAsDef("RetType"));
441
442     // Translate the arguments...
443     ListInit *Args = Node->getValueAsListInit("ArgTypes");
444     std::vector<NodeType::ArgResultTypes> ArgTypes;
445
446     for (unsigned a = 0, e = Args->getSize(); a != e; ++a) {
447       if (DefInit *DI = dynamic_cast<DefInit*>(Args->getElement(a)))
448         ArgTypes.push_back(NodeType::Translate(DI->getDef()));
449       else
450         throw "In node " + Node->getName() + ", argument is not a Def!";
451
452       if (a == 0 && ArgTypes.back() == NodeType::Arg0)
453         throw "In node " + Node->getName() + ", arg 0 cannot have type 'arg0'!";
454       if (a == 1 && ArgTypes.back() == NodeType::Arg1)
455         throw "In node " + Node->getName() + ", arg 1 cannot have type 'arg1'!";
456     }
457     if ((RetTy == NodeType::Arg0 && Args->getSize() == 0) ||
458         (RetTy == NodeType::Arg1 && Args->getSize() < 2))
459       throw "In node " + Node->getName() +
460             ", invalid return type for node with this many operands!";
461
462     // Add the node type mapping now...
463     NodeTypes[Node] = NodeType(RetTy, ArgTypes);
464     DEBUG(std::cerr << Node->getName() << ", ");
465   }
466   DEBUG(std::cerr << "DONE!\n");
467 }
468
469 Pattern *InstrSelectorEmitter::ReadNonterminal(Record *R) {
470   Pattern *&P = Patterns[R];
471   if (P) return P;  // Don't reread it!
472
473   DagInit *DI = R->getValueAsDag("Pattern");
474   P = new Pattern(Pattern::Nonterminal, DI, R, *this);
475   DEBUG(std::cerr << "Parsed " << *P << "\n");
476   return P;
477 }
478
479
480 // ReadNonTerminals - Read in all nonterminals and incorporate them into our
481 // pattern database.
482 void InstrSelectorEmitter::ReadNonterminals() {
483   std::vector<Record*> NTs = Records.getAllDerivedDefinitions("Nonterminal");
484   for (unsigned i = 0, e = NTs.size(); i != e; ++i)
485     ReadNonterminal(NTs[i]);
486 }
487
488
489 /// ReadInstructionPatterns - Read in all subclasses of Instruction, and process
490 /// those with a useful Pattern field.
491 ///
492 void InstrSelectorEmitter::ReadInstructionPatterns() {
493   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
494   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
495     Record *Inst = Insts[i];
496     if (DagInit *DI = dynamic_cast<DagInit*>(Inst->getValueInit("Pattern"))) {
497       Patterns[Inst] = new Pattern(Pattern::Instruction, DI, Inst, *this);
498       DEBUG(std::cerr << "Parsed " << *Patterns[Inst] << "\n");
499     }
500   }
501 }
502
503 /// ReadExpanderPatterns - Read in all expander patterns...
504 ///
505 void InstrSelectorEmitter::ReadExpanderPatterns() {
506   std::vector<Record*> Expanders = Records.getAllDerivedDefinitions("Expander");
507   for (unsigned i = 0, e = Expanders.size(); i != e; ++i) {
508     Record *Expander = Expanders[i];
509     DagInit *DI = Expander->getValueAsDag("Pattern");
510     Patterns[Expander] = new Pattern(Pattern::Expander, DI, Expander, *this);
511     DEBUG(std::cerr << "Parsed " << *Patterns[Expander] << "\n");
512   }
513 }
514
515
516 // InstantiateNonterminals - Instantiate any unresolved nonterminals with
517 // information from the context that they are used in.
518 //
519 void InstrSelectorEmitter::InstantiateNonterminals() {
520   DEBUG(std::cerr << "Instantiating nonterminals:\n");
521   for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
522          E = Patterns.end(); I != E; ++I)
523     if (I->second->isResolved())
524       I->second->InstantiateNonterminals();
525 }
526
527 /// InstantiateNonterminal - This method takes the nonterminal specified by
528 /// NT, which should not be completely resolved, clones it, applies ResultTy
529 /// to its root, then runs the type inference stuff on it.  This should
530 /// produce a newly resolved nonterminal, which we make a record for and
531 /// return.  To be extra fancy and efficient, this only makes one clone for
532 /// each type it is instantiated with.
533 Record *InstrSelectorEmitter::InstantiateNonterminal(Pattern *NT,
534                                                      MVT::ValueType ResultTy) {
535   assert(!NT->isResolved() && "Nonterminal is already resolved!");
536
537   // Check to see if we have already instantiated this pair...
538   Record* &Slot = InstantiatedNTs[std::make_pair(NT, ResultTy)];
539   if (Slot) return Slot;
540   
541   Record *New = new Record(NT->getRecord()->getName()+"_"+getName(ResultTy));
542
543   // Copy over the superclasses...
544   const std::vector<Record*> &SCs = NT->getRecord()->getSuperClasses();
545   for (unsigned i = 0, e = SCs.size(); i != e; ++i)
546     New->addSuperClass(SCs[i]);
547
548   DEBUG(std::cerr << "  Nonterminal '" << NT->getRecord()->getName()
549                   << "' for type '" << getName(ResultTy) << "', producing '"
550                   << New->getName() << "'\n");
551
552   // Copy the pattern...
553   Pattern *NewPat = NT->clone(New);
554
555   // Apply the type to the root...
556   NewPat->getTree()->updateNodeType(ResultTy, New->getName());
557
558   // Infer types...
559   NewPat->InferAllTypes();
560
561   // Make sure everything is good to go now...
562   if (!NewPat->isResolved())
563     NewPat->error("Instantiating nonterminal did not resolve all types!");
564
565   // Add the pattern to the patterns map, add the record to the RecordKeeper,
566   // return the new record.
567   Patterns[New] = NewPat;
568   Records.addDef(New);
569   return Slot = New;
570 }
571
572 // CalculateComputableValues - Fill in the ComputableValues map through
573 // analysis of the patterns we are playing with.
574 void InstrSelectorEmitter::CalculateComputableValues() {
575   // Loop over all of the patterns, adding them to the ComputableValues map
576   for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
577          E = Patterns.end(); I != E; ++I)
578     if (I->second->isResolved()) {
579       // We don't want to add patterns like R32 = R32.  This is a hack working
580       // around a special case of a general problem, but for now we explicitly
581       // forbid these patterns.  They can never match anyway.
582       Pattern *P = I->second;
583       if (!P->getResult() || !P->getTree()->isLeaf() ||
584           P->getResult() != P->getTree()->getValueRecord())
585         ComputableValues.addPattern(P);
586     }
587 }
588
589 #if 0
590 // MoveIdenticalPatterns - Given a tree pattern 'P', move all of the tree
591 // patterns which have the same top-level structure as P from the 'From' list to
592 // the 'To' list.
593 static void MoveIdenticalPatterns(TreePatternNode *P,
594                     std::vector<std::pair<Pattern*, TreePatternNode*> > &From,
595                     std::vector<std::pair<Pattern*, TreePatternNode*> > &To) {
596   assert(!P->isLeaf() && "All leaves are identical!");
597
598   const std::vector<TreePatternNode*> &PChildren = P->getChildren();
599   for (unsigned i = 0; i != From.size(); ++i) {
600     TreePatternNode *N = From[i].second;
601     assert(P->getOperator() == N->getOperator() &&"Differing operators?");
602     assert(PChildren.size() == N->getChildren().size() &&
603            "Nodes with different arity??");
604     bool isDifferent = false;
605     for (unsigned c = 0, e = PChildren.size(); c != e; ++c) {
606       TreePatternNode *PC = PChildren[c];
607       TreePatternNode *NC = N->getChild(c);
608       if (PC->isLeaf() != NC->isLeaf()) {
609         isDifferent = true;
610         break;
611       }
612
613       if (!PC->isLeaf()) {
614         if (PC->getOperator() != NC->getOperator()) {
615           isDifferent = true;
616           break;
617         }
618       } else {  // It's a leaf!
619         if (PC->getValueRecord() != NC->getValueRecord()) {
620           isDifferent = true;
621           break;
622         }
623       }
624     }
625     // If it's the same as the reference one, move it over now...
626     if (!isDifferent) {
627       To.push_back(std::make_pair(From[i].first, N));
628       From.erase(From.begin()+i);
629       --i;   // Don't skip an entry...
630     }
631   }
632 }
633 #endif
634
635 static std::string getNodeName(Record *R) {
636   RecordVal *RV = R->getValue("EnumName");
637   if (RV)
638     if (Init *I = RV->getValue())
639       if (StringInit *SI = dynamic_cast<StringInit*>(I))
640         return SI->getValue();
641   return R->getName();
642 }
643
644
645 static void EmitPatternPredicates(TreePatternNode *Tree,
646                                   const std::string &VarName, std::ostream &OS){
647   OS << " && " << VarName << "->getNodeType() == ISD::"
648      << getNodeName(Tree->getOperator());
649
650   for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
651     if (!Tree->getChild(c)->isLeaf())
652       EmitPatternPredicates(Tree->getChild(c),
653                             VarName + "->getUse(" + utostr(c)+")", OS);
654 }
655
656 static void EmitPatternCosts(TreePatternNode *Tree, const std::string &VarName,
657                              std::ostream &OS) {
658   for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
659     if (Tree->getChild(c)->isLeaf()) {
660       OS << " + Match_"
661          << Pattern::getSlotName(Tree->getChild(c)->getValueRecord()) << "("
662          << VarName << "->getUse(" << c << "))";
663     } else {
664       EmitPatternCosts(Tree->getChild(c),
665                        VarName + "->getUse(" + utostr(c) + ")", OS);
666     }
667 }
668
669
670 // EmitMatchCosters - Given a list of patterns, which all have the same root
671 // pattern operator, emit an efficient decision tree to decide which one to
672 // pick.  This is structured this way to avoid reevaluations of non-obvious
673 // subexpressions.
674 void InstrSelectorEmitter::EmitMatchCosters(std::ostream &OS,
675            const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
676                                             const std::string &VarPrefix,
677                                             unsigned IndentAmt) {
678   assert(!Patterns.empty() && "No patterns to emit matchers for!");
679   std::string Indent(IndentAmt, ' ');
680   
681   // Load all of the operands of the root node into scalars for fast access
682   const NodeType &ONT = getNodeType(Patterns[0].second->getOperator());
683   for (unsigned i = 0, e = ONT.ArgTypes.size(); i != e; ++i)
684     OS << Indent << "SelectionDAGNode *" << VarPrefix << "_Op" << i
685        << " = N->getUse(" << i << ");\n";
686
687   // Compute the costs of computing the various nonterminals/registers, which
688   // are directly used at this level.
689   OS << "\n" << Indent << "// Operand matching costs...\n";
690   std::set<std::string> ComputedValues;   // Avoid duplicate computations...
691   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
692     TreePatternNode *NParent = Patterns[i].second;
693     for (unsigned c = 0, e = NParent->getNumChildren(); c != e; ++c) {
694       TreePatternNode *N = NParent->getChild(c);
695       if (N->isLeaf()) {
696         Record *VR = N->getValueRecord();
697         const std::string &LeafName = VR->getName();
698         std::string OpName  = VarPrefix + "_Op" + utostr(c);
699         std::string ValName = OpName + "_" + LeafName + "_Cost";
700         if (!ComputedValues.count(ValName)) {
701           OS << Indent << "unsigned " << ValName << " = Match_"
702              << Pattern::getSlotName(VR) << "(" << OpName << ");\n";
703           ComputedValues.insert(ValName);
704         }
705       }
706     }
707   }
708   OS << "\n";
709
710
711   std::string LocCostName = VarPrefix + "_Cost";
712   OS << Indent << "unsigned " << LocCostName << "Min = ~0U >> 1;\n"
713      << Indent << "unsigned " << VarPrefix << "_PatternMin = NoMatchPattern;\n";
714   
715 #if 0
716   // Separate out all of the patterns into groups based on what their top-level
717   // signature looks like...
718   std::vector<std::pair<Pattern*, TreePatternNode*> > PatternsLeft(Patterns);
719   while (!PatternsLeft.empty()) {
720     // Process all of the patterns that have the same signature as the last
721     // element...
722     std::vector<std::pair<Pattern*, TreePatternNode*> > Group;
723     MoveIdenticalPatterns(PatternsLeft.back().second, PatternsLeft, Group);
724     assert(!Group.empty() && "Didn't at least pick the source pattern?");
725
726 #if 0
727     OS << "PROCESSING GROUP:\n";
728     for (unsigned i = 0, e = Group.size(); i != e; ++i)
729       OS << "  " << *Group[i].first << "\n";
730     OS << "\n\n";
731 #endif
732
733     OS << Indent << "{ // ";
734
735     if (Group.size() != 1) {
736       OS << Group.size() << " size group...\n";
737       OS << Indent << "  unsigned " << VarPrefix << "_Pattern = NoMatch;\n";
738     } else {
739       OS << *Group[0].first << "\n";
740       OS << Indent << "  unsigned " << VarPrefix << "_Pattern = "
741          << Group[0].first->getRecord()->getName() << "_Pattern;\n";
742     }
743
744     OS << Indent << "  unsigned " << LocCostName << " = ";
745     if (Group.size() == 1)
746       OS << "1;\n";    // Add inst cost if at individual rec
747     else
748       OS << "0;\n";
749
750     // Loop over all of the operands, adding in their costs...
751     TreePatternNode *N = Group[0].second;
752     const std::vector<TreePatternNode*> &Children = N->getChildren();
753
754     // If necessary, emit conditionals to check for the appropriate tree
755     // structure here...
756     for (unsigned i = 0, e = Children.size(); i != e; ++i) {
757       TreePatternNode *C = Children[i];
758       if (C->isLeaf()) {
759         // We already calculated the cost for this leaf, add it in now...
760         OS << Indent << "  " << LocCostName << " += "
761            << VarPrefix << "_Op" << utostr(i) << "_"
762            << C->getValueRecord()->getName() << "_Cost;\n";
763       } else {
764         // If it's not a leaf, we have to check to make sure that the current
765         // node has the appropriate structure, then recurse into it...
766         OS << Indent << "  if (" << VarPrefix << "_Op" << i
767            << "->getNodeType() == ISD::" << getNodeName(C->getOperator())
768            << ") {\n";
769         std::vector<std::pair<Pattern*, TreePatternNode*> > SubPatterns;
770         for (unsigned n = 0, e = Group.size(); n != e; ++n)
771           SubPatterns.push_back(std::make_pair(Group[n].first,
772                                                Group[n].second->getChild(i)));
773         EmitMatchCosters(OS, SubPatterns, VarPrefix+"_Op"+utostr(i),
774                          IndentAmt + 4);
775         OS << Indent << "  }\n";
776       }
777     }
778
779     // If the cost for this match is less than the minimum computed cost so far,
780     // update the minimum cost and selected pattern.
781     OS << Indent << "  if (" << LocCostName << " < " << LocCostName << "Min) { "
782        << LocCostName << "Min = " << LocCostName << "; " << VarPrefix
783        << "_PatternMin = " << VarPrefix << "_Pattern; }\n";
784     
785     OS << Indent << "}\n";
786   }
787 #endif
788
789   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
790     Pattern *P = Patterns[i].first;
791     TreePatternNode *PTree = P->getTree();
792     unsigned PatternCost = 1;
793
794     // Check to see if there are any non-leaf elements in the pattern.  If so,
795     // we need to emit a predicate for this match.
796     bool AnyNonLeaf = false;
797     for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
798       if (!PTree->getChild(c)->isLeaf()) {
799         AnyNonLeaf = true;
800         break;
801       }
802
803     if (!AnyNonLeaf) {   // No predicate necessary, just output a scope...
804       OS << "  {// " << *P << "\n";
805     } else {
806       // We need to emit a predicate to make sure the tree pattern matches, do
807       // so now...
808       OS << "  if (1";
809       for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
810         if (!PTree->getChild(c)->isLeaf())
811           EmitPatternPredicates(PTree->getChild(c),
812                                 VarPrefix + "_Op" + utostr(c), OS);
813
814       OS << ") {\n    // " << *P << "\n";
815     }
816
817     OS << "    unsigned PatCost = " << PatternCost;
818
819     for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
820       if (PTree->getChild(c)->isLeaf()) {
821         OS << " + " << VarPrefix << "_Op" << c << "_"
822            << PTree->getChild(c)->getValueRecord()->getName() << "_Cost";
823       } else {
824         EmitPatternCosts(PTree->getChild(c), VarPrefix + "_Op" + utostr(c), OS);
825       }
826     OS << ";\n";
827     OS << "    if (PatCost < MinCost) { MinCost = PatCost; Pattern = "
828        << P->getRecord()->getName() << "_Pattern; }\n"
829        << "  }\n";
830   }
831 }
832
833 static void ReduceAllOperands(TreePatternNode *N, const std::string &Name,
834              std::vector<std::pair<TreePatternNode*, std::string> > &Operands,
835                               std::ostream &OS) {
836   if (N->isLeaf()) {
837     // If this is a leaf, register or nonterminal reference...
838     std::string SlotName = Pattern::getSlotName(N->getValueRecord());
839     OS << "    ReducedValue_" << SlotName << " *" << Name << "Val = Reduce_"
840        << SlotName << "(" << Name << ", MBB);\n";
841     Operands.push_back(std::make_pair(N, Name+"Val"));
842   } else if (N->getNumChildren() == 0) {
843     // This is a reference to a leaf tree node, like an immediate or frame
844     // index.
845     if (N->getType() != MVT::isVoid) {
846       std::string SlotName =
847         getNodeName(N->getOperator()) + "_" + getName(N->getType());
848       OS << "    ReducedValue_" << SlotName << " *" << Name << "Val = "
849          << Name << "->getValue<ReducedValue_" << SlotName << ">(ISD::"
850          << SlotName << "_Slot);\n";
851       Operands.push_back(std::make_pair(N, Name+"Val"));
852     }
853   } else {
854     // Otherwise this is an interior node...
855     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
856       std::string ChildName = Name + "_Op" + utostr(i);
857       OS << "    SelectionDAGNode *" << ChildName << " = " << Name
858          << "->getUse(" << i << ");\n";
859       ReduceAllOperands(N->getChild(i), ChildName, Operands, OS);
860     }
861   }
862 }
863
864 /// PrintExpanderOperand - Print out Arg as part of the instruction emission
865 /// process for the expander pattern P.  This argument may be referencing some
866 /// values defined in P, or may just be physical register references or
867 /// something like that.  If PrintArg is true, we are printing out arguments to
868 /// the BuildMI call.  If it is false, we are printing the result register
869 /// name.
870 void InstrSelectorEmitter::PrintExpanderOperand(Init *Arg,
871                                                 const std::string &NameVar,
872                                                 TreePatternNode *ArgDeclNode,
873                                                 Pattern *P, bool PrintArg,
874                                                 std::ostream &OS) {
875   if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
876     Record *Arg = DI->getDef();
877     if (!ArgDeclNode->isLeaf() && ArgDeclNode->getNumChildren() != 0)
878       P->error("Expected leaf node as argument!");
879     Record *ArgDecl = ArgDeclNode->isLeaf() ? ArgDeclNode->getValueRecord() :
880                       ArgDeclNode->getOperator();
881     if (Arg->isSubClassOf("Register")) {
882       // This is a physical register reference... make sure that the instruction
883       // requested a register!
884       if (!ArgDecl->isSubClassOf("RegisterClass"))
885         P->error("Argument mismatch for instruction pattern!");
886
887       // FIXME: This should check to see if the register is in the specified
888       // register class!
889       if (PrintArg) OS << ".addReg(";
890       OS << getQualifiedName(Arg);
891       if (PrintArg) OS << ")";
892       return;
893     } else if (Arg->isSubClassOf("RegisterClass")) {
894       // If this is a symbolic register class reference, we must be using a
895       // named value.
896       if (NameVar.empty()) P->error("Did not specify WHICH register to pass!");
897       if (Arg != ArgDecl) P->error("Instruction pattern mismatch!");
898
899       if (PrintArg) OS << ".addReg(";
900       OS << NameVar;
901       if (PrintArg) OS << ")";
902       return;
903     } else if (Arg->getName() == "frameidx") {
904       if (!PrintArg) P->error("Cannot define a new frameidx value!");
905       OS << ".addFrameIndex(" << NameVar << ")";
906       return;
907     } else if (Arg->getName() == "basicblock") {
908       if (!PrintArg) P->error("Cannot define a new basicblock value!");
909       OS << ".addMBB(" << NameVar << ")";
910       return;
911     }
912     P->error("Unknown operand type '" + Arg->getName() + "' to expander!");
913   } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
914     if (!NameVar.empty())
915       P->error("Illegal to specify a name for a constant initializer arg!");
916
917     // Hack this check to allow R32 values with 0 as the initializer for memory
918     // references... FIXME!
919     if (ArgDeclNode->isLeaf() && II->getValue() == 0 &&
920         ArgDeclNode->getValueRecord()->getName() == "R32") {
921       OS << ".addReg(0)";
922     } else {
923       if (ArgDeclNode->isLeaf() || ArgDeclNode->getOperator()->getName()!="imm")
924         P->error("Illegal immediate int value '" + itostr(II->getValue()) +
925                  "' operand!");
926       OS << ".addZImm(" << II->getValue() << ")";
927     }
928     return;
929   }
930   P->error("Unknown operand type to expander!");
931 }
932
933 static std::string getArgName(Pattern *P, const std::string &ArgName, 
934        const std::vector<std::pair<TreePatternNode*, std::string> > &Operands) {
935   assert(P->getNumArgs() == Operands.size() &&"Argument computation mismatch!");
936   if (ArgName.empty()) return "";
937
938   for (unsigned i = 0, e = P->getNumArgs(); i != e; ++i)
939     if (P->getArgName(i) == ArgName)
940       return Operands[i].second + "->Val";
941
942   if (ArgName == P->getResultName())
943     return "NewReg";
944   P->error("Pattern does not define a value named $" + ArgName + "!");
945   return "";
946 }
947
948
949 void InstrSelectorEmitter::run(std::ostream &OS) {
950   // Type-check all of the node types to ensure we "understand" them.
951   ReadNodeTypes();
952   
953   // Read in all of the nonterminals, instructions, and expanders...
954   ReadNonterminals();
955   ReadInstructionPatterns();
956   ReadExpanderPatterns();
957
958   // Instantiate any unresolved nonterminals with information from the context
959   // that they are used in.
960   InstantiateNonterminals();
961
962   // Clear InstantiatedNTs, we don't need it anymore...
963   InstantiatedNTs.clear();
964
965   DEBUG(std::cerr << "Patterns acquired:\n");
966   for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
967          E = Patterns.end(); I != E; ++I)
968     if (I->second->isResolved())
969       DEBUG(std::cerr << "  " << *I->second << "\n");
970
971   CalculateComputableValues();
972   
973   EmitSourceFileHeader("Instruction Selector for the " + Target.getName() +
974                        " target", OS);
975   OS << "#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n";
976
977   // Output the slot number enums...
978   OS << "\nenum { // Slot numbers...\n"
979      << "  LastBuiltinSlot = ISD::NumBuiltinSlots-1, // Start numbering here\n";
980   for (PatternOrganizer::iterator I = ComputableValues.begin(),
981          E = ComputableValues.end(); I != E; ++I)
982     OS << "  " << I->first << "_Slot,\n";
983   OS << "  NumSlots\n};\n\n// Reduction value typedefs...\n";
984
985   // Output the reduction value typedefs...
986   for (PatternOrganizer::iterator I = ComputableValues.begin(),
987          E = ComputableValues.end(); I != E; ++I) {
988
989     OS << "typedef ReducedValue<unsigned, " << I->first
990        << "_Slot> ReducedValue_" << I->first << ";\n";
991   }
992
993   // Output the pattern enums...
994   OS << "\n\n"
995      << "enum { // Patterns...\n"
996      << "  NotComputed = 0,\n"
997      << "  NoMatchPattern, \n";
998   for (PatternOrganizer::iterator I = ComputableValues.begin(),
999          E = ComputableValues.end(); I != E; ++I) {
1000     OS << "  // " << I->first << " patterns...\n";
1001     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1002            E = I->second.end(); J != E; ++J)
1003       for (unsigned i = 0, e = J->second.size(); i != e; ++i)
1004         OS << "  " << J->second[i]->getRecord()->getName() << "_Pattern,\n";
1005   }
1006   OS << "};\n\n";
1007
1008   //===--------------------------------------------------------------------===//
1009   // Emit the class definition...
1010   //
1011   OS << "namespace {\n"
1012      << "  class " << Target.getName() << "ISel {\n"
1013      << "    SelectionDAG &DAG;\n"
1014      << "  public:\n"
1015      << "    X86ISel(SelectionDAG &D) : DAG(D) {}\n"
1016      << "    void generateCode();\n"
1017      << "  private:\n"
1018      << "    unsigned makeAnotherReg(const TargetRegisterClass *RC) {\n"
1019      << "      return DAG.getMachineFunction().getSSARegMap()->createVirt"
1020                                        "ualRegister(RC);\n"
1021      << "    }\n\n"
1022      << "    // DAG matching methods for classes... all of these methods"
1023                                        " return the cost\n"
1024      << "    // of producing a value of the specified class and type, which"
1025                                        " also gets\n"
1026      << "    // added to the DAG node.\n";
1027
1028   // Output all of the matching prototypes for slots...
1029   for (PatternOrganizer::iterator I = ComputableValues.begin(),
1030          E = ComputableValues.end(); I != E; ++I)
1031     OS << "    unsigned Match_" << I->first << "(SelectionDAGNode *N);\n";
1032   OS << "\n    // DAG matching methods for DAG nodes...\n";
1033
1034   // Output all of the matching prototypes for slot/node pairs
1035   for (PatternOrganizer::iterator I = ComputableValues.begin(),
1036          E = ComputableValues.end(); I != E; ++I)
1037     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1038            E = I->second.end(); J != E; ++J)
1039       OS << "    unsigned Match_" << I->first << "_" << getNodeName(J->first)
1040          << "(SelectionDAGNode *N);\n";
1041
1042   // Output all of the dag reduction methods prototypes...
1043   OS << "\n    // DAG reduction methods...\n";
1044   for (PatternOrganizer::iterator I = ComputableValues.begin(),
1045          E = ComputableValues.end(); I != E; ++I)
1046     OS << "    ReducedValue_" << I->first << " *Reduce_" << I->first
1047        << "(SelectionDAGNode *N,\n" << std::string(27+2*I->first.size(), ' ')
1048        << "MachineBasicBlock *MBB);\n";
1049   OS << "  };\n}\n\n";
1050
1051   // Emit the generateCode entry-point...
1052   OS << "void X86ISel::generateCode() {\n"
1053      << "  SelectionDAGNode *Root = DAG.getRoot();\n"
1054      << "  assert(Root->getValueType() == MVT::isVoid && "
1055                                        "\"Root of DAG produces value??\");\n\n"
1056      << "  std::cerr << \"\\n\";\n"
1057      << "  unsigned Cost = Match_Void_void(Root);\n"
1058      << "  if (Cost >= ~0U >> 1) {\n"
1059      << "    std::cerr << \"Match failed!\\n\";\n"
1060      << "    Root->dump();\n"
1061      << "    abort();\n"
1062      << "  }\n\n"
1063      << "  std::cerr << \"Total DAG Cost: \" << Cost << \"\\n\\n\";\n\n"
1064      << "  Reduce_Void_void(Root, 0);\n"
1065      << "}\n\n"
1066      << "//===" << std::string(70, '-') << "===//\n"
1067      << "//  Matching methods...\n"
1068      << "//\n\n";
1069
1070   //===--------------------------------------------------------------------===//
1071   // Emit all of the matcher methods...
1072   //
1073   for (PatternOrganizer::iterator I = ComputableValues.begin(),
1074          E = ComputableValues.end(); I != E; ++I) {
1075     const std::string &SlotName = I->first;
1076     OS << "unsigned " << Target.getName() << "ISel::Match_" << SlotName
1077        << "(SelectionDAGNode *N) {\n"
1078        << "  assert(N->getValueType() == MVT::"
1079        << getEnumName((*I->second.begin()).second[0]->getTree()->getType())
1080        << ");\n" << "  // If we already have a cost available for " << SlotName
1081        << " use it!\n"
1082        << "  if (N->getPatternFor(" << SlotName << "_Slot))\n"
1083        << "    return N->getCostFor(" << SlotName << "_Slot);\n\n"
1084        << "  unsigned Cost;\n"
1085        << "  switch (N->getNodeType()) {\n"
1086        << "  default: Cost = ~0U >> 1;   // Match failed\n"
1087        << "           N->setPatternCostFor(" << SlotName << "_Slot, NoMatchPattern, Cost, NumSlots);\n"
1088        << "           break;\n";
1089
1090     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1091            E = I->second.end(); J != E; ++J)
1092       if (!J->first->isSubClassOf("Nonterminal"))
1093         OS << "  case ISD::" << getNodeName(J->first) << ":\tCost = Match_"
1094            << SlotName << "_" << getNodeName(J->first) << "(N); break;\n";
1095     OS << "  }\n";  // End of the switch statement
1096
1097     // Emit any patterns which have a nonterminal leaf as the RHS.  These may
1098     // match multiple root nodes, so they cannot be handled with the switch...
1099     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1100            E = I->second.end(); J != E; ++J)
1101       if (J->first->isSubClassOf("Nonterminal")) {
1102         OS << "  unsigned " << J->first->getName() << "_Cost = Match_"
1103            << getNodeName(J->first) << "(N);\n"
1104            << "  if (" << getNodeName(J->first) << "_Cost < Cost) Cost = "
1105            << getNodeName(J->first) << "_Cost;\n";
1106       }
1107
1108     OS << "  return Cost;\n}\n\n";
1109
1110     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1111            E = I->second.end(); J != E; ++J) {
1112       Record *Operator = J->first;
1113       bool isNonterm = Operator->isSubClassOf("Nonterminal");
1114       if (!isNonterm) {
1115         OS << "unsigned " << Target.getName() << "ISel::Match_";
1116         if (!isNonterm) OS << SlotName << "_";
1117         OS << getNodeName(Operator) << "(SelectionDAGNode *N) {\n"
1118            << "  unsigned Pattern = NoMatchPattern;\n"
1119            << "  unsigned MinCost = ~0U >> 1;\n";
1120         
1121         std::vector<std::pair<Pattern*, TreePatternNode*> > Patterns;
1122         for (unsigned i = 0, e = J->second.size(); i != e; ++i)
1123           Patterns.push_back(std::make_pair(J->second[i],
1124                                             J->second[i]->getTree()));
1125         EmitMatchCosters(OS, Patterns, "N", 2);
1126         
1127         OS << "\n  N->setPatternCostFor(" << SlotName
1128            << "_Slot, Pattern, MinCost, NumSlots);\n"
1129            << "  return MinCost;\n"
1130            << "}\n";
1131       }
1132     }
1133   }
1134
1135   //===--------------------------------------------------------------------===//
1136   // Emit all of the reducer methods...
1137   //
1138   OS << "\n\n//===" << std::string(70, '-') << "===//\n"
1139      << "// Reducer methods...\n"
1140      << "//\n";
1141
1142   for (PatternOrganizer::iterator I = ComputableValues.begin(),
1143          E = ComputableValues.end(); I != E; ++I) {
1144     const std::string &SlotName = I->first;
1145     OS << "ReducedValue_" << SlotName << " *" << Target.getName()
1146        << "ISel::Reduce_" << SlotName
1147        << "(SelectionDAGNode *N, MachineBasicBlock *MBB) {\n"
1148        << "  ReducedValue_" << SlotName << " *Val = N->hasValue<ReducedValue_"
1149        << SlotName << ">(" << SlotName << "_Slot);\n"
1150        << "  if (Val) return Val;\n"
1151        << "  if (N->getBB()) MBB = N->getBB();\n\n"
1152        << "  switch (N->getPatternFor(" << SlotName << "_Slot)) {\n";
1153
1154     // Loop over all of the patterns that can produce a value for this slot...
1155     PatternOrganizer::NodesForSlot &NodesForSlot = I->second;
1156     for (PatternOrganizer::NodesForSlot::iterator J = NodesForSlot.begin(),
1157            E = NodesForSlot.end(); J != E; ++J)
1158       for (unsigned i = 0, e = J->second.size(); i != e; ++i) {
1159         Pattern *P = J->second[i];
1160         OS << "  case " << P->getRecord()->getName() << "_Pattern: {\n"
1161            << "    // " << *P << "\n";
1162         // Loop over the operands, reducing them...
1163         std::vector<std::pair<TreePatternNode*, std::string> > Operands;
1164         ReduceAllOperands(P->getTree(), "N", Operands, OS);
1165         
1166         // Now that we have reduced all of our operands, and have the values
1167         // that reduction produces, perform the reduction action for this
1168         // pattern.
1169         std::string Result;
1170
1171         // If the pattern produces a register result, generate a new register
1172         // now.
1173         if (Record *R = P->getResult()) {
1174           assert(R->isSubClassOf("RegisterClass") &&
1175                  "Only handle register class results so far!");
1176           OS << "    unsigned NewReg = makeAnotherReg(" << Target.getName()
1177              << "::" << R->getName() << "RegisterClass);\n";
1178           Result = "NewReg";
1179           DEBUG(OS << "    std::cerr << \"%reg\" << NewReg << \" =\t\";\n");
1180         } else {
1181           DEBUG(OS << "    std::cerr << \"\t\t\";\n");
1182           Result = "0";
1183         }
1184
1185         // Print out the pattern that matched...
1186         DEBUG(OS << "    std::cerr << \"  " << P->getRecord()->getName() <<'"');
1187         DEBUG(for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1188                 if (Operands[i].first->isLeaf()) {
1189                   Record *RV = Operands[i].first->getValueRecord();
1190                   assert(RV->isSubClassOf("RegisterClass") &&
1191                          "Only handles registers here so far!");
1192                   OS << " << \" %reg\" << " << Operands[i].second
1193                      << "->Val";
1194                 } else {
1195                   OS << " << ' ' << " << Operands[i].second
1196                      << "->Val";
1197                 });
1198         DEBUG(OS << " << \"\\n\";\n");
1199         
1200         // Generate the reduction code appropriate to the particular type of
1201         // pattern that this is...
1202         switch (P->getPatternType()) {
1203         case Pattern::Instruction:
1204           // Instruction patterns just emit a single MachineInstr, using BuildMI
1205           OS << "    BuildMI(MBB, " << Target.getName() << "::"
1206              << P->getRecord()->getName() << ", " << Operands.size();
1207           if (P->getResult()) OS << ", NewReg";
1208           OS << ")";
1209
1210           for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
1211             TreePatternNode *Op = Operands[i].first;
1212             if (Op->isLeaf()) {
1213               Record *RV = Op->getValueRecord();
1214               assert(RV->isSubClassOf("RegisterClass") &&
1215                      "Only handles registers here so far!");
1216               OS << ".addReg(" << Operands[i].second << "->Val)";
1217             } else if (Op->getOperator()->getName() == "imm") {
1218               OS << ".addZImm(" << Operands[i].second << "->Val)";
1219             } else if (Op->getOperator()->getName() == "basicblock") {
1220               OS << ".addMBB(" << Operands[i].second << "->Val)";
1221             } else {
1222               assert(0 && "Unknown value type!");
1223             }
1224           }
1225           OS << ";\n";
1226           break;
1227         case Pattern::Expander: {
1228           // Expander patterns emit one machine instr for each instruction in
1229           // the list of instructions expanded to.
1230           ListInit *Insts = P->getRecord()->getValueAsListInit("Result");
1231           for (unsigned IN = 0, e = Insts->getSize(); IN != e; ++IN) {
1232             DagInit *DIInst = dynamic_cast<DagInit*>(Insts->getElement(IN));
1233             if (!DIInst) P->error("Result list must contain instructions!");
1234             Record *InstRec  = DIInst->getNodeType();
1235             Pattern *InstPat = getPattern(InstRec);
1236             if (!InstPat || InstPat->getPatternType() != Pattern::Instruction)
1237               P->error("Instruction list must contain Instruction patterns!");
1238             
1239             bool hasResult = InstPat->getResult() != 0;
1240             if (InstPat->getNumArgs() != DIInst->getNumArgs()-hasResult) {
1241               P->error("Incorrect number of arguments specified for inst '" +
1242                        InstPat->getRecord()->getName() + "' in result list!");
1243             }
1244
1245             // Start emission of the instruction...
1246             OS << "    BuildMI(MBB, " << Target.getName() << "::"
1247                << InstRec->getName() << ", "
1248                << DIInst->getNumArgs()-hasResult;
1249             // Emit register result if necessary..
1250             if (hasResult) {
1251               std::string ArgNameVal =
1252                 getArgName(P, DIInst->getArgName(0), Operands);
1253               PrintExpanderOperand(DIInst->getArg(0), ArgNameVal,
1254                                    InstPat->getResultNode(), P, false,
1255                                    OS << ", ");
1256             }
1257             OS << ")";
1258
1259             for (unsigned i = hasResult, e = DIInst->getNumArgs(); i != e; ++i){
1260               std::string ArgNameVal =
1261                 getArgName(P, DIInst->getArgName(i), Operands);
1262
1263               PrintExpanderOperand(DIInst->getArg(i), ArgNameVal,
1264                                    InstPat->getArg(i-hasResult), P, true, OS);
1265             }
1266
1267             OS << ";\n";
1268           }
1269           break;
1270         }
1271         default:
1272           assert(0 && "Reduction of this type of pattern not implemented!");
1273         }
1274
1275         OS << "    Val = new ReducedValue_" << SlotName << "(" << Result<<");\n"
1276            << "    break;\n"
1277            << "  }\n";
1278       }
1279     
1280     
1281     OS << "  default: assert(0 && \"Unknown " << SlotName << " pattern!\");\n"
1282        << "  }\n\n  N->addValue(Val);  // Do not ever recalculate this\n"
1283        << "  return Val;\n}\n\n";
1284   }
1285 }
1286