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