Re-apply the memory operand changes, with a fix for the static
[oota-llvm.git] / utils / TableGen / DAGISelEmitter.cpp
1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 "llvm/Support/MathExtras.h"
19 #include "llvm/Support/Streams.h"
20 #include <algorithm>
21 using namespace llvm;
22
23 //===----------------------------------------------------------------------===//
24 // DAGISelEmitter Helper methods
25 //
26
27 /// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
28 /// ComplexPattern.
29 static bool NodeIsComplexPattern(TreePatternNode *N) {
30   return (N->isLeaf() &&
31           dynamic_cast<DefInit*>(N->getLeafValue()) &&
32           static_cast<DefInit*>(N->getLeafValue())->getDef()->
33           isSubClassOf("ComplexPattern"));
34 }
35
36 /// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
37 /// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
38 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
39                                                    CodeGenDAGPatterns &CGP) {
40   if (N->isLeaf() &&
41       dynamic_cast<DefInit*>(N->getLeafValue()) &&
42       static_cast<DefInit*>(N->getLeafValue())->getDef()->
43       isSubClassOf("ComplexPattern")) {
44     return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
45                                        ->getDef());
46   }
47   return NULL;
48 }
49
50 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
51 /// patterns before small ones.  This is used to determine the size of a
52 /// pattern.
53 static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
54   assert((MVT::isExtIntegerInVTs(P->getExtTypes()) || 
55           MVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
56           P->getExtTypeNum(0) == MVT::isVoid ||
57           P->getExtTypeNum(0) == MVT::Flag ||
58           P->getExtTypeNum(0) == MVT::iPTR) && 
59          "Not a valid pattern node to size!");
60   unsigned Size = 3;  // The node itself.
61   // If the root node is a ConstantSDNode, increases its size.
62   // e.g. (set R32:$dst, 0).
63   if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
64     Size += 2;
65
66   // FIXME: This is a hack to statically increase the priority of patterns
67   // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
68   // Later we can allow complexity / cost for each pattern to be (optionally)
69   // specified. To get best possible pattern match we'll need to dynamically
70   // calculate the complexity of all patterns a dag can potentially map to.
71   const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
72   if (AM)
73     Size += AM->getNumOperands() * 3;
74
75   // If this node has some predicate function that must match, it adds to the
76   // complexity of this node.
77   if (!P->getPredicateFn().empty())
78     ++Size;
79   
80   // Count children in the count if they are also nodes.
81   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
82     TreePatternNode *Child = P->getChild(i);
83     if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
84       Size += getPatternSize(Child, CGP);
85     else if (Child->isLeaf()) {
86       if (dynamic_cast<IntInit*>(Child->getLeafValue())) 
87         Size += 5;  // Matches a ConstantSDNode (+3) and a specific value (+2).
88       else if (NodeIsComplexPattern(Child))
89         Size += getPatternSize(Child, CGP);
90       else if (!Child->getPredicateFn().empty())
91         ++Size;
92     }
93   }
94   
95   return Size;
96 }
97
98 /// getResultPatternCost - Compute the number of instructions for this pattern.
99 /// This is a temporary hack.  We should really include the instruction
100 /// latencies in this calculation.
101 static unsigned getResultPatternCost(TreePatternNode *P,
102                                      CodeGenDAGPatterns &CGP) {
103   if (P->isLeaf()) return 0;
104   
105   unsigned Cost = 0;
106   Record *Op = P->getOperator();
107   if (Op->isSubClassOf("Instruction")) {
108     Cost++;
109     CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
110     if (II.usesCustomDAGSchedInserter)
111       Cost += 10;
112   }
113   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
114     Cost += getResultPatternCost(P->getChild(i), CGP);
115   return Cost;
116 }
117
118 /// getResultPatternCodeSize - Compute the code size of instructions for this
119 /// pattern.
120 static unsigned getResultPatternSize(TreePatternNode *P, 
121                                      CodeGenDAGPatterns &CGP) {
122   if (P->isLeaf()) return 0;
123
124   unsigned Cost = 0;
125   Record *Op = P->getOperator();
126   if (Op->isSubClassOf("Instruction")) {
127     Cost += Op->getValueAsInt("CodeSize");
128   }
129   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
130     Cost += getResultPatternSize(P->getChild(i), CGP);
131   return Cost;
132 }
133
134 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
135 // In particular, we want to match maximal patterns first and lowest cost within
136 // a particular complexity first.
137 struct PatternSortingPredicate {
138   PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
139   CodeGenDAGPatterns &CGP;
140
141   bool operator()(const PatternToMatch *LHS,
142                   const PatternToMatch *RHS) {
143     unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
144     unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
145     LHSSize += LHS->getAddedComplexity();
146     RHSSize += RHS->getAddedComplexity();
147     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
148     if (LHSSize < RHSSize) return false;
149     
150     // If the patterns have equal complexity, compare generated instruction cost
151     unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
152     unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
153     if (LHSCost < RHSCost) return true;
154     if (LHSCost > RHSCost) return false;
155
156     return getResultPatternSize(LHS->getDstPattern(), CGP) <
157       getResultPatternSize(RHS->getDstPattern(), CGP);
158   }
159 };
160
161 /// getRegisterValueType - Look up and return the first ValueType of specified 
162 /// RegisterClass record
163 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
164   if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
165     return RC->getValueTypeNum(0);
166   return MVT::Other;
167 }
168
169
170 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
171 /// type information from it.
172 static void RemoveAllTypes(TreePatternNode *N) {
173   N->removeTypes();
174   if (!N->isLeaf())
175     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
176       RemoveAllTypes(N->getChild(i));
177 }
178
179 /// NodeHasProperty - return true if TreePatternNode has the specified
180 /// property.
181 static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
182                             CodeGenDAGPatterns &CGP) {
183   if (N->isLeaf()) {
184     const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
185     if (CP)
186       return CP->hasProperty(Property);
187     return false;
188   }
189   Record *Operator = N->getOperator();
190   if (!Operator->isSubClassOf("SDNode")) return false;
191
192   return CGP.getSDNodeInfo(Operator).hasProperty(Property);
193 }
194
195 static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
196                                CodeGenDAGPatterns &CGP) {
197   if (NodeHasProperty(N, Property, CGP))
198     return true;
199
200   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
201     TreePatternNode *Child = N->getChild(i);
202     if (PatternHasProperty(Child, Property, CGP))
203       return true;
204   }
205
206   return false;
207 }
208
209 //===----------------------------------------------------------------------===//
210 // Node Transformation emitter implementation.
211 //
212 void DAGISelEmitter::EmitNodeTransforms(std::ostream &OS) {
213   // Walk the pattern fragments, adding them to a map, which sorts them by
214   // name.
215   typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
216   NXsByNameTy NXsByName;
217
218   for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
219        I != E; ++I)
220     NXsByName.insert(std::make_pair(I->first->getName(), I->second));
221   
222   OS << "\n// Node transformations.\n";
223   
224   for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
225        I != E; ++I) {
226     Record *SDNode = I->second.first;
227     std::string Code = I->second.second;
228     
229     if (Code.empty()) continue;  // Empty code?  Skip it.
230     
231     std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
232     const char *C2 = ClassName == "SDNode" ? "N" : "inN";
233     
234     OS << "inline SDOperand Transform_" << I->first << "(SDNode *" << C2
235        << ") {\n";
236     if (ClassName != "SDNode")
237       OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
238     OS << Code << "\n}\n";
239   }
240 }
241
242 //===----------------------------------------------------------------------===//
243 // Predicate emitter implementation.
244 //
245
246 void DAGISelEmitter::EmitPredicateFunctions(std::ostream &OS) {
247   OS << "\n// Predicate functions.\n";
248
249   // Walk the pattern fragments, adding them to a map, which sorts them by
250   // name.
251   typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
252   PFsByNameTy PFsByName;
253
254   for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
255        I != E; ++I)
256     PFsByName.insert(std::make_pair(I->first->getName(), *I));
257
258   
259   for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
260        I != E; ++I) {
261     Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
262     TreePattern *P = I->second.second;
263     
264     // If there is a code init for this fragment, emit the predicate code.
265     std::string Code = PatFragRecord->getValueAsCode("Predicate");
266     if (Code.empty()) continue;
267     
268     if (P->getOnlyTree()->isLeaf())
269       OS << "inline bool Predicate_" << PatFragRecord->getName()
270       << "(SDNode *N) {\n";
271     else {
272       std::string ClassName =
273         CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
274       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
275       
276       OS << "inline bool Predicate_" << PatFragRecord->getName()
277          << "(SDNode *" << C2 << ") {\n";
278       if (ClassName != "SDNode")
279         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
280     }
281     OS << Code << "\n}\n";
282   }
283   
284   OS << "\n\n";
285 }
286
287
288 //===----------------------------------------------------------------------===//
289 // PatternCodeEmitter implementation.
290 //
291 class PatternCodeEmitter {
292 private:
293   CodeGenDAGPatterns &CGP;
294
295   // Predicates.
296   ListInit *Predicates;
297   // Pattern cost.
298   unsigned Cost;
299   // Instruction selector pattern.
300   TreePatternNode *Pattern;
301   // Matched instruction.
302   TreePatternNode *Instruction;
303   
304   // Node to name mapping
305   std::map<std::string, std::string> VariableMap;
306   // Node to operator mapping
307   std::map<std::string, Record*> OperatorMap;
308   // Name of the folded node which produces a flag.
309   std::pair<std::string, unsigned> FoldedFlag;
310   // Names of all the folded nodes which produce chains.
311   std::vector<std::pair<std::string, unsigned> > FoldedChains;
312   // Original input chain(s).
313   std::vector<std::pair<std::string, std::string> > OrigChains;
314   std::set<std::string> Duplicates;
315
316   /// LSI - Load/Store information.
317   /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
318   /// for each memory access. This facilitates the use of AliasAnalysis in
319   /// the backend.
320   std::vector<std::string> LSI;
321
322   /// GeneratedCode - This is the buffer that we emit code to.  The first int
323   /// indicates whether this is an exit predicate (something that should be
324   /// tested, and if true, the match fails) [when 1], or normal code to emit
325   /// [when 0], or initialization code to emit [when 2].
326   std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
327   /// GeneratedDecl - This is the set of all SDOperand declarations needed for
328   /// the set of patterns for each top-level opcode.
329   std::set<std::string> &GeneratedDecl;
330   /// TargetOpcodes - The target specific opcodes used by the resulting
331   /// instructions.
332   std::vector<std::string> &TargetOpcodes;
333   std::vector<std::string> &TargetVTs;
334
335   std::string ChainName;
336   unsigned TmpNo;
337   unsigned OpcNo;
338   unsigned VTNo;
339   
340   void emitCheck(const std::string &S) {
341     if (!S.empty())
342       GeneratedCode.push_back(std::make_pair(1, S));
343   }
344   void emitCode(const std::string &S) {
345     if (!S.empty())
346       GeneratedCode.push_back(std::make_pair(0, S));
347   }
348   void emitInit(const std::string &S) {
349     if (!S.empty())
350       GeneratedCode.push_back(std::make_pair(2, S));
351   }
352   void emitDecl(const std::string &S) {
353     assert(!S.empty() && "Invalid declaration");
354     GeneratedDecl.insert(S);
355   }
356   void emitOpcode(const std::string &Opc) {
357     TargetOpcodes.push_back(Opc);
358     OpcNo++;
359   }
360   void emitVT(const std::string &VT) {
361     TargetVTs.push_back(VT);
362     VTNo++;
363   }
364 public:
365   PatternCodeEmitter(CodeGenDAGPatterns &cgp, ListInit *preds,
366                      TreePatternNode *pattern, TreePatternNode *instr,
367                      std::vector<std::pair<unsigned, std::string> > &gc,
368                      std::set<std::string> &gd,
369                      std::vector<std::string> &to,
370                      std::vector<std::string> &tv)
371   : CGP(cgp), Predicates(preds), Pattern(pattern), Instruction(instr),
372     GeneratedCode(gc), GeneratedDecl(gd),
373     TargetOpcodes(to), TargetVTs(tv),
374     TmpNo(0), OpcNo(0), VTNo(0) {}
375
376   /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
377   /// if the match fails. At this point, we already know that the opcode for N
378   /// matches, and the SDNode for the result has the RootName specified name.
379   void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
380                      const std::string &RootName, const std::string &ChainSuffix,
381                      bool &FoundChain) {
382
383     // Save loads/stores matched by a pattern.
384     if (!N->isLeaf() && N->getName().empty()) {
385       std::string EnumName = N->getOperator()->getValueAsString("Opcode");
386       if (EnumName == "ISD::LOAD" ||
387           EnumName == "ISD::STORE") {
388         LSI.push_back(RootName);
389       }
390     }
391
392     bool isRoot = (P == NULL);
393     // Emit instruction predicates. Each predicate is just a string for now.
394     if (isRoot) {
395       std::string PredicateCheck;
396       for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
397         if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
398           Record *Def = Pred->getDef();
399           if (!Def->isSubClassOf("Predicate")) {
400 #ifndef NDEBUG
401             Def->dump();
402 #endif
403             assert(0 && "Unknown predicate type!");
404           }
405           if (!PredicateCheck.empty())
406             PredicateCheck += " && ";
407           PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
408         }
409       }
410       
411       emitCheck(PredicateCheck);
412     }
413
414     if (N->isLeaf()) {
415       if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
416         emitCheck("cast<ConstantSDNode>(" + RootName +
417                   ")->getSignExtended() == " + itostr(II->getValue()));
418         return;
419       } else if (!NodeIsComplexPattern(N)) {
420         assert(0 && "Cannot match this as a leaf value!");
421         abort();
422       }
423     }
424   
425     // If this node has a name associated with it, capture it in VariableMap. If
426     // we already saw this in the pattern, emit code to verify dagness.
427     if (!N->getName().empty()) {
428       std::string &VarMapEntry = VariableMap[N->getName()];
429       if (VarMapEntry.empty()) {
430         VarMapEntry = RootName;
431       } else {
432         // If we get here, this is a second reference to a specific name.  Since
433         // we already have checked that the first reference is valid, we don't
434         // have to recursively match it, just check that it's the same as the
435         // previously named thing.
436         emitCheck(VarMapEntry + " == " + RootName);
437         return;
438       }
439
440       if (!N->isLeaf())
441         OperatorMap[N->getName()] = N->getOperator();
442     }
443
444
445     // Emit code to load the child nodes and match their contents recursively.
446     unsigned OpNo = 0;
447     bool NodeHasChain = NodeHasProperty   (N, SDNPHasChain, CGP);
448     bool HasChain     = PatternHasProperty(N, SDNPHasChain, CGP);
449     bool EmittedUseCheck = false;
450     if (HasChain) {
451       if (NodeHasChain)
452         OpNo = 1;
453       if (!isRoot) {
454         // Multiple uses of actual result?
455         emitCheck(RootName + ".hasOneUse()");
456         EmittedUseCheck = true;
457         if (NodeHasChain) {
458           // If the immediate use can somehow reach this node through another
459           // path, then can't fold it either or it will create a cycle.
460           // e.g. In the following diagram, XX can reach ld through YY. If
461           // ld is folded into XX, then YY is both a predecessor and a successor
462           // of XX.
463           //
464           //         [ld]
465           //         ^  ^
466           //         |  |
467           //        /   \---
468           //      /        [YY]
469           //      |         ^
470           //     [XX]-------|
471           bool NeedCheck = false;
472           if (P != Pattern)
473             NeedCheck = true;
474           else {
475             const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
476             NeedCheck =
477               P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
478               P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
479               P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
480               PInfo.getNumOperands() > 1 ||
481               PInfo.hasProperty(SDNPHasChain) ||
482               PInfo.hasProperty(SDNPInFlag) ||
483               PInfo.hasProperty(SDNPOptInFlag);
484           }
485
486           if (NeedCheck) {
487             std::string ParentName(RootName.begin(), RootName.end()-1);
488             emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
489                       ".Val, N.Val)");
490           }
491         }
492       }
493
494       if (NodeHasChain) {
495         if (FoundChain) {
496           emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
497                     "IsChainCompatible(" + ChainName + ".Val, " +
498                     RootName + ".Val))");
499           OrigChains.push_back(std::make_pair(ChainName, RootName));
500         } else
501           FoundChain = true;
502         ChainName = "Chain" + ChainSuffix;
503         emitInit("SDOperand " + ChainName + " = " + RootName +
504                  ".getOperand(0);");
505       }
506     }
507
508     // Don't fold any node which reads or writes a flag and has multiple uses.
509     // FIXME: We really need to separate the concepts of flag and "glue". Those
510     // real flag results, e.g. X86CMP output, can have multiple uses.
511     // FIXME: If the optional incoming flag does not exist. Then it is ok to
512     // fold it.
513     if (!isRoot &&
514         (PatternHasProperty(N, SDNPInFlag, CGP) ||
515          PatternHasProperty(N, SDNPOptInFlag, CGP) ||
516          PatternHasProperty(N, SDNPOutFlag, CGP))) {
517       if (!EmittedUseCheck) {
518         // Multiple uses of actual result?
519         emitCheck(RootName + ".hasOneUse()");
520       }
521     }
522
523     // If there is a node predicate for this, emit the call.
524     if (!N->getPredicateFn().empty())
525       emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
526
527     
528     // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
529     // a constant without a predicate fn that has more that one bit set, handle
530     // this as a special case.  This is usually for targets that have special
531     // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
532     // handling stuff).  Using these instructions is often far more efficient
533     // than materializing the constant.  Unfortunately, both the instcombiner
534     // and the dag combiner can often infer that bits are dead, and thus drop
535     // them from the mask in the dag.  For example, it might turn 'AND X, 255'
536     // into 'AND X, 254' if it knows the low bit is set.  Emit code that checks
537     // to handle this.
538     if (!N->isLeaf() && 
539         (N->getOperator()->getName() == "and" || 
540          N->getOperator()->getName() == "or") &&
541         N->getChild(1)->isLeaf() &&
542         N->getChild(1)->getPredicateFn().empty()) {
543       if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
544         if (!isPowerOf2_32(II->getValue())) {  // Don't bother with single bits.
545           emitInit("SDOperand " + RootName + "0" + " = " +
546                    RootName + ".getOperand(" + utostr(0) + ");");
547           emitInit("SDOperand " + RootName + "1" + " = " +
548                    RootName + ".getOperand(" + utostr(1) + ");");
549
550           emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
551           const char *MaskPredicate = N->getOperator()->getName() == "or"
552             ? "CheckOrMask(" : "CheckAndMask(";
553           emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
554                     RootName + "1), " + itostr(II->getValue()) + ")");
555           
556           EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
557                              ChainSuffix + utostr(0), FoundChain);
558           return;
559         }
560       }
561     }
562     
563     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
564       emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
565                RootName + ".getOperand(" +utostr(OpNo) + ");");
566
567       EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
568                          ChainSuffix + utostr(OpNo), FoundChain);
569     }
570
571     // Handle cases when root is a complex pattern.
572     const ComplexPattern *CP;
573     if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
574       std::string Fn = CP->getSelectFunc();
575       unsigned NumOps = CP->getNumOperands();
576       for (unsigned i = 0; i < NumOps; ++i) {
577         emitDecl("CPTmp" + utostr(i));
578         emitCode("SDOperand CPTmp" + utostr(i) + ";");
579       }
580       if (CP->hasProperty(SDNPHasChain)) {
581         emitDecl("CPInChain");
582         emitDecl("Chain" + ChainSuffix);
583         emitCode("SDOperand CPInChain;");
584         emitCode("SDOperand Chain" + ChainSuffix + ";");
585       }
586
587       std::string Code = Fn + "(" + RootName + ", " + RootName;
588       for (unsigned i = 0; i < NumOps; i++)
589         Code += ", CPTmp" + utostr(i);
590       if (CP->hasProperty(SDNPHasChain)) {
591         ChainName = "Chain" + ChainSuffix;
592         Code += ", CPInChain, Chain" + ChainSuffix;
593       }
594       emitCheck(Code + ")");
595     }
596   }
597
598   void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
599                           const std::string &RootName, 
600                           const std::string &ParentRootName,
601                           const std::string &ChainSuffix, bool &FoundChain) {
602     if (!Child->isLeaf()) {
603       // If it's not a leaf, recursively match.
604       const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
605       emitCheck(RootName + ".getOpcode() == " +
606                 CInfo.getEnumName());
607       EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
608       bool HasChain = false;
609       if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
610         HasChain = true;
611         FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
612       }
613       if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
614         assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
615                "Pattern folded multiple nodes which produce flags?");
616         FoldedFlag = std::make_pair(RootName,
617                                     CInfo.getNumResults() + (unsigned)HasChain);
618       }
619     } else {
620       // If this child has a name associated with it, capture it in VarMap. If
621       // we already saw this in the pattern, emit code to verify dagness.
622       if (!Child->getName().empty()) {
623         std::string &VarMapEntry = VariableMap[Child->getName()];
624         if (VarMapEntry.empty()) {
625           VarMapEntry = RootName;
626         } else {
627           // If we get here, this is a second reference to a specific name.
628           // Since we already have checked that the first reference is valid,
629           // we don't have to recursively match it, just check that it's the
630           // same as the previously named thing.
631           emitCheck(VarMapEntry + " == " + RootName);
632           Duplicates.insert(RootName);
633           return;
634         }
635       }
636       
637       // Handle leaves of various types.
638       if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
639         Record *LeafRec = DI->getDef();
640         if (LeafRec->isSubClassOf("RegisterClass") || 
641             LeafRec->getName() == "ptr_rc") {
642           // Handle register references.  Nothing to do here.
643         } else if (LeafRec->isSubClassOf("Register")) {
644           // Handle register references.
645         } else if (LeafRec->isSubClassOf("ComplexPattern")) {
646           // Handle complex pattern.
647           const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
648           std::string Fn = CP->getSelectFunc();
649           unsigned NumOps = CP->getNumOperands();
650           for (unsigned i = 0; i < NumOps; ++i) {
651             emitDecl("CPTmp" + utostr(i));
652             emitCode("SDOperand CPTmp" + utostr(i) + ";");
653           }
654           if (CP->hasProperty(SDNPHasChain)) {
655             const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
656             FoldedChains.push_back(std::make_pair("CPInChain",
657                                                   PInfo.getNumResults()));
658             ChainName = "Chain" + ChainSuffix;
659             emitDecl("CPInChain");
660             emitDecl(ChainName);
661             emitCode("SDOperand CPInChain;");
662             emitCode("SDOperand " + ChainName + ";");
663           }
664           
665           std::string Code = Fn + "(";
666           if (CP->hasAttribute(CPAttrParentAsRoot)) {
667             Code += ParentRootName + ", ";
668           } else {
669             Code += "N, ";
670           }
671           if (CP->hasProperty(SDNPHasChain)) {
672             std::string ParentName(RootName.begin(), RootName.end()-1);
673             Code += ParentName + ", ";
674           }
675           Code += RootName;
676           for (unsigned i = 0; i < NumOps; i++)
677             Code += ", CPTmp" + utostr(i);
678           if (CP->hasProperty(SDNPHasChain))
679             Code += ", CPInChain, Chain" + ChainSuffix;
680           emitCheck(Code + ")");
681         } else if (LeafRec->getName() == "srcvalue") {
682           // Place holder for SRCVALUE nodes. Nothing to do here.
683         } else if (LeafRec->isSubClassOf("ValueType")) {
684           // Make sure this is the specified value type.
685           emitCheck("cast<VTSDNode>(" + RootName +
686                     ")->getVT() == MVT::" + LeafRec->getName());
687         } else if (LeafRec->isSubClassOf("CondCode")) {
688           // Make sure this is the specified cond code.
689           emitCheck("cast<CondCodeSDNode>(" + RootName +
690                     ")->get() == ISD::" + LeafRec->getName());
691         } else {
692 #ifndef NDEBUG
693           Child->dump();
694           cerr << " ";
695 #endif
696           assert(0 && "Unknown leaf type!");
697         }
698         
699         // If there is a node predicate for this, emit the call.
700         if (!Child->getPredicateFn().empty())
701           emitCheck(Child->getPredicateFn() + "(" + RootName +
702                     ".Val)");
703       } else if (IntInit *II =
704                  dynamic_cast<IntInit*>(Child->getLeafValue())) {
705         emitCheck("isa<ConstantSDNode>(" + RootName + ")");
706         unsigned CTmp = TmpNo++;
707         emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
708                  RootName + ")->getSignExtended();");
709         
710         emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
711       } else {
712 #ifndef NDEBUG
713         Child->dump();
714 #endif
715         assert(0 && "Unknown leaf type!");
716       }
717     }
718   }
719
720   /// EmitResultCode - Emit the action for a pattern.  Now that it has matched
721   /// we actually have to build a DAG!
722   std::vector<std::string>
723   EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
724                  bool InFlagDecled, bool ResNodeDecled,
725                  bool LikeLeaf = false, bool isRoot = false) {
726     // List of arguments of getTargetNode() or SelectNodeTo().
727     std::vector<std::string> NodeOps;
728     // This is something selected from the pattern we matched.
729     if (!N->getName().empty()) {
730       const std::string &VarName = N->getName();
731       std::string Val = VariableMap[VarName];
732       bool ModifiedVal = false;
733       assert(!Val.empty() &&
734              "Variable referenced but not defined and not caught earlier!");
735       if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
736         // Already selected this operand, just return the tmpval.
737         NodeOps.push_back(Val);
738         return NodeOps;
739       }
740
741       const ComplexPattern *CP;
742       unsigned ResNo = TmpNo++;
743       if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
744         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
745         std::string CastType;
746         std::string TmpVar =  "Tmp" + utostr(ResNo);
747         switch (N->getTypeNum(0)) {
748         default:
749           cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
750                << " type as an immediate constant. Aborting\n";
751           abort();
752         case MVT::i1:  CastType = "bool"; break;
753         case MVT::i8:  CastType = "unsigned char"; break;
754         case MVT::i16: CastType = "unsigned short"; break;
755         case MVT::i32: CastType = "unsigned"; break;
756         case MVT::i64: CastType = "uint64_t"; break;
757         }
758         emitCode("SDOperand " + TmpVar + 
759                  " = CurDAG->getTargetConstant(((" + CastType +
760                  ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
761                  getEnumName(N->getTypeNum(0)) + ");");
762         // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
763         // value if used multiple times by this pattern result.
764         Val = TmpVar;
765         ModifiedVal = true;
766         NodeOps.push_back(Val);
767       } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
768         Record *Op = OperatorMap[N->getName()];
769         // Transform ExternalSymbol to TargetExternalSymbol
770         if (Op && Op->getName() == "externalsym") {
771           std::string TmpVar = "Tmp"+utostr(ResNo);
772           emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
773                    "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
774                    Val + ")->getSymbol(), " +
775                    getEnumName(N->getTypeNum(0)) + ");");
776           // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
777           // this value if used multiple times by this pattern result.
778           Val = TmpVar;
779           ModifiedVal = true;
780         }
781         NodeOps.push_back(Val);
782       } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
783                  || N->getOperator()->getName() == "tglobaltlsaddr")) {
784         Record *Op = OperatorMap[N->getName()];
785         // Transform GlobalAddress to TargetGlobalAddress
786         if (Op && (Op->getName() == "globaladdr" ||
787                    Op->getName() == "globaltlsaddr")) {
788           std::string TmpVar = "Tmp" + utostr(ResNo);
789           emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
790                    "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
791                    ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
792                    ");");
793           // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
794           // this value if used multiple times by this pattern result.
795           Val = TmpVar;
796           ModifiedVal = true;
797         }
798         NodeOps.push_back(Val);
799       } else if (!N->isLeaf()
800                  && (N->getOperator()->getName() == "texternalsym"
801                       || N->getOperator()->getName() == "tconstpool")) {
802         // Do not rewrite the variable name, since we don't generate a new
803         // temporary.
804         NodeOps.push_back(Val);
805       } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
806         for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
807           emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
808           NodeOps.push_back("CPTmp" + utostr(i));
809         }
810       } else {
811         // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
812         // node even if it isn't one. Don't select it.
813         if (!LikeLeaf) {
814           emitCode("AddToISelQueue(" + Val + ");");
815           if (isRoot && N->isLeaf()) {
816             emitCode("ReplaceUses(N, " + Val + ");");
817             emitCode("return NULL;");
818           }
819         }
820         NodeOps.push_back(Val);
821       }
822
823       if (ModifiedVal) {
824         VariableMap[VarName] = Val;
825       }
826       return NodeOps;
827     }
828     if (N->isLeaf()) {
829       // If this is an explicit register reference, handle it.
830       if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
831         unsigned ResNo = TmpNo++;
832         if (DI->getDef()->isSubClassOf("Register")) {
833           emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
834                    getQualifiedName(DI->getDef()) + ", " +
835                    getEnumName(N->getTypeNum(0)) + ");");
836           NodeOps.push_back("Tmp" + utostr(ResNo));
837           return NodeOps;
838         } else if (DI->getDef()->getName() == "zero_reg") {
839           emitCode("SDOperand Tmp" + utostr(ResNo) +
840                    " = CurDAG->getRegister(0, " +
841                    getEnumName(N->getTypeNum(0)) + ");");
842           NodeOps.push_back("Tmp" + utostr(ResNo));
843           return NodeOps;
844         }
845       } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
846         unsigned ResNo = TmpNo++;
847         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
848         emitCode("SDOperand Tmp" + utostr(ResNo) + 
849                  " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
850                  ", " + getEnumName(N->getTypeNum(0)) + ");");
851         NodeOps.push_back("Tmp" + utostr(ResNo));
852         return NodeOps;
853       }
854     
855 #ifndef NDEBUG
856       N->dump();
857 #endif
858       assert(0 && "Unknown leaf type!");
859       return NodeOps;
860     }
861
862     Record *Op = N->getOperator();
863     if (Op->isSubClassOf("Instruction")) {
864       const CodeGenTarget &CGT = CGP.getTargetInfo();
865       CodeGenInstruction &II = CGT.getInstruction(Op->getName());
866       const DAGInstruction &Inst = CGP.getInstruction(Op);
867       const TreePattern *InstPat = Inst.getPattern();
868       // FIXME: Assume actual pattern comes before "implicit".
869       TreePatternNode *InstPatNode =
870         isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
871                : (InstPat ? InstPat->getTree(0) : NULL);
872       if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
873         InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
874       }
875       bool HasVarOps     = isRoot && II.isVariadic;
876       // FIXME: fix how we deal with physical register operands.
877       bool HasImpInputs  = isRoot && Inst.getNumImpOperands() > 0;
878       bool HasImpResults = isRoot && DstRegs.size() > 0;
879       bool NodeHasOptInFlag = isRoot &&
880         PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
881       bool NodeHasInFlag  = isRoot &&
882         PatternHasProperty(Pattern, SDNPInFlag, CGP);
883       bool NodeHasOutFlag = isRoot &&
884         PatternHasProperty(Pattern, SDNPOutFlag, CGP);
885       bool NodeHasChain = InstPatNode &&
886         PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
887       bool InputHasChain = isRoot &&
888         NodeHasProperty(Pattern, SDNPHasChain, CGP);
889       unsigned NumResults = Inst.getNumResults();    
890       unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
891
892       if (NodeHasOptInFlag) {
893         emitCode("bool HasInFlag = "
894            "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
895       }
896       if (HasVarOps)
897         emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
898
899       // How many results is this pattern expected to produce?
900       unsigned NumPatResults = 0;
901       for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
902         MVT::ValueType VT = Pattern->getTypeNum(i);
903         if (VT != MVT::isVoid && VT != MVT::Flag)
904           NumPatResults++;
905       }
906
907       if (OrigChains.size() > 0) {
908         // The original input chain is being ignored. If it is not just
909         // pointing to the op that's being folded, we should create a
910         // TokenFactor with it and the chain of the folded op as the new chain.
911         // We could potentially be doing multiple levels of folding, in that
912         // case, the TokenFactor can have more operands.
913         emitCode("SmallVector<SDOperand, 8> InChains;");
914         for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
915           emitCode("if (" + OrigChains[i].first + ".Val != " +
916                    OrigChains[i].second + ".Val) {");
917           emitCode("  AddToISelQueue(" + OrigChains[i].first + ");");
918           emitCode("  InChains.push_back(" + OrigChains[i].first + ");");
919           emitCode("}");
920         }
921         emitCode("AddToISelQueue(" + ChainName + ");");
922         emitCode("InChains.push_back(" + ChainName + ");");
923         emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
924                  "&InChains[0], InChains.size());");
925       }
926
927       // Loop over all of the operands of the instruction pattern, emitting code
928       // to fill them all in.  The node 'N' usually has number children equal to
929       // the number of input operands of the instruction.  However, in cases
930       // where there are predicate operands for an instruction, we need to fill
931       // in the 'execute always' values.  Match up the node operands to the
932       // instruction operands to do this.
933       std::vector<std::string> AllOps;
934       unsigned NumEAInputs = 0; // # of synthesized 'execute always' inputs.
935       for (unsigned ChildNo = 0, InstOpNo = NumResults;
936            InstOpNo != II.OperandList.size(); ++InstOpNo) {
937         std::vector<std::string> Ops;
938         
939         // If this is a normal operand or a predicate operand without
940         // 'execute always', emit it.
941         Record *OperandNode = II.OperandList[InstOpNo].Rec;
942         if ((!OperandNode->isSubClassOf("PredicateOperand") &&
943              !OperandNode->isSubClassOf("OptionalDefOperand")) ||
944             CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
945           Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
946                                InFlagDecled, ResNodeDecled);
947           AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
948           ++ChildNo;
949         } else {
950           // Otherwise, this is a predicate or optional def operand, emit the
951           // 'default ops' operands.
952           const DAGDefaultOperand &DefaultOp =
953             CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
954           for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
955             Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
956                                  InFlagDecled, ResNodeDecled);
957             AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
958             NumEAInputs += Ops.size();
959           }
960         }
961       }
962
963       // Generate MemOperandSDNodes nodes for each memory accesses covered by this
964       // pattern.
965       if (isRoot) {
966         std::vector<std::string>::const_iterator mi, mie;
967         for (mi = LSI.begin(), mie = LSI.end(); mi != mie; ++mi) {
968           emitCode("SDOperand LSI_" + *mi + " = "
969                    "CurDAG->getMemOperand(cast<LSBaseSDNode>(" +
970                    *mi + ")->getMemOperand());");
971           AllOps.push_back("LSI_" + *mi);
972         }
973       }
974
975       // Emit all the chain and CopyToReg stuff.
976       bool ChainEmitted = NodeHasChain;
977       if (NodeHasChain)
978         emitCode("AddToISelQueue(" + ChainName + ");");
979       if (NodeHasInFlag || HasImpInputs)
980         EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
981                              InFlagDecled, ResNodeDecled, true);
982       if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
983         if (!InFlagDecled) {
984           emitCode("SDOperand InFlag(0, 0);");
985           InFlagDecled = true;
986         }
987         if (NodeHasOptInFlag) {
988           emitCode("if (HasInFlag) {");
989           emitCode("  InFlag = N.getOperand(N.getNumOperands()-1);");
990           emitCode("  AddToISelQueue(InFlag);");
991           emitCode("}");
992         }
993       }
994
995       unsigned ResNo = TmpNo++;
996       if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
997           NodeHasOptInFlag || HasImpResults) {
998         std::string Code;
999         std::string Code2;
1000         std::string NodeName;
1001         if (!isRoot) {
1002           NodeName = "Tmp" + utostr(ResNo);
1003           Code2 = "SDOperand " + NodeName + "(";
1004         } else {
1005           NodeName = "ResNode";
1006           if (!ResNodeDecled) {
1007             Code2 = "SDNode *" + NodeName + " = ";
1008             ResNodeDecled = true;
1009           } else
1010             Code2 = NodeName + " = ";
1011         }
1012
1013         Code += "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
1014         unsigned OpsNo = OpcNo;
1015         emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1016
1017         // Output order: results, chain, flags
1018         // Result types.
1019         if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1020           Code += ", VT" + utostr(VTNo);
1021           emitVT(getEnumName(N->getTypeNum(0)));
1022         }
1023         // Add types for implicit results in physical registers, scheduler will
1024         // care of adding copyfromreg nodes.
1025         for (unsigned i = 0; i < NumDstRegs; i++) {
1026           Record *RR = DstRegs[i];
1027           if (RR->isSubClassOf("Register")) {
1028             MVT::ValueType RVT = getRegisterValueType(RR, CGT);
1029             Code += ", " + getEnumName(RVT);
1030           }
1031         }
1032         if (NodeHasChain)
1033           Code += ", MVT::Other";
1034         if (NodeHasOutFlag)
1035           Code += ", MVT::Flag";
1036
1037         // Figure out how many fixed inputs the node has.  This is important to
1038         // know which inputs are the variable ones if present.
1039         unsigned NumInputs = AllOps.size();
1040         NumInputs += NodeHasChain;
1041         
1042         // Inputs.
1043         if (HasVarOps) {
1044           for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1045             emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1046           AllOps.clear();
1047         }
1048
1049         if (HasVarOps) {
1050           // Figure out whether any operands at the end of the op list are not
1051           // part of the variable section.
1052           std::string EndAdjust;
1053           if (NodeHasInFlag || HasImpInputs)
1054             EndAdjust = "-1";  // Always has one flag.
1055           else if (NodeHasOptInFlag)
1056             EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1057
1058           emitCode("for (unsigned i = " + utostr(NumInputs - NumEAInputs) +
1059                    ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1060
1061           emitCode("  AddToISelQueue(N.getOperand(i));");
1062           emitCode("  Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1063           emitCode("}");
1064         }
1065
1066         if (NodeHasChain) {
1067           if (HasVarOps)
1068             emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1069           else
1070             AllOps.push_back(ChainName);
1071         }
1072
1073         if (HasVarOps) {
1074           if (NodeHasInFlag || HasImpInputs)
1075             emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1076           else if (NodeHasOptInFlag) {
1077             emitCode("if (HasInFlag)");
1078             emitCode("  Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1079           }
1080           Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1081             ".size()";
1082         } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1083           AllOps.push_back("InFlag");
1084
1085         unsigned NumOps = AllOps.size();
1086         if (NumOps) {
1087           if (!NodeHasOptInFlag && NumOps < 4) {
1088             for (unsigned i = 0; i != NumOps; ++i)
1089               Code += ", " + AllOps[i];
1090           } else {
1091             std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
1092             for (unsigned i = 0; i != NumOps; ++i) {
1093               OpsCode += AllOps[i];
1094               if (i != NumOps-1)
1095                 OpsCode += ", ";
1096             }
1097             emitCode(OpsCode + " };");
1098             Code += ", Ops" + utostr(OpsNo) + ", ";
1099             if (NodeHasOptInFlag) {
1100               Code += "HasInFlag ? ";
1101               Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1102             } else
1103               Code += utostr(NumOps);
1104           }
1105         }
1106             
1107         if (!isRoot)
1108           Code += "), 0";
1109         emitCode(Code2 + Code + ");");
1110
1111         if (NodeHasChain)
1112           // Remember which op produces the chain.
1113           if (!isRoot)
1114             emitCode(ChainName + " = SDOperand(" + NodeName +
1115                      ".Val, " + utostr(NumResults+NumDstRegs) + ");");
1116           else
1117             emitCode(ChainName + " = SDOperand(" + NodeName +
1118                      ", " + utostr(NumResults+NumDstRegs) + ");");
1119
1120         if (!isRoot) {
1121           NodeOps.push_back("Tmp" + utostr(ResNo));
1122           return NodeOps;
1123         }
1124
1125         bool NeedReplace = false;
1126         if (NodeHasOutFlag) {
1127           if (!InFlagDecled) {
1128             emitCode("SDOperand InFlag(ResNode, " + 
1129                    utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
1130             InFlagDecled = true;
1131           } else
1132             emitCode("InFlag = SDOperand(ResNode, " + 
1133                    utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
1134         }
1135
1136         if (FoldedChains.size() > 0) {
1137           std::string Code;
1138           for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
1139             emitCode("ReplaceUses(SDOperand(" +
1140                      FoldedChains[j].first + ".Val, " + 
1141                      utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
1142                      utostr(NumResults+NumDstRegs) + "));");
1143           NeedReplace = true;
1144         }
1145
1146         if (NodeHasOutFlag) {
1147           if (FoldedFlag.first != "") {
1148             emitCode("ReplaceUses(SDOperand(" + FoldedFlag.first + ".Val, " +
1149                      utostr(FoldedFlag.second) + "), InFlag);");
1150           } else {
1151             assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
1152             emitCode("ReplaceUses(SDOperand(N.Val, " +
1153                      utostr(NumPatResults + (unsigned)InputHasChain)
1154                      +"), InFlag);");
1155           }
1156           NeedReplace = true;
1157         }
1158
1159         if (NeedReplace && InputHasChain)
1160           emitCode("ReplaceUses(SDOperand(N.Val, " + 
1161                    utostr(NumPatResults) + "), SDOperand(" + ChainName
1162                    + ".Val, " + ChainName + ".ResNo" + "));");
1163
1164         // User does not expect the instruction would produce a chain!
1165         if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1166           ;
1167         } else if (InputHasChain && !NodeHasChain) {
1168           // One of the inner node produces a chain.
1169           if (NodeHasOutFlag)
1170             emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults+1) +
1171                      "), SDOperand(ResNode, N.ResNo-1));");
1172           emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults) +
1173                    "), " + ChainName + ");");
1174         }
1175
1176         emitCode("return ResNode;");
1177       } else {
1178         std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
1179           utostr(OpcNo);
1180         if (N->getTypeNum(0) != MVT::isVoid)
1181           Code += ", VT" + utostr(VTNo);
1182         if (NodeHasOutFlag)
1183           Code += ", MVT::Flag";
1184
1185         if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1186           AllOps.push_back("InFlag");
1187
1188         unsigned NumOps = AllOps.size();
1189         if (NumOps) {
1190           if (!NodeHasOptInFlag && NumOps < 4) {
1191             for (unsigned i = 0; i != NumOps; ++i)
1192               Code += ", " + AllOps[i];
1193           } else {
1194             std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
1195             for (unsigned i = 0; i != NumOps; ++i) {
1196               OpsCode += AllOps[i];
1197               if (i != NumOps-1)
1198                 OpsCode += ", ";
1199             }
1200             emitCode(OpsCode + " };");
1201             Code += ", Ops" + utostr(OpcNo) + ", ";
1202             Code += utostr(NumOps);
1203           }
1204         }
1205         emitCode(Code + ");");
1206         emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1207         if (N->getTypeNum(0) != MVT::isVoid)
1208           emitVT(getEnumName(N->getTypeNum(0)));
1209       }
1210
1211       return NodeOps;
1212     } else if (Op->isSubClassOf("SDNodeXForm")) {
1213       assert(N->getNumChildren() == 1 && "node xform should have one child!");
1214       // PatLeaf node - the operand may or may not be a leaf node. But it should
1215       // behave like one.
1216       std::vector<std::string> Ops =
1217         EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1218                        ResNodeDecled, true);
1219       unsigned ResNo = TmpNo++;
1220       emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1221                + "(" + Ops.back() + ".Val);");
1222       NodeOps.push_back("Tmp" + utostr(ResNo));
1223       if (isRoot)
1224         emitCode("return Tmp" + utostr(ResNo) + ".Val;");
1225       return NodeOps;
1226     } else {
1227       N->dump();
1228       cerr << "\n";
1229       throw std::string("Unknown node in result pattern!");
1230     }
1231   }
1232
1233   /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1234   /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that 
1235   /// 'Pat' may be missing types.  If we find an unresolved type to add a check
1236   /// for, this returns true otherwise false if Pat has all types.
1237   bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1238                           const std::string &Prefix, bool isRoot = false) {
1239     // Did we find one?
1240     if (Pat->getExtTypes() != Other->getExtTypes()) {
1241       // Move a type over from 'other' to 'pat'.
1242       Pat->setTypes(Other->getExtTypes());
1243       // The top level node type is checked outside of the select function.
1244       if (!isRoot)
1245         emitCheck(Prefix + ".Val->getValueType(0) == " +
1246                   getName(Pat->getTypeNum(0)));
1247       return true;
1248     }
1249   
1250     unsigned OpNo =
1251       (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1252     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1253       if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1254                              Prefix + utostr(OpNo)))
1255         return true;
1256     return false;
1257   }
1258
1259 private:
1260   /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1261   /// being built.
1262   void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1263                             bool &ChainEmitted, bool &InFlagDecled,
1264                             bool &ResNodeDecled, bool isRoot = false) {
1265     const CodeGenTarget &T = CGP.getTargetInfo();
1266     unsigned OpNo =
1267       (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1268     bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1269     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1270       TreePatternNode *Child = N->getChild(i);
1271       if (!Child->isLeaf()) {
1272         EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1273                              InFlagDecled, ResNodeDecled);
1274       } else {
1275         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1276           if (!Child->getName().empty()) {
1277             std::string Name = RootName + utostr(OpNo);
1278             if (Duplicates.find(Name) != Duplicates.end())
1279               // A duplicate! Do not emit a copy for this node.
1280               continue;
1281           }
1282
1283           Record *RR = DI->getDef();
1284           if (RR->isSubClassOf("Register")) {
1285             MVT::ValueType RVT = getRegisterValueType(RR, T);
1286             if (RVT == MVT::Flag) {
1287               if (!InFlagDecled) {
1288                 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
1289                 InFlagDecled = true;
1290               } else
1291                 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1292               emitCode("AddToISelQueue(InFlag);");
1293             } else {
1294               if (!ChainEmitted) {
1295                 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
1296                 ChainName = "Chain";
1297                 ChainEmitted = true;
1298               }
1299               emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1300               if (!InFlagDecled) {
1301                 emitCode("SDOperand InFlag(0, 0);");
1302                 InFlagDecled = true;
1303               }
1304               std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1305               emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1306                        ", " + getQualifiedName(RR) +
1307                        ", " +  RootName + utostr(OpNo) + ", InFlag).Val;");
1308               ResNodeDecled = true;
1309               emitCode(ChainName + " = SDOperand(ResNode, 0);");
1310               emitCode("InFlag = SDOperand(ResNode, 1);");
1311             }
1312           }
1313         }
1314       }
1315     }
1316
1317     if (HasInFlag) {
1318       if (!InFlagDecled) {
1319         emitCode("SDOperand InFlag = " + RootName +
1320                ".getOperand(" + utostr(OpNo) + ");");
1321         InFlagDecled = true;
1322       } else
1323         emitCode("InFlag = " + RootName +
1324                ".getOperand(" + utostr(OpNo) + ");");
1325       emitCode("AddToISelQueue(InFlag);");
1326     }
1327   }
1328 };
1329
1330 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1331 /// stream to match the pattern, and generate the code for the match if it
1332 /// succeeds.  Returns true if the pattern is not guaranteed to match.
1333 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1334                   std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1335                                            std::set<std::string> &GeneratedDecl,
1336                                         std::vector<std::string> &TargetOpcodes,
1337                                           std::vector<std::string> &TargetVTs) {
1338   PatternCodeEmitter Emitter(CGP, Pattern.getPredicates(),
1339                              Pattern.getSrcPattern(), Pattern.getDstPattern(),
1340                              GeneratedCode, GeneratedDecl,
1341                              TargetOpcodes, TargetVTs);
1342
1343   // Emit the matcher, capturing named arguments in VariableMap.
1344   bool FoundChain = false;
1345   Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1346
1347   // TP - Get *SOME* tree pattern, we don't care which.
1348   TreePattern &TP = *CGP.pf_begin()->second;
1349   
1350   // At this point, we know that we structurally match the pattern, but the
1351   // types of the nodes may not match.  Figure out the fewest number of type 
1352   // comparisons we need to emit.  For example, if there is only one integer
1353   // type supported by a target, there should be no type comparisons at all for
1354   // integer patterns!
1355   //
1356   // To figure out the fewest number of type checks needed, clone the pattern,
1357   // remove the types, then perform type inference on the pattern as a whole.
1358   // If there are unresolved types, emit an explicit check for those types,
1359   // apply the type to the tree, then rerun type inference.  Iterate until all
1360   // types are resolved.
1361   //
1362   TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1363   RemoveAllTypes(Pat);
1364   
1365   do {
1366     // Resolve/propagate as many types as possible.
1367     try {
1368       bool MadeChange = true;
1369       while (MadeChange)
1370         MadeChange = Pat->ApplyTypeConstraints(TP,
1371                                                true/*Ignore reg constraints*/);
1372     } catch (...) {
1373       assert(0 && "Error: could not find consistent types for something we"
1374              " already decided was ok!");
1375       abort();
1376     }
1377
1378     // Insert a check for an unresolved type and add it to the tree.  If we find
1379     // an unresolved type to add a check for, this returns true and we iterate,
1380     // otherwise we are done.
1381   } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1382
1383   Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1384                          false, false, false, true);
1385   delete Pat;
1386 }
1387
1388 /// EraseCodeLine - Erase one code line from all of the patterns.  If removing
1389 /// a line causes any of them to be empty, remove them and return true when
1390 /// done.
1391 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*, 
1392                           std::vector<std::pair<unsigned, std::string> > > >
1393                           &Patterns) {
1394   bool ErasedPatterns = false;
1395   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1396     Patterns[i].second.pop_back();
1397     if (Patterns[i].second.empty()) {
1398       Patterns.erase(Patterns.begin()+i);
1399       --i; --e;
1400       ErasedPatterns = true;
1401     }
1402   }
1403   return ErasedPatterns;
1404 }
1405
1406 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1407 /// code together between the patterns.
1408 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*, 
1409                               std::vector<std::pair<unsigned, std::string> > > >
1410                                   &Patterns, unsigned Indent,
1411                                   std::ostream &OS) {
1412   typedef std::pair<unsigned, std::string> CodeLine;
1413   typedef std::vector<CodeLine> CodeList;
1414   typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1415   
1416   if (Patterns.empty()) return;
1417   
1418   // Figure out how many patterns share the next code line.  Explicitly copy
1419   // FirstCodeLine so that we don't invalidate a reference when changing
1420   // Patterns.
1421   const CodeLine FirstCodeLine = Patterns.back().second.back();
1422   unsigned LastMatch = Patterns.size()-1;
1423   while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1424     --LastMatch;
1425   
1426   // If not all patterns share this line, split the list into two pieces.  The
1427   // first chunk will use this line, the second chunk won't.
1428   if (LastMatch != 0) {
1429     PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1430     PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1431     
1432     // FIXME: Emit braces?
1433     if (Shared.size() == 1) {
1434       const PatternToMatch &Pattern = *Shared.back().first;
1435       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1436       Pattern.getSrcPattern()->print(OS);
1437       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1438       Pattern.getDstPattern()->print(OS);
1439       OS << "\n";
1440       unsigned AddedComplexity = Pattern.getAddedComplexity();
1441       OS << std::string(Indent, ' ') << "// Pattern complexity = "
1442          << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1443          << "  cost = "
1444          << getResultPatternCost(Pattern.getDstPattern(), CGP)
1445          << "  size = "
1446          << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1447     }
1448     if (FirstCodeLine.first != 1) {
1449       OS << std::string(Indent, ' ') << "{\n";
1450       Indent += 2;
1451     }
1452     EmitPatterns(Shared, Indent, OS);
1453     if (FirstCodeLine.first != 1) {
1454       Indent -= 2;
1455       OS << std::string(Indent, ' ') << "}\n";
1456     }
1457     
1458     if (Other.size() == 1) {
1459       const PatternToMatch &Pattern = *Other.back().first;
1460       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1461       Pattern.getSrcPattern()->print(OS);
1462       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1463       Pattern.getDstPattern()->print(OS);
1464       OS << "\n";
1465       unsigned AddedComplexity = Pattern.getAddedComplexity();
1466       OS << std::string(Indent, ' ') << "// Pattern complexity = "
1467          << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1468          << "  cost = "
1469          << getResultPatternCost(Pattern.getDstPattern(), CGP)
1470          << "  size = "
1471          << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1472     }
1473     EmitPatterns(Other, Indent, OS);
1474     return;
1475   }
1476   
1477   // Remove this code from all of the patterns that share it.
1478   bool ErasedPatterns = EraseCodeLine(Patterns);
1479   
1480   bool isPredicate = FirstCodeLine.first == 1;
1481   
1482   // Otherwise, every pattern in the list has this line.  Emit it.
1483   if (!isPredicate) {
1484     // Normal code.
1485     OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1486   } else {
1487     OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1488     
1489     // If the next code line is another predicate, and if all of the pattern
1490     // in this group share the same next line, emit it inline now.  Do this
1491     // until we run out of common predicates.
1492     while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1493       // Check that all of fhe patterns in Patterns end with the same predicate.
1494       bool AllEndWithSamePredicate = true;
1495       for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1496         if (Patterns[i].second.back() != Patterns.back().second.back()) {
1497           AllEndWithSamePredicate = false;
1498           break;
1499         }
1500       // If all of the predicates aren't the same, we can't share them.
1501       if (!AllEndWithSamePredicate) break;
1502       
1503       // Otherwise we can.  Emit it shared now.
1504       OS << " &&\n" << std::string(Indent+4, ' ')
1505          << Patterns.back().second.back().second;
1506       ErasedPatterns = EraseCodeLine(Patterns);
1507     }
1508     
1509     OS << ") {\n";
1510     Indent += 2;
1511   }
1512   
1513   EmitPatterns(Patterns, Indent, OS);
1514   
1515   if (isPredicate)
1516     OS << std::string(Indent-2, ' ') << "}\n";
1517 }
1518
1519 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
1520   return CGP.getSDNodeInfo(Op).getEnumName();
1521 }
1522
1523 static std::string getLegalCName(std::string OpName) {
1524   std::string::size_type pos = OpName.find("::");
1525   if (pos != std::string::npos)
1526     OpName.replace(pos, 2, "_");
1527   return OpName;
1528 }
1529
1530 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1531   const CodeGenTarget &Target = CGP.getTargetInfo();
1532   
1533   // Get the namespace to insert instructions into.  Make sure not to pick up
1534   // "TargetInstrInfo" by accidentally getting the namespace off the PHI
1535   // instruction or something.
1536   std::string InstNS;
1537   for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
1538        e = Target.inst_end(); i != e; ++i) {
1539     InstNS = i->second.Namespace;
1540     if (InstNS != "TargetInstrInfo")
1541       break;
1542   }
1543   
1544   if (!InstNS.empty()) InstNS += "::";
1545   
1546   // Group the patterns by their top-level opcodes.
1547   std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1548   // All unique target node emission functions.
1549   std::map<std::string, unsigned> EmitFunctions;
1550   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1551        E = CGP.ptm_end(); I != E; ++I) {
1552     const PatternToMatch &Pattern = *I;
1553
1554     TreePatternNode *Node = Pattern.getSrcPattern();
1555     if (!Node->isLeaf()) {
1556       PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1557         push_back(&Pattern);
1558     } else {
1559       const ComplexPattern *CP;
1560       if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1561         PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1562           push_back(&Pattern);
1563       } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1564         std::vector<Record*> OpNodes = CP->getRootNodes();
1565         for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1566           PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1567             .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1568                     &Pattern);
1569         }
1570       } else {
1571         cerr << "Unrecognized opcode '";
1572         Node->dump();
1573         cerr << "' on tree pattern '";
1574         cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1575         exit(1);
1576       }
1577     }
1578   }
1579
1580   // For each opcode, there might be multiple select functions, one per
1581   // ValueType of the node (or its first operand if it doesn't produce a
1582   // non-chain result.
1583   std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1584
1585   // Emit one Select_* method for each top-level opcode.  We do this instead of
1586   // emitting one giant switch statement to support compilers where this will
1587   // result in the recursive functions taking less stack space.
1588   for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1589          PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1590        PBOI != E; ++PBOI) {
1591     const std::string &OpName = PBOI->first;
1592     std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1593     assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1594
1595     // We want to emit all of the matching code now.  However, we want to emit
1596     // the matches in order of minimal cost.  Sort the patterns so the least
1597     // cost one is at the start.
1598     std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
1599                      PatternSortingPredicate(CGP));
1600
1601     // Split them into groups by type.
1602     std::map<MVT::ValueType, std::vector<const PatternToMatch*> >PatternsByType;
1603     for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1604       const PatternToMatch *Pat = PatternsOfOp[i];
1605       TreePatternNode *SrcPat = Pat->getSrcPattern();
1606       MVT::ValueType VT = SrcPat->getTypeNum(0);
1607       std::map<MVT::ValueType, 
1608                std::vector<const PatternToMatch*> >::iterator TI = 
1609         PatternsByType.find(VT);
1610       if (TI != PatternsByType.end())
1611         TI->second.push_back(Pat);
1612       else {
1613         std::vector<const PatternToMatch*> PVec;
1614         PVec.push_back(Pat);
1615         PatternsByType.insert(std::make_pair(VT, PVec));
1616       }
1617     }
1618
1619     for (std::map<MVT::ValueType, std::vector<const PatternToMatch*> >::iterator
1620            II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1621          ++II) {
1622       MVT::ValueType OpVT = II->first;
1623       std::vector<const PatternToMatch*> &Patterns = II->second;
1624       typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1625       typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
1626     
1627       std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1628       std::vector<std::vector<std::string> > PatternOpcodes;
1629       std::vector<std::vector<std::string> > PatternVTs;
1630       std::vector<std::set<std::string> > PatternDecls;
1631       for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1632         CodeList GeneratedCode;
1633         std::set<std::string> GeneratedDecl;
1634         std::vector<std::string> TargetOpcodes;
1635         std::vector<std::string> TargetVTs;
1636         GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1637                                TargetOpcodes, TargetVTs);
1638         CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1639         PatternDecls.push_back(GeneratedDecl);
1640         PatternOpcodes.push_back(TargetOpcodes);
1641         PatternVTs.push_back(TargetVTs);
1642       }
1643     
1644       // Scan the code to see if all of the patterns are reachable and if it is
1645       // possible that the last one might not match.
1646       bool mightNotMatch = true;
1647       for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1648         CodeList &GeneratedCode = CodeForPatterns[i].second;
1649         mightNotMatch = false;
1650
1651         for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1652           if (GeneratedCode[j].first == 1) { // predicate.
1653             mightNotMatch = true;
1654             break;
1655           }
1656         }
1657       
1658         // If this pattern definitely matches, and if it isn't the last one, the
1659         // patterns after it CANNOT ever match.  Error out.
1660         if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1661           cerr << "Pattern '";
1662           CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1663           cerr << "' is impossible to select!\n";
1664           exit(1);
1665         }
1666       }
1667
1668       // Factor target node emission code (emitted by EmitResultCode) into
1669       // separate functions. Uniquing and share them among all instruction
1670       // selection routines.
1671       for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1672         CodeList &GeneratedCode = CodeForPatterns[i].second;
1673         std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1674         std::vector<std::string> &TargetVTs = PatternVTs[i];
1675         std::set<std::string> Decls = PatternDecls[i];
1676         std::vector<std::string> AddedInits;
1677         int CodeSize = (int)GeneratedCode.size();
1678         int LastPred = -1;
1679         for (int j = CodeSize-1; j >= 0; --j) {
1680           if (LastPred == -1 && GeneratedCode[j].first == 1)
1681             LastPred = j;
1682           else if (LastPred != -1 && GeneratedCode[j].first == 2)
1683             AddedInits.push_back(GeneratedCode[j].second);
1684         }
1685
1686         std::string CalleeCode = "(const SDOperand &N";
1687         std::string CallerCode = "(N";
1688         for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1689           CalleeCode += ", unsigned Opc" + utostr(j);
1690           CallerCode += ", " + TargetOpcodes[j];
1691         }
1692         for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1693           CalleeCode += ", MVT::ValueType VT" + utostr(j);
1694           CallerCode += ", " + TargetVTs[j];
1695         }
1696         for (std::set<std::string>::iterator
1697                I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1698           std::string Name = *I;
1699           CalleeCode += ", SDOperand &" + Name;
1700           CallerCode += ", " + Name;
1701         }
1702         CallerCode += ");";
1703         CalleeCode += ") ";
1704         // Prevent emission routines from being inlined to reduce selection
1705         // routines stack frame sizes.
1706         CalleeCode += "DISABLE_INLINE ";
1707         CalleeCode += "{\n";
1708
1709         for (std::vector<std::string>::const_reverse_iterator
1710                I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1711           CalleeCode += "  " + *I + "\n";
1712
1713         for (int j = LastPred+1; j < CodeSize; ++j)
1714           CalleeCode += "  " + GeneratedCode[j].second + "\n";
1715         for (int j = LastPred+1; j < CodeSize; ++j)
1716           GeneratedCode.pop_back();
1717         CalleeCode += "}\n";
1718
1719         // Uniquing the emission routines.
1720         unsigned EmitFuncNum;
1721         std::map<std::string, unsigned>::iterator EFI =
1722           EmitFunctions.find(CalleeCode);
1723         if (EFI != EmitFunctions.end()) {
1724           EmitFuncNum = EFI->second;
1725         } else {
1726           EmitFuncNum = EmitFunctions.size();
1727           EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1728           OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1729         }
1730
1731         // Replace the emission code within selection routines with calls to the
1732         // emission functions.
1733         CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1734         GeneratedCode.push_back(std::make_pair(false, CallerCode));
1735       }
1736
1737       // Print function.
1738       std::string OpVTStr;
1739       if (OpVT == MVT::iPTR) {
1740         OpVTStr = "_iPTR";
1741       } else if (OpVT == MVT::isVoid) {
1742         // Nodes with a void result actually have a first result type of either
1743         // Other (a chain) or Flag.  Since there is no one-to-one mapping from
1744         // void to this case, we handle it specially here.
1745       } else {
1746         OpVTStr = "_" + getEnumName(OpVT).substr(5);  // Skip 'MVT::'
1747       }
1748       std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1749         OpcodeVTMap.find(OpName);
1750       if (OpVTI == OpcodeVTMap.end()) {
1751         std::vector<std::string> VTSet;
1752         VTSet.push_back(OpVTStr);
1753         OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1754       } else
1755         OpVTI->second.push_back(OpVTStr);
1756
1757       OS << "SDNode *Select_" << getLegalCName(OpName)
1758          << OpVTStr << "(const SDOperand &N) {\n";    
1759
1760       // Loop through and reverse all of the CodeList vectors, as we will be
1761       // accessing them from their logical front, but accessing the end of a
1762       // vector is more efficient.
1763       for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1764         CodeList &GeneratedCode = CodeForPatterns[i].second;
1765         std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1766       }
1767     
1768       // Next, reverse the list of patterns itself for the same reason.
1769       std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1770     
1771       // Emit all of the patterns now, grouped together to share code.
1772       EmitPatterns(CodeForPatterns, 2, OS);
1773     
1774       // If the last pattern has predicates (which could fail) emit code to
1775       // catch the case where nothing handles a pattern.
1776       if (mightNotMatch) {
1777         OS << "  cerr << \"Cannot yet select: \";\n";
1778         if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1779             OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1780             OpName != "ISD::INTRINSIC_VOID") {
1781           OS << "  N.Val->dump(CurDAG);\n";
1782         } else {
1783           OS << "  unsigned iid = cast<ConstantSDNode>(N.getOperand("
1784             "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1785              << "  cerr << \"intrinsic %\"<< "
1786             "Intrinsic::getName((Intrinsic::ID)iid);\n";
1787         }
1788         OS << "  cerr << '\\n';\n"
1789            << "  abort();\n"
1790            << "  return NULL;\n";
1791       }
1792       OS << "}\n\n";
1793     }
1794   }
1795   
1796   // Emit boilerplate.
1797   OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
1798      << "  std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
1799      << "  SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1800     
1801      << "  // Ensure that the asm operands are themselves selected.\n"
1802      << "  for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1803      << "    AddToISelQueue(Ops[j]);\n\n"
1804     
1805      << "  std::vector<MVT::ValueType> VTs;\n"
1806      << "  VTs.push_back(MVT::Other);\n"
1807      << "  VTs.push_back(MVT::Flag);\n"
1808      << "  SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1809                  "Ops.size());\n"
1810      << "  return New.Val;\n"
1811      << "}\n\n";
1812   
1813   OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
1814      << "  SDOperand Chain = N.getOperand(0);\n"
1815      << "  SDOperand N1 = N.getOperand(1);\n"
1816      << "  SDOperand N2 = N.getOperand(2);\n"
1817      << "  unsigned C1 = cast<ConstantSDNode>(N1)->getValue();\n"
1818      << "  unsigned C2 = cast<ConstantSDNode>(N2)->getValue();\n"
1819      << "  SDOperand Tmp1 = CurDAG->getTargetConstant(C1, MVT::i32);\n"
1820      << "  SDOperand Tmp2 = CurDAG->getTargetConstant(C2, MVT::i32);\n"
1821      << "  AddToISelQueue(Chain);\n"
1822      << "  SDOperand Ops[] = { Tmp1, Tmp2, Chain };\n"
1823      << "  return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
1824      << "                               MVT::Other, Ops, 3);\n"
1825      << "}\n\n";
1826
1827   OS << "SDNode *Select_DECLARE(const SDOperand &N) {\n"
1828      << "  SDOperand Chain = N.getOperand(0);\n"
1829      << "  SDOperand N1 = N.getOperand(1);\n"
1830      << "  SDOperand N2 = N.getOperand(2);\n"
1831      << "  if (!isa<FrameIndexSDNode>(N1) || !isa<GlobalAddressSDNode>(N2)) {\n"
1832      << "    cerr << \"Cannot yet select llvm.dbg.declare: \";\n"
1833      << "    N.Val->dump(CurDAG);\n"
1834      << "    abort();\n"
1835      << "  }\n"
1836      << "  int FI = cast<FrameIndexSDNode>(N1)->getIndex();\n"
1837      << "  GlobalValue *GV = cast<GlobalAddressSDNode>(N2)->getGlobal();\n"
1838      << "  SDOperand Tmp1 = "
1839      << "CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());\n"
1840      << "  SDOperand Tmp2 = "
1841      << "CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());\n"
1842      << "  AddToISelQueue(Chain);\n"
1843      << "  SDOperand Ops[] = { Tmp1, Tmp2, Chain };\n"
1844      << "  return CurDAG->getTargetNode(TargetInstrInfo::DECLARE,\n"
1845      << "                               MVT::Other, Ops, 3);\n"
1846      << "}\n\n";
1847
1848   OS << "SDNode *Select_EXTRACT_SUBREG(const SDOperand &N) {\n"
1849      << "  SDOperand N0 = N.getOperand(0);\n"
1850      << "  SDOperand N1 = N.getOperand(1);\n"
1851      << "  unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1852      << "  SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1853      << "  AddToISelQueue(N0);\n"
1854      << "  SDOperand Ops[] = { N0, Tmp };\n"
1855      << "  return CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,\n"
1856      << "                               N.getValueType(), Ops, 2);\n"
1857      << "}\n\n";
1858
1859   OS << "SDNode *Select_INSERT_SUBREG(const SDOperand &N) {\n"
1860      << "  SDOperand N0 = N.getOperand(0);\n"
1861      << "  SDOperand N1 = N.getOperand(1);\n"
1862      << "  SDOperand N2 = N.getOperand(2);\n"
1863      << "  unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
1864      << "  SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1865      << "  AddToISelQueue(N1);\n"
1866      << "  SDOperand Ops[] = { N0, N1, Tmp };\n"
1867      << "  if (N0.getOpcode() == ISD::UNDEF) {\n"
1868      << "    return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1869      << "                                 N.getValueType(), Ops+1, 2);\n"
1870      << "  } else {\n"
1871      << "    AddToISelQueue(N0);\n"
1872      << "    return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1873      << "                                 N.getValueType(), Ops, 3);\n"
1874      << "  }\n"
1875      << "}\n\n";
1876
1877   OS << "// The main instruction selector code.\n"
1878      << "SDNode *SelectCode(SDOperand N) {\n"
1879      << "  if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1880      << "      N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1881      << "INSTRUCTION_LIST_END)) {\n"
1882      << "    return NULL;   // Already selected.\n"
1883      << "  }\n\n"
1884      << "  MVT::ValueType NVT = N.Val->getValueType(0);\n"
1885      << "  switch (N.getOpcode()) {\n"
1886      << "  default: break;\n"
1887      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
1888      << "  case ISD::BasicBlock:\n"
1889      << "  case ISD::Register:\n"
1890      << "  case ISD::HANDLENODE:\n"
1891      << "  case ISD::TargetConstant:\n"
1892      << "  case ISD::TargetConstantPool:\n"
1893      << "  case ISD::TargetFrameIndex:\n"
1894      << "  case ISD::TargetExternalSymbol:\n"
1895      << "  case ISD::TargetJumpTable:\n"
1896      << "  case ISD::TargetGlobalTLSAddress:\n"
1897      << "  case ISD::TargetGlobalAddress: {\n"
1898      << "    return NULL;\n"
1899      << "  }\n"
1900      << "  case ISD::AssertSext:\n"
1901      << "  case ISD::AssertZext: {\n"
1902      << "    AddToISelQueue(N.getOperand(0));\n"
1903      << "    ReplaceUses(N, N.getOperand(0));\n"
1904      << "    return NULL;\n"
1905      << "  }\n"
1906      << "  case ISD::TokenFactor:\n"
1907      << "  case ISD::CopyFromReg:\n"
1908      << "  case ISD::CopyToReg: {\n"
1909      << "    for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1910      << "      AddToISelQueue(N.getOperand(i));\n"
1911      << "    return NULL;\n"
1912      << "  }\n"
1913      << "  case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1914      << "  case ISD::LABEL: return Select_LABEL(N);\n"
1915      << "  case ISD::DECLARE: return Select_DECLARE(N);\n"
1916      << "  case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1917      << "  case ISD::INSERT_SUBREG:  return Select_INSERT_SUBREG(N);\n";
1918
1919     
1920   // Loop over all of the case statements, emiting a call to each method we
1921   // emitted above.
1922   for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1923          PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1924        PBOI != E; ++PBOI) {
1925     const std::string &OpName = PBOI->first;
1926     // Potentially multiple versions of select for this opcode. One for each
1927     // ValueType of the node (or its first true operand if it doesn't produce a
1928     // result.
1929     std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1930       OpcodeVTMap.find(OpName);
1931     std::vector<std::string> &OpVTs = OpVTI->second;
1932     OS << "  case " << OpName << ": {\n";
1933     // Keep track of whether we see a pattern that has an iPtr result.
1934     bool HasPtrPattern = false;
1935     bool HasDefaultPattern = false;
1936       
1937     OS << "    switch (NVT) {\n";
1938     for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1939       std::string &VTStr = OpVTs[i];
1940       if (VTStr.empty()) {
1941         HasDefaultPattern = true;
1942         continue;
1943       }
1944
1945       // If this is a match on iPTR: don't emit it directly, we need special
1946       // code.
1947       if (VTStr == "_iPTR") {
1948         HasPtrPattern = true;
1949         continue;
1950       }
1951       OS << "    case MVT::" << VTStr.substr(1) << ":\n"
1952          << "      return Select_" << getLegalCName(OpName)
1953          << VTStr << "(N);\n";
1954     }
1955     OS << "    default:\n";
1956       
1957     // If there is an iPTR result version of this pattern, emit it here.
1958     if (HasPtrPattern) {
1959       OS << "      if (NVT == TLI.getPointerTy())\n";
1960       OS << "        return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1961     }
1962     if (HasDefaultPattern) {
1963       OS << "      return Select_" << getLegalCName(OpName) << "(N);\n";
1964     }
1965     OS << "      break;\n";
1966     OS << "    }\n";
1967     OS << "    break;\n";
1968     OS << "  }\n";
1969   }
1970
1971   OS << "  } // end of big switch.\n\n"
1972      << "  cerr << \"Cannot yet select: \";\n"
1973      << "  if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
1974      << "      N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
1975      << "      N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
1976      << "    N.Val->dump(CurDAG);\n"
1977      << "  } else {\n"
1978      << "    unsigned iid = cast<ConstantSDNode>(N.getOperand("
1979                "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1980      << "    cerr << \"intrinsic %\"<< "
1981                "Intrinsic::getName((Intrinsic::ID)iid);\n"
1982      << "  }\n"
1983      << "  cerr << '\\n';\n"
1984      << "  abort();\n"
1985      << "  return NULL;\n"
1986      << "}\n";
1987 }
1988
1989 void DAGISelEmitter::run(std::ostream &OS) {
1990   EmitSourceFileHeader("DAG Instruction Selector for the " +
1991                        CGP.getTargetInfo().getName() + " target", OS);
1992   
1993   OS << "// *** NOTE: This file is #included into the middle of the target\n"
1994      << "// *** instruction selector class.  These functions are really "
1995      << "methods.\n\n";
1996   
1997   OS << "// Instruction selector priority queue:\n"
1998      << "std::vector<SDNode*> ISelQueue;\n";
1999   OS << "/// Keep track of nodes which have already been added to queue.\n"
2000      << "unsigned char *ISelQueued;\n";
2001   OS << "/// Keep track of nodes which have already been selected.\n"
2002      << "unsigned char *ISelSelected;\n";
2003
2004
2005   OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
2006   OS << "/// not reach Op.\n";
2007   OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
2008   OS << "  if (Chain->getOpcode() == ISD::EntryToken)\n";
2009   OS << "    return true;\n";
2010   OS << "  else if (Chain->getOpcode() == ISD::TokenFactor)\n";
2011   OS << "    return false;\n";
2012   OS << "  else if (Chain->getNumOperands() > 0) {\n";
2013   OS << "    SDOperand C0 = Chain->getOperand(0);\n";
2014   OS << "    if (C0.getValueType() == MVT::Other)\n";
2015   OS << "      return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
2016   OS << "  }\n";
2017   OS << "  return true;\n";
2018   OS << "}\n";
2019
2020   OS << "/// Sorting functions for the selection queue.\n"
2021      << "struct isel_sort : public std::binary_function"
2022      << "<SDNode*, SDNode*, bool> {\n"
2023      << "  bool operator()(const SDNode* left, const SDNode* right) "
2024      << "const {\n"
2025      << "    return (left->getNodeId() > right->getNodeId());\n"
2026      << "  }\n"
2027      << "};\n\n";
2028
2029   OS << "inline void setQueued(int Id) {\n";
2030   OS << "  ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
2031   OS << "}\n";
2032   OS << "inline bool isQueued(int Id) {\n";
2033   OS << "  return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
2034   OS << "}\n";
2035   OS << "inline void setSelected(int Id) {\n";
2036   OS << "  ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
2037   OS << "}\n";
2038   OS << "inline bool isSelected(int Id) {\n";
2039   OS << "  return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
2040   OS << "}\n\n";
2041
2042   OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
2043   OS << "  int Id = N.Val->getNodeId();\n";
2044   OS << "  if (Id != -1 && !isQueued(Id)) {\n";
2045   OS << "    ISelQueue.push_back(N.Val);\n";
2046  OS << "    std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2047   OS << "    setQueued(Id);\n";
2048   OS << "  }\n";
2049   OS << "}\n\n";
2050
2051   
2052   OS << "class VISIBILITY_HIDDEN ISelQueueUpdater :\n";
2053   OS << "  public SelectionDAG::DAGUpdateListener {\n";
2054   OS << "    std::vector<SDNode*> &ISelQueue;\n";
2055   OS << "    bool HadDelete;\n";
2056   OS << "  public:\n";
2057   OS << "    ISelQueueUpdater(std::vector<SDNode*> &isq)\n";
2058   OS << "      : ISelQueue(isq), HadDelete(false) {}\n";
2059   OS << "    \n";
2060   OS << "    bool hadDelete() const { return HadDelete; }\n";
2061   OS << "    \n";
2062   OS << "    virtual void NodeDeleted(SDNode *N) {\n";
2063   OS << "      ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(),";
2064   OS << " N),\n                      ISelQueue.end());\n";
2065   OS << "      HadDelete = true;\n";
2066   OS << "    }\n";
2067   OS << "    \n";
2068   OS << "    // Ignore updates.\n";
2069   OS << "    virtual void NodeUpdated(SDNode *N) {}\n";
2070   OS << "  };\n";
2071   
2072   OS << "inline void UpdateQueue(const ISelQueueUpdater &ISQU) {\n";
2073   OS << "  if (ISQU.hadDelete())\n";
2074   OS << "    std::make_heap(ISelQueue.begin(), ISelQueue.end(),isel_sort());\n";
2075   OS << "}\n\n";
2076
2077   OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
2078   OS << "  ISelQueueUpdater ISQU(ISelQueue);\n";
2079   OS << "  CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISQU);\n";
2080   OS << "  setSelected(F.Val->getNodeId());\n";
2081   OS << "  UpdateQueue(ISQU);\n";
2082   OS << "}\n";
2083   OS << "void ReplaceUses(SDNode *F, SDNode *T) DISABLE_INLINE {\n";
2084   OS << "  unsigned FNumVals = F->getNumValues();\n";
2085   OS << "  unsigned TNumVals = T->getNumValues();\n";
2086   OS << "  ISelQueueUpdater ISQU(ISelQueue);\n";
2087   OS << "  if (FNumVals != TNumVals) {\n";
2088   OS << "    for (unsigned i = 0, e = std::min(FNumVals, TNumVals); "
2089      << "i < e; ++i)\n";
2090   OS << "      CurDAG->ReplaceAllUsesOfValueWith(SDOperand(F, i), "
2091      << "SDOperand(T, i), &ISQU);\n";
2092   OS << "  } else {\n";
2093   OS << "    CurDAG->ReplaceAllUsesWith(F, T, &ISQU);\n";
2094   OS << "  }\n";
2095   OS << "  setSelected(F->getNodeId());\n";
2096   OS << "  UpdateQueue(ISQU);\n";
2097   OS << "}\n\n";
2098
2099   OS << "// SelectRoot - Top level entry to DAG isel.\n";
2100   OS << "SDOperand SelectRoot(SDOperand Root) {\n";
2101   OS << "  SelectRootInit();\n";
2102   OS << "  unsigned NumBytes = (DAGSize + 7) / 8;\n";
2103   OS << "  ISelQueued   = new unsigned char[NumBytes];\n";
2104   OS << "  ISelSelected = new unsigned char[NumBytes];\n";
2105   OS << "  memset(ISelQueued,   0, NumBytes);\n";
2106   OS << "  memset(ISelSelected, 0, NumBytes);\n";
2107   OS << "\n";
2108   OS << "  // Create a dummy node (which is not added to allnodes), that adds\n"
2109      << "  // a reference to the root node, preventing it from being deleted,\n"
2110      << "  // and tracking any changes of the root.\n"
2111      << "  HandleSDNode Dummy(CurDAG->getRoot());\n"
2112      << "  ISelQueue.push_back(CurDAG->getRoot().Val);\n";
2113   OS << "  while (!ISelQueue.empty()) {\n";
2114   OS << "    SDNode *Node = ISelQueue.front();\n";
2115   OS << "    std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2116   OS << "    ISelQueue.pop_back();\n";
2117   OS << "    if (!isSelected(Node->getNodeId())) {\n";
2118   OS << "      SDNode *ResNode = Select(SDOperand(Node, 0));\n";
2119   OS << "      if (ResNode != Node) {\n";
2120   OS << "        if (ResNode)\n";
2121   OS << "          ReplaceUses(Node, ResNode);\n";
2122   OS << "        if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
2123   OS << "          ISelQueueUpdater ISQU(ISelQueue);\n";
2124   OS << "          CurDAG->RemoveDeadNode(Node, &ISQU);\n";
2125   OS << "          UpdateQueue(ISQU);\n";
2126   OS << "        }\n";
2127   OS << "      }\n";
2128   OS << "    }\n";
2129   OS << "  }\n";
2130   OS << "\n";
2131   OS << "  delete[] ISelQueued;\n";
2132   OS << "  ISelQueued = NULL;\n";
2133   OS << "  delete[] ISelSelected;\n";
2134   OS << "  ISelSelected = NULL;\n";
2135   OS << "  return Dummy.getValue();\n";
2136   OS << "}\n";
2137   
2138   EmitNodeTransforms(OS);
2139   EmitPredicateFunctions(OS);
2140   
2141   DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
2142   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2143        I != E; ++I) {
2144     DOUT << "PATTERN: ";   DEBUG(I->getSrcPattern()->dump());
2145     DOUT << "\nRESULT:  "; DEBUG(I->getDstPattern()->dump());
2146     DOUT << "\n";
2147   }
2148   
2149   // At this point, we have full information about the 'Patterns' we need to
2150   // parse, both implicitly from instructions as well as from explicit pattern
2151   // definitions.  Emit the resultant instruction selector.
2152   EmitInstructionSelector(OS);  
2153   
2154 }