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