put instructions into a map instead of a vector for quick lookup
[oota-llvm.git] / utils / TableGen / DAGISelEmitter.cpp
1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend emits a DAG instruction selector.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "DAGISelEmitter.h"
15 #include "Record.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Debug.h"
18 #include <set>
19 using namespace llvm;
20
21 //===----------------------------------------------------------------------===//
22 // SDTypeConstraint implementation
23 //
24
25 SDTypeConstraint::SDTypeConstraint(Record *R) {
26   OperandNo = R->getValueAsInt("OperandNum");
27   
28   if (R->isSubClassOf("SDTCisVT")) {
29     ConstraintType = SDTCisVT;
30     x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
31   } else if (R->isSubClassOf("SDTCisInt")) {
32     ConstraintType = SDTCisInt;
33   } else if (R->isSubClassOf("SDTCisFP")) {
34     ConstraintType = SDTCisFP;
35   } else if (R->isSubClassOf("SDTCisSameAs")) {
36     ConstraintType = SDTCisSameAs;
37     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
38   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
39     ConstraintType = SDTCisVTSmallerThanOp;
40     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum = 
41       R->getValueAsInt("OtherOperandNum");
42   } else {
43     std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
44     exit(1);
45   }
46 }
47
48 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
49 /// N, which has NumResults results.
50 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
51                                                  TreePatternNode *N,
52                                                  unsigned NumResults) const {
53   assert(NumResults == 1 && "We only work with single result nodes so far!");
54   
55   if (OpNo < NumResults)
56     return N;  // FIXME: need value #
57   else
58     return N->getChild(OpNo-NumResults);
59 }
60
61 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
62 /// constraint to the nodes operands.  This returns true if it makes a
63 /// change, false otherwise.  If a type contradiction is found, throw an
64 /// exception.
65 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
66                                            const SDNodeInfo &NodeInfo,
67                                            TreePattern &TP) const {
68   unsigned NumResults = NodeInfo.getNumResults();
69   assert(NumResults == 1 && "We only work with single result nodes so far!");
70   
71   // Check that the number of operands is sane.
72   if (NodeInfo.getNumOperands() >= 0) {
73     if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
74       TP.error(N->getOperator()->getName() + " node requires exactly " +
75                itostr(NodeInfo.getNumOperands()) + " operands!");
76   }
77   
78   TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
79   
80   switch (ConstraintType) {
81   default: assert(0 && "Unknown constraint type!");
82   case SDTCisVT:
83     // Operand must be a particular type.
84     return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
85   case SDTCisInt:
86     if (NodeToApply->hasTypeSet() && !MVT::isInteger(NodeToApply->getType()))
87       NodeToApply->UpdateNodeType(MVT::i1, TP);  // throw an error.
88
89     // FIXME: can tell from the target if there is only one Int type supported.
90     return false;
91   case SDTCisFP:
92     if (NodeToApply->hasTypeSet() &&
93         !MVT::isFloatingPoint(NodeToApply->getType()))
94       NodeToApply->UpdateNodeType(MVT::f32, TP);  // throw an error.
95     // FIXME: can tell from the target if there is only one FP type supported.
96     return false;
97   case SDTCisSameAs: {
98     TreePatternNode *OtherNode =
99       getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
100     return NodeToApply->UpdateNodeType(OtherNode->getType(), TP) |
101            OtherNode->UpdateNodeType(NodeToApply->getType(), TP);
102   }
103   case SDTCisVTSmallerThanOp: {
104     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
105     // have an integer type that is smaller than the VT.
106     if (!NodeToApply->isLeaf() ||
107         !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
108         !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
109                ->isSubClassOf("ValueType"))
110       TP.error(N->getOperator()->getName() + " expects a VT operand!");
111     MVT::ValueType VT =
112      getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
113     if (!MVT::isInteger(VT))
114       TP.error(N->getOperator()->getName() + " VT operand must be integer!");
115     
116     TreePatternNode *OtherNode =
117       getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
118     if (OtherNode->hasTypeSet() &&
119         (!MVT::isInteger(OtherNode->getType()) ||
120          OtherNode->getType() <= VT))
121       OtherNode->UpdateNodeType(MVT::Other, TP);  // Throw an error.
122     return false;
123   }
124   }  
125   return false;
126 }
127
128
129 //===----------------------------------------------------------------------===//
130 // SDNodeInfo implementation
131 //
132 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
133   EnumName    = R->getValueAsString("Opcode");
134   SDClassName = R->getValueAsString("SDClass");
135   Record *TypeProfile = R->getValueAsDef("TypeProfile");
136   NumResults = TypeProfile->getValueAsInt("NumResults");
137   NumOperands = TypeProfile->getValueAsInt("NumOperands");
138   
139   // Parse the type constraints.
140   ListInit *Constraints = TypeProfile->getValueAsListInit("Constraints");
141   for (unsigned i = 0, e = Constraints->getSize(); i != e; ++i) {
142     assert(dynamic_cast<DefInit*>(Constraints->getElement(i)) &&
143            "Constraints list should contain constraint definitions!");
144     Record *Constraint = 
145       static_cast<DefInit*>(Constraints->getElement(i))->getDef();
146     TypeConstraints.push_back(Constraint);
147   }
148 }
149
150 //===----------------------------------------------------------------------===//
151 // TreePatternNode implementation
152 //
153
154 TreePatternNode::~TreePatternNode() {
155 #if 0 // FIXME: implement refcounted tree nodes!
156   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
157     delete getChild(i);
158 #endif
159 }
160
161 /// UpdateNodeType - Set the node type of N to VT if VT contains
162 /// information.  If N already contains a conflicting type, then throw an
163 /// exception.  This returns true if any information was updated.
164 ///
165 bool TreePatternNode::UpdateNodeType(MVT::ValueType VT, TreePattern &TP) {
166   if (VT == MVT::LAST_VALUETYPE || getType() == VT) return false;
167   if (getType() == MVT::LAST_VALUETYPE) {
168     setType(VT);
169     return true;
170   }
171   
172   TP.error("Type inference contradiction found in node " + 
173            getOperator()->getName() + "!");
174   return true; // unreachable
175 }
176
177
178 void TreePatternNode::print(std::ostream &OS) const {
179   if (isLeaf()) {
180     OS << *getLeafValue();
181   } else {
182     OS << "(" << getOperator()->getName();
183   }
184   
185   if (getType() == MVT::Other)
186     OS << ":Other";
187   else if (getType() == MVT::LAST_VALUETYPE)
188     ;//OS << ":?";
189   else
190     OS << ":" << getType();
191
192   if (!isLeaf()) {
193     if (getNumChildren() != 0) {
194       OS << " ";
195       getChild(0)->print(OS);
196       for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
197         OS << ", ";
198         getChild(i)->print(OS);
199       }
200     }
201     OS << ")";
202   }
203   
204   if (!PredicateFn.empty())
205     OS << "<<P:" << PredicateFn << ">>";
206   if (TransformFn)
207     OS << "<<X:" << TransformFn->getName() << ">>";
208   if (!getName().empty())
209     OS << ":$" << getName();
210
211 }
212 void TreePatternNode::dump() const {
213   print(std::cerr);
214 }
215
216 /// clone - Make a copy of this tree and all of its children.
217 ///
218 TreePatternNode *TreePatternNode::clone() const {
219   TreePatternNode *New;
220   if (isLeaf()) {
221     New = new TreePatternNode(getLeafValue());
222   } else {
223     std::vector<TreePatternNode*> CChildren;
224     CChildren.reserve(Children.size());
225     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
226       CChildren.push_back(getChild(i)->clone());
227     New = new TreePatternNode(getOperator(), CChildren);
228   }
229   New->setName(getName());
230   New->setType(getType());
231   New->setPredicateFn(getPredicateFn());
232   New->setTransformFn(getTransformFn());
233   return New;
234 }
235
236 /// SubstituteFormalArguments - Replace the formal arguments in this tree
237 /// with actual values specified by ArgMap.
238 void TreePatternNode::
239 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
240   if (isLeaf()) return;
241   
242   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
243     TreePatternNode *Child = getChild(i);
244     if (Child->isLeaf()) {
245       Init *Val = Child->getLeafValue();
246       if (dynamic_cast<DefInit*>(Val) &&
247           static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
248         // We found a use of a formal argument, replace it with its value.
249         Child = ArgMap[Child->getName()];
250         assert(Child && "Couldn't find formal argument!");
251         setChild(i, Child);
252       }
253     } else {
254       getChild(i)->SubstituteFormalArguments(ArgMap);
255     }
256   }
257 }
258
259
260 /// InlinePatternFragments - If this pattern refers to any pattern
261 /// fragments, inline them into place, giving us a pattern without any
262 /// PatFrag references.
263 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
264   if (isLeaf()) return this;  // nothing to do.
265   Record *Op = getOperator();
266   
267   if (!Op->isSubClassOf("PatFrag")) {
268     // Just recursively inline children nodes.
269     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
270       setChild(i, getChild(i)->InlinePatternFragments(TP));
271     return this;
272   }
273
274   // Otherwise, we found a reference to a fragment.  First, look up its
275   // TreePattern record.
276   TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
277   
278   // Verify that we are passing the right number of operands.
279   if (Frag->getNumArgs() != Children.size())
280     TP.error("'" + Op->getName() + "' fragment requires " +
281              utostr(Frag->getNumArgs()) + " operands!");
282
283   TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
284
285   // Resolve formal arguments to their actual value.
286   if (Frag->getNumArgs()) {
287     // Compute the map of formal to actual arguments.
288     std::map<std::string, TreePatternNode*> ArgMap;
289     for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
290       ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
291   
292     FragTree->SubstituteFormalArguments(ArgMap);
293   }
294   
295   FragTree->setName(getName());
296   
297   // Get a new copy of this fragment to stitch into here.
298   //delete this;    // FIXME: implement refcounting!
299   return FragTree;
300 }
301
302 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
303 /// this node and its children in the tree.  This returns true if it makes a
304 /// change, false otherwise.  If a type contradiction is found, throw an
305 /// exception.
306 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP) {
307   if (isLeaf()) return false;
308   
309   // special handling for set, which isn't really an SDNode.
310   if (getOperator()->getName() == "set") {
311     assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
312     bool MadeChange = getChild(0)->ApplyTypeConstraints(TP);
313     MadeChange |= getChild(1)->ApplyTypeConstraints(TP);
314     
315     // Types of operands must match.
316     MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getType(), TP);
317     MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getType(), TP);
318     MadeChange |= UpdateNodeType(MVT::isVoid, TP);
319     return MadeChange;
320   } else if (getOperator()->isSubClassOf("SDNode")) {
321     const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
322     
323     bool MadeChange = NI.ApplyTypeConstraints(this, TP);
324     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
325       MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
326     return MadeChange;  
327   } else {
328     assert(getOperator()->isSubClassOf("Instruction") && "Unknown node type!");
329     
330     const DAGInstruction &Inst =
331       TP.getDAGISelEmitter().getInstruction(getOperator());
332     
333     // TODO: type inference for instructions.
334     return false;
335   }
336 }
337
338
339 //===----------------------------------------------------------------------===//
340 // TreePattern implementation
341 //
342
343 TreePattern::TreePattern(Record *TheRec, const std::vector<DagInit *> &RawPat,
344                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
345
346   for (unsigned i = 0, e = RawPat.size(); i != e; ++i)
347     Trees.push_back(ParseTreePattern(RawPat[i]));
348 }
349
350 void TreePattern::error(const std::string &Msg) const {
351   dump();
352   throw "In " + TheRecord->getName() + ": " + Msg;
353 }
354
355 /// getIntrinsicType - Check to see if the specified record has an intrinsic
356 /// type which should be applied to it.  This infer the type of register
357 /// references from the register file information, for example.
358 ///
359 MVT::ValueType TreePattern::getIntrinsicType(Record *R) const {
360   // Check to see if this is a register or a register class...
361   if (R->isSubClassOf("RegisterClass"))
362     return getValueType(R->getValueAsDef("RegType"));
363   else if (R->isSubClassOf("PatFrag")) {
364     // Pattern fragment types will be resolved when they are inlined.
365     return MVT::LAST_VALUETYPE;
366   } else if (R->isSubClassOf("Register")) {
367     assert(0 && "Explicit registers not handled here yet!\n");
368     return MVT::LAST_VALUETYPE;
369   } else if (R->isSubClassOf("ValueType")) {
370     // Using a VTSDNode.
371     return MVT::Other;
372   } else if (R->getName() == "node") {
373     // Placeholder.
374     return MVT::LAST_VALUETYPE;
375   }
376   
377   error("Unknown value used: " + R->getName());
378   return MVT::Other;
379 }
380
381 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
382   Record *Operator = Dag->getNodeType();
383   
384   if (Operator->isSubClassOf("ValueType")) {
385     // If the operator is a ValueType, then this must be "type cast" of a leaf
386     // node.
387     if (Dag->getNumArgs() != 1)
388       error("Type cast only valid for a leaf node!");
389     
390     Init *Arg = Dag->getArg(0);
391     TreePatternNode *New;
392     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
393       New = new TreePatternNode(DI);
394       // If it's a regclass or something else known, set the type.
395       New->setType(getIntrinsicType(DI->getDef()));
396     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
397       New = ParseTreePattern(DI);
398     } else {
399       Arg->dump();
400       error("Unknown leaf value for tree pattern!");
401       return 0;
402     }
403     
404     // Apply the type cast.
405     New->UpdateNodeType(getValueType(Operator), *this);
406     return New;
407   }
408   
409   // Verify that this is something that makes sense for an operator.
410   if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
411       !Operator->isSubClassOf("Instruction") && 
412       !Operator->isSubClassOf("SDNodeXForm") &&
413       Operator->getName() != "set")
414     error("Unrecognized node '" + Operator->getName() + "'!");
415   
416   std::vector<TreePatternNode*> Children;
417   
418   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
419     Init *Arg = Dag->getArg(i);
420     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
421       Children.push_back(ParseTreePattern(DI));
422       Children.back()->setName(Dag->getArgName(i));
423     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
424       Record *R = DefI->getDef();
425       // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
426       // TreePatternNode if its own.
427       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
428         Dag->setArg(i, new DagInit(R,
429                               std::vector<std::pair<Init*, std::string> >()));
430         --i;  // Revisit this node...
431       } else {
432         TreePatternNode *Node = new TreePatternNode(DefI);
433         Node->setName(Dag->getArgName(i));
434         Children.push_back(Node);
435         
436         // If it's a regclass or something else known, set the type.
437         Node->setType(getIntrinsicType(R));
438         
439         // Input argument?
440         if (R->getName() == "node") {
441           if (Dag->getArgName(i).empty())
442             error("'node' argument requires a name to match with operand list");
443           Args.push_back(Dag->getArgName(i));
444         }
445       }
446     } else {
447       Arg->dump();
448       error("Unknown leaf value for tree pattern!");
449     }
450   }
451   
452   return new TreePatternNode(Operator, Children);
453 }
454
455 /// InferAllTypes - Infer/propagate as many types throughout the expression
456 /// patterns as possible.  Return true if all types are infered, false
457 /// otherwise.  Throw an exception if a type contradiction is found.
458 bool TreePattern::InferAllTypes() {
459   bool MadeChange = true;
460   while (MadeChange) {
461     MadeChange = false;
462     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
463       MadeChange |= Trees[i]->ApplyTypeConstraints(*this);
464   }
465   
466   bool HasUnresolvedTypes = false;
467   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
468     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
469   return !HasUnresolvedTypes;
470 }
471
472 void TreePattern::print(std::ostream &OS) const {
473   OS << getRecord()->getName();
474   if (!Args.empty()) {
475     OS << "(" << Args[0];
476     for (unsigned i = 1, e = Args.size(); i != e; ++i)
477       OS << ", " << Args[i];
478     OS << ")";
479   }
480   OS << ": ";
481   
482   if (Trees.size() > 1)
483     OS << "[\n";
484   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
485     OS << "\t";
486     Trees[i]->print(OS);
487     OS << "\n";
488   }
489
490   if (Trees.size() > 1)
491     OS << "]\n";
492 }
493
494 void TreePattern::dump() const { print(std::cerr); }
495
496
497
498 //===----------------------------------------------------------------------===//
499 // DAGISelEmitter implementation
500 //
501
502 // Parse all of the SDNode definitions for the target, populating SDNodes.
503 void DAGISelEmitter::ParseNodeInfo() {
504   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
505   while (!Nodes.empty()) {
506     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
507     Nodes.pop_back();
508   }
509 }
510
511 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
512 /// map, and emit them to the file as functions.
513 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
514   OS << "\n// Node transformations.\n";
515   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
516   while (!Xforms.empty()) {
517     Record *XFormNode = Xforms.back();
518     Record *SDNode = XFormNode->getValueAsDef("Opcode");
519     std::string Code = XFormNode->getValueAsCode("XFormFunction");
520     SDNodeXForms.insert(std::make_pair(XFormNode,
521                                        std::make_pair(SDNode, Code)));
522
523     if (!Code.empty()) {
524       std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
525       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
526
527       OS << "inline SDOperand Transform_" << XFormNode->getName()
528          << "(SDNode *" << C2 << ") {\n";
529       if (ClassName != "SDNode")
530         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
531       OS << Code << "\n}\n";
532     }
533
534     Xforms.pop_back();
535   }
536 }
537
538
539
540 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
541 /// file, building up the PatternFragments map.  After we've collected them all,
542 /// inline fragments together as necessary, so that there are no references left
543 /// inside a pattern fragment to a pattern fragment.
544 ///
545 /// This also emits all of the predicate functions to the output file.
546 ///
547 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
548   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
549   
550   // First step, parse all of the fragments and emit predicate functions.
551   OS << "\n// Predicate functions.\n";
552   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
553     std::vector<DagInit*> Trees;
554     Trees.push_back(Fragments[i]->getValueAsDag("Fragment"));
555     TreePattern *P = new TreePattern(Fragments[i], Trees, *this);
556     PatternFragments[Fragments[i]] = P;
557     
558     // Validate the argument list, converting it to map, to discard duplicates.
559     std::vector<std::string> &Args = P->getArgList();
560     std::set<std::string> OperandsMap(Args.begin(), Args.end());
561     
562     if (OperandsMap.count(""))
563       P->error("Cannot have unnamed 'node' values in pattern fragment!");
564     
565     // Parse the operands list.
566     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
567     if (OpsList->getNodeType()->getName() != "ops")
568       P->error("Operands list should start with '(ops ... '!");
569     
570     // Copy over the arguments.       
571     Args.clear();
572     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
573       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
574           static_cast<DefInit*>(OpsList->getArg(j))->
575           getDef()->getName() != "node")
576         P->error("Operands list should all be 'node' values.");
577       if (OpsList->getArgName(j).empty())
578         P->error("Operands list should have names for each operand!");
579       if (!OperandsMap.count(OpsList->getArgName(j)))
580         P->error("'" + OpsList->getArgName(j) +
581                  "' does not occur in pattern or was multiply specified!");
582       OperandsMap.erase(OpsList->getArgName(j));
583       Args.push_back(OpsList->getArgName(j));
584     }
585     
586     if (!OperandsMap.empty())
587       P->error("Operands list does not contain an entry for operand '" +
588                *OperandsMap.begin() + "'!");
589
590     // If there is a code init for this fragment, emit the predicate code and
591     // keep track of the fact that this fragment uses it.
592     std::string Code = Fragments[i]->getValueAsCode("Predicate");
593     if (!Code.empty()) {
594       assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
595       std::string ClassName =
596         getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
597       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
598       
599       OS << "inline bool Predicate_" << Fragments[i]->getName()
600          << "(SDNode *" << C2 << ") {\n";
601       if (ClassName != "SDNode")
602         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
603       OS << Code << "\n}\n";
604       P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
605     }
606     
607     // If there is a node transformation corresponding to this, keep track of
608     // it.
609     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
610     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
611       P->getOnlyTree()->setTransformFn(Transform);
612   }
613   
614   OS << "\n\n";
615
616   // Now that we've parsed all of the tree fragments, do a closure on them so
617   // that there are not references to PatFrags left inside of them.
618   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
619        E = PatternFragments.end(); I != E; ++I) {
620     TreePattern *ThePat = I->second;
621     ThePat->InlinePatternFragments();
622         
623     // Infer as many types as possible.  Don't worry about it if we don't infer
624     // all of them, some may depend on the inputs of the pattern.
625     try {
626       ThePat->InferAllTypes();
627     } catch (...) {
628       // If this pattern fragment is not supported by this target (no types can
629       // satisfy its constraints), just ignore it.  If the bogus pattern is
630       // actually used by instructions, the type consistency error will be
631       // reported there.
632     }
633     
634     // If debugging, print out the pattern fragment result.
635     DEBUG(ThePat->dump());
636   }
637 }
638
639 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
640 /// instruction input.  Return true if this is a real use.
641 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
642                       std::map<std::string, TreePatternNode*> &InstInputs) {
643   // No name -> not interesting.
644   if (Pat->getName().empty()) {
645     if (Pat->isLeaf()) {
646       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
647       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
648         I->error("Input " + DI->getDef()->getName() + " must be named!");
649
650     }
651     return false;
652   }
653
654   Record *Rec;
655   if (Pat->isLeaf()) {
656     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
657     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
658     Rec = DI->getDef();
659   } else {
660     assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
661     Rec = Pat->getOperator();
662   }
663
664   TreePatternNode *&Slot = InstInputs[Pat->getName()];
665   if (!Slot) {
666     Slot = Pat;
667   } else {
668     Record *SlotRec;
669     if (Slot->isLeaf()) {
670       Rec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
671     } else {
672       assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
673       SlotRec = Slot->getOperator();
674     }
675     
676     // Ensure that the inputs agree if we've already seen this input.
677     if (Rec != SlotRec)
678       I->error("All $" + Pat->getName() + " inputs must agree with each other");
679     if (Slot->getType() != Pat->getType())
680       I->error("All $" + Pat->getName() + " inputs must agree with each other");
681   }
682   return true;
683 }
684
685 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
686 /// part of "I", the instruction), computing the set of inputs and outputs of
687 /// the pattern.  Report errors if we see anything naughty.
688 void DAGISelEmitter::
689 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
690                             std::map<std::string, TreePatternNode*> &InstInputs,
691                             std::map<std::string, Record*> &InstResults) {
692   if (Pat->isLeaf()) {
693     bool isUse = HandleUse(I, Pat, InstInputs);
694     if (!isUse && Pat->getTransformFn())
695       I->error("Cannot specify a transform function for a non-input value!");
696     return;
697   } else if (Pat->getOperator()->getName() != "set") {
698     // If this is not a set, verify that the children nodes are not void typed,
699     // and recurse.
700     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
701       if (Pat->getChild(i)->getType() == MVT::isVoid)
702         I->error("Cannot have void nodes inside of patterns!");
703       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
704     }
705     
706     // If this is a non-leaf node with no children, treat it basically as if
707     // it were a leaf.  This handles nodes like (imm).
708     bool isUse = false;
709     if (Pat->getNumChildren() == 0)
710       isUse = HandleUse(I, Pat, InstInputs);
711     
712     if (!isUse && Pat->getTransformFn())
713       I->error("Cannot specify a transform function for a non-input value!");
714     return;
715   } 
716   
717   // Otherwise, this is a set, validate and collect instruction results.
718   if (Pat->getNumChildren() == 0)
719     I->error("set requires operands!");
720   else if (Pat->getNumChildren() & 1)
721     I->error("set requires an even number of operands");
722   
723   if (Pat->getTransformFn())
724     I->error("Cannot specify a transform function on a set node!");
725   
726   // Check the set destinations.
727   unsigned NumValues = Pat->getNumChildren()/2;
728   for (unsigned i = 0; i != NumValues; ++i) {
729     TreePatternNode *Dest = Pat->getChild(i);
730     if (!Dest->isLeaf())
731       I->error("set destination should be a virtual register!");
732     
733     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
734     if (!Val)
735       I->error("set destination should be a virtual register!");
736     
737     if (!Val->getDef()->isSubClassOf("RegisterClass"))
738       I->error("set destination should be a virtual register!");
739     if (Dest->getName().empty())
740       I->error("set destination must have a name!");
741     if (InstResults.count(Dest->getName()))
742       I->error("cannot set '" + Dest->getName() +"' multiple times");
743     InstResults[Dest->getName()] = Val->getDef();
744
745     // Verify and collect info from the computation.
746     FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
747                                 InstInputs, InstResults);
748   }
749 }
750
751
752 /// ParseInstructions - Parse all of the instructions, inlining and resolving
753 /// any fragments involved.  This populates the Instructions list with fully
754 /// resolved instructions.
755 void DAGISelEmitter::ParseInstructions() {
756   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
757   
758   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
759     if (!dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
760       continue; // no pattern yet, ignore it.
761     
762     ListInit *LI = Instrs[i]->getValueAsListInit("Pattern");
763     if (LI->getSize() == 0) continue;  // no pattern.
764     
765     std::vector<DagInit*> Trees;
766     for (unsigned j = 0, e = LI->getSize(); j != e; ++j)
767       Trees.push_back((DagInit*)LI->getElement(j));
768
769     // Parse the instruction.
770     TreePattern *I = new TreePattern(Instrs[i], Trees, *this);
771     // Inline pattern fragments into it.
772     I->InlinePatternFragments();
773     
774     // Infer as many types as possible.  If we cannot infer all of them, we can
775     // never do anything with this instruction pattern: report it to the user.
776     if (!I->InferAllTypes())
777       I->error("Could not infer all types in pattern!");
778     
779     // InstInputs - Keep track of all of the inputs of the instruction, along 
780     // with the record they are declared as.
781     std::map<std::string, TreePatternNode*> InstInputs;
782     
783     // InstResults - Keep track of all the virtual registers that are 'set'
784     // in the instruction, including what reg class they are.
785     std::map<std::string, Record*> InstResults;
786     
787     // Verify that the top-level forms in the instruction are of void type, and
788     // fill in the InstResults map.
789     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
790       TreePatternNode *Pat = I->getTree(j);
791       if (Pat->getType() != MVT::isVoid) {
792         I->dump();
793         I->error("Top-level forms in instruction pattern should have"
794                  " void types");
795       }
796
797       // Find inputs and outputs, and verify the structure of the uses/defs.
798       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
799     }
800
801     // Now that we have inputs and outputs of the pattern, inspect the operands
802     // list for the instruction.  This determines the order that operands are
803     // added to the machine instruction the node corresponds to.
804     unsigned NumResults = InstResults.size();
805
806     // Parse the operands list from the (ops) list, validating it.
807     std::vector<std::string> &Args = I->getArgList();
808     assert(Args.empty() && "Args list should still be empty here!");
809     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
810
811     // Check that all of the results occur first in the list.
812     std::vector<MVT::ValueType> ResultTypes;
813     for (unsigned i = 0; i != NumResults; ++i) {
814       if (i == CGI.OperandList.size())
815         I->error("'" + InstResults.begin()->first +
816                  "' set but does not appear in operand list!");
817       const std::string &OpName = CGI.OperandList[i].Name;
818       
819       // Check that it exists in InstResults.
820       Record *R = InstResults[OpName];
821       if (R == 0)
822         I->error("Operand $" + OpName + " should be a set destination: all "
823                  "outputs must occur before inputs in operand list!");
824       
825       if (CGI.OperandList[i].Rec != R)
826         I->error("Operand $" + OpName + " class mismatch!");
827       
828       // Remember the return type.
829       ResultTypes.push_back(CGI.OperandList[i].Ty);
830       
831       // Okay, this one checks out.
832       InstResults.erase(OpName);
833     }
834
835     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
836     // the copy while we're checking the inputs.
837     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
838
839     std::vector<TreePatternNode*> ResultNodeOperands;
840     std::vector<MVT::ValueType> OperandTypes;
841     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
842       const std::string &OpName = CGI.OperandList[i].Name;
843       if (OpName.empty())
844         I->error("Operand #" + utostr(i) + " in operands list has no name!");
845
846       if (!InstInputsCheck.count(OpName))
847         I->error("Operand $" + OpName +
848                  " does not appear in the instruction pattern");
849       TreePatternNode *InVal = InstInputsCheck[OpName];
850       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
851       if (CGI.OperandList[i].Ty != InVal->getType())
852         I->error("Operand $" + OpName +
853                  "'s type disagrees between the operand and pattern");
854       OperandTypes.push_back(InVal->getType());
855       
856       // Construct the result for the dest-pattern operand list.
857       TreePatternNode *OpNode = InVal->clone();
858       
859       // No predicate is useful on the result.
860       OpNode->setPredicateFn("");
861       
862       // Promote the xform function to be an explicit node if set.
863       if (Record *Xform = OpNode->getTransformFn()) {
864         OpNode->setTransformFn(0);
865         std::vector<TreePatternNode*> Children;
866         Children.push_back(OpNode);
867         OpNode = new TreePatternNode(Xform, Children);
868       }
869       
870       ResultNodeOperands.push_back(OpNode);
871     }
872     
873     if (!InstInputsCheck.empty())
874       I->error("Input operand $" + InstInputsCheck.begin()->first +
875                " occurs in pattern but not in operands list!");
876
877     TreePatternNode *ResultPattern =
878       new TreePatternNode(I->getRecord(), ResultNodeOperands);
879     
880     DEBUG(I->dump());
881     Instructions.insert(std::make_pair(I->getRecord(),
882                                        DAGInstruction(I, ResultTypes,
883                                                 OperandTypes, ResultPattern)));
884   }
885    
886   // If we can, convert the instructions to be patterns that are matched!
887   for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
888        E = Instructions.end(); II != E; ++II) {
889     TreePattern *I = II->second.getPattern();
890     
891     if (I->getNumTrees() != 1) {
892       std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
893       continue;
894     }
895     TreePatternNode *Pattern = I->getTree(0);
896     if (Pattern->getOperator()->getName() != "set")
897       continue;  // Not a set (store or something?)
898     
899     if (Pattern->getNumChildren() != 2)
900       continue;  // Not a set of a single value (not handled so far)
901     
902     TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
903     TreePatternNode *DstPattern = II->second.getResultPattern();
904     PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
905   }
906 }
907
908 void DAGISelEmitter::ParsePatterns() {
909   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
910
911   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
912     std::vector<DagInit*> Trees;
913     Trees.push_back(Patterns[i]->getValueAsDag("PatternToMatch"));
914     TreePattern *Pattern = new TreePattern(Patterns[i], Trees, *this);
915     Trees.clear();
916
917     // Inline pattern fragments into it.
918     Pattern->InlinePatternFragments();
919     
920     // Infer as many types as possible.  If we cannot infer all of them, we can
921     // never do anything with this pattern: report it to the user.
922     if (!Pattern->InferAllTypes())
923       Pattern->error("Could not infer all types in pattern!");
924     
925     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
926     if (LI->getSize() == 0) continue;  // no pattern.
927     for (unsigned j = 0, e = LI->getSize(); j != e; ++j)
928       Trees.push_back((DagInit*)LI->getElement(j));
929     
930     // Parse the instruction.
931     TreePattern *Result = new TreePattern(Patterns[i], Trees, *this);
932     
933     // Inline pattern fragments into it.
934     Result->InlinePatternFragments();
935     
936     // Infer as many types as possible.  If we cannot infer all of them, we can
937     // never do anything with this pattern: report it to the user.
938 #if 0  // FIXME: ENABLE when we can infer though instructions!
939     if (!Result->InferAllTypes())
940       Result->error("Could not infer all types in pattern result!");
941 #endif
942    
943     if (Result->getNumTrees() != 1)
944       Result->error("Cannot handle instructions producing instructions "
945                     "with temporaries yet!");
946     PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
947                                              Result->getOnlyTree()));
948   }
949
950   DEBUG(std::cerr << "\n\nPARSED PATTERNS TO MATCH:\n\n";
951         for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
952           std::cerr << "PATTERN: ";  PatternsToMatch[i].first->dump();
953           std::cerr << "\nRESULT:  ";PatternsToMatch[i].second->dump();
954           std::cerr << "\n";
955         });
956 }
957
958 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
959   // Emit boilerplate.
960   OS << "// The main instruction selector code.\n"
961      << "SDOperand SelectCode(SDOperand Op) {\n"
962      << "  SDNode *N = Op.Val;\n"
963      << "  if (N->getOpcode() >= ISD::BUILTIN_OP_END &&\n"
964      << "      N->getOpcode() < PPCISD::FIRST_NUMBER)\n"
965      << "    return Op;   // Already selected.\n\n"
966      << "  switch (N->getOpcode()) {\n"
967      << "  default: break;\n"
968      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
969      << "    return Op;\n"
970      << "  case ISD::AssertSext:\n"
971      << "  case ISD::AssertZext:\n"
972      << "    return Select(N->getOperand(0));\n";
973     
974
975   
976   OS << "  } // end of big switch.\n\n"
977      << "  std::cerr << \"Cannot yet select: \";\n"
978      << "  N->dump();\n"
979      << "  std::cerr << '\\n';\n"
980      << "  abort();\n"
981      << "}\n";
982 }
983
984 void DAGISelEmitter::run(std::ostream &OS) {
985   EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
986                        " target", OS);
987   
988   OS << "// *** NOTE: This file is #included into the middle of the target\n"
989      << "// *** instruction selector class.  These functions are really "
990      << "methods.\n\n";
991   ParseNodeInfo();
992   ParseNodeTransforms(OS);
993   ParsePatternFragments(OS);
994   ParseInstructions();
995   ParsePatterns();
996
997   // TODO: convert some instructions to expanders if needed or something.
998   
999   EmitInstructionSelector(OS);  
1000   
1001   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1002        E = PatternFragments.end(); I != E; ++I)
1003     delete I->second;
1004   PatternFragments.clear();
1005
1006   Instructions.clear();
1007 }