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