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