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