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