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