Replace some special-case code which probably was buggy with an assertion
[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         assert(!NodeHasOutFlag && "Node has flag but not chain!");
1245         ReplaceFroms.push_back("SDValue(N.getNode(), " +
1246                                utostr(NumPatResults) + ")");
1247         ReplaceTos.push_back(ChainName);
1248       }
1249       }
1250
1251       if (ChainAssignmentNeeded) {
1252         // Remember which op produces the chain.
1253         std::string ChainAssign;
1254         if (!isRoot)
1255           ChainAssign = ChainName + " = SDValue(" + NodeName +
1256                         ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1257         else
1258           ChainAssign = ChainName + " = SDValue(" + NodeName +
1259                         ", " + utostr(NumResults+NumDstRegs) + ");";
1260
1261         After.push_front(ChainAssign);
1262       }
1263
1264       if (ReplaceFroms.size() == 1) {
1265         After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1266                         ReplaceTos[0] + ");");
1267       } else if (!ReplaceFroms.empty()) {
1268         After.push_back("const SDValue Froms[] = {");
1269         for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1270           After.push_back("  " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1271         After.push_back("};");
1272         After.push_back("const SDValue Tos[] = {");
1273         for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1274           After.push_back("  " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1275         After.push_back("};");
1276         After.push_back("ReplaceUses(Froms, Tos, " +
1277                         itostr(ReplaceFroms.size()) + ");");
1278       }
1279
1280       // We prefer to use SelectNodeTo since it avoids allocation when
1281       // possible and it avoids CSE map recalculation for the node's
1282       // users, however it's tricky to use in a non-root context.
1283       //
1284       // We also don't use SelectNodeTo if the pattern replacement is being
1285       // used to jettison a chain result, since morphing the node in place
1286       // would leave users of the chain dangling.
1287       //
1288       if (!isRoot || (InputHasChain && !NodeHasChain)) {
1289         Code = "CurDAG->getMachineNode(" + Code;
1290       } else {
1291         Code = "CurDAG->SelectNodeTo(N.getNode(), " + Code;
1292       }
1293       if (isRoot) {
1294         if (After.empty())
1295           CodePrefix = "return ";
1296         else
1297           After.push_back("return ResNode;");
1298       }
1299
1300       emitCode(CodePrefix + Code + ");");
1301
1302       if (GenDebug) {
1303         if (!isRoot) {
1304           emitCode("CurDAG->setSubgraphColor(" + NodeName +".getNode(), \"yellow\");");
1305           emitCode("CurDAG->setSubgraphColor(" + NodeName +".getNode(), \"black\");");
1306         }
1307         else {
1308           emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1309           emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1310         }
1311       }
1312
1313       for (unsigned i = 0, e = After.size(); i != e; ++i)
1314         emitCode(After[i]);
1315
1316       return NodeOps;
1317     }
1318     if (Op->isSubClassOf("SDNodeXForm")) {
1319       assert(N->getNumChildren() == 1 && "node xform should have one child!");
1320       // PatLeaf node - the operand may or may not be a leaf node. But it should
1321       // behave like one.
1322       std::vector<std::string> Ops =
1323         EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1324                        ResNodeDecled, true);
1325       unsigned ResNo = TmpNo++;
1326       emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1327                + "(" + Ops.back() + ".getNode());");
1328       NodeOps.push_back("Tmp" + utostr(ResNo));
1329       if (isRoot)
1330         emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1331       return NodeOps;
1332     }
1333
1334     N->dump();
1335     errs() << "\n";
1336     throw std::string("Unknown node in result pattern!");
1337   }
1338
1339   /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1340   /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that 
1341   /// 'Pat' may be missing types.  If we find an unresolved type to add a check
1342   /// for, this returns true otherwise false if Pat has all types.
1343   bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1344                           const std::string &Prefix, bool isRoot = false) {
1345     // Did we find one?
1346     if (Pat->getExtTypes() != Other->getExtTypes()) {
1347       // Move a type over from 'other' to 'pat'.
1348       Pat->setTypes(Other->getExtTypes());
1349       // The top level node type is checked outside of the select function.
1350       if (!isRoot)
1351         emitCheck(Prefix + ".getValueType() == " +
1352                   getName(Pat->getTypeNum(0)));
1353       return true;
1354     }
1355   
1356     unsigned OpNo =
1357       (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1358     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1359       if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1360                              Prefix + utostr(OpNo)))
1361         return true;
1362     return false;
1363   }
1364
1365 private:
1366   /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1367   /// being built.
1368   void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1369                             bool &ChainEmitted, bool &InFlagDecled,
1370                             bool &ResNodeDecled, bool isRoot = false) {
1371     const CodeGenTarget &T = CGP.getTargetInfo();
1372     unsigned OpNo =
1373       (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1374     bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1375     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1376       TreePatternNode *Child = N->getChild(i);
1377       if (!Child->isLeaf()) {
1378         EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1379                              InFlagDecled, ResNodeDecled);
1380       } else {
1381         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1382           if (!Child->getName().empty()) {
1383             std::string Name = RootName + utostr(OpNo);
1384             if (Duplicates.find(Name) != Duplicates.end())
1385               // A duplicate! Do not emit a copy for this node.
1386               continue;
1387           }
1388
1389           Record *RR = DI->getDef();
1390           if (RR->isSubClassOf("Register")) {
1391             MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
1392             if (RVT == MVT::Flag) {
1393               if (!InFlagDecled) {
1394                 emitCode("SDValue InFlag = " + RootName + utostr(OpNo) + ";");
1395                 InFlagDecled = true;
1396               } else
1397                 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1398             } else {
1399               if (!ChainEmitted) {
1400                 emitCode("SDValue Chain = CurDAG->getEntryNode();");
1401                 ChainName = "Chain";
1402                 ChainEmitted = true;
1403               }
1404               if (!InFlagDecled) {
1405                 emitCode("SDValue InFlag(0, 0);");
1406                 InFlagDecled = true;
1407               }
1408               std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1409               emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1410                        ", " + RootName + ".getDebugLoc()" +
1411                        ", " + getQualifiedName(RR) +
1412                        ", " +  RootName + utostr(OpNo) + ", InFlag).getNode();");
1413               ResNodeDecled = true;
1414               emitCode(ChainName + " = SDValue(ResNode, 0);");
1415               emitCode("InFlag = SDValue(ResNode, 1);");
1416             }
1417           }
1418         }
1419       }
1420     }
1421
1422     if (HasInFlag) {
1423       if (!InFlagDecled) {
1424         emitCode("SDValue InFlag = " + RootName +
1425                ".getOperand(" + utostr(OpNo) + ");");
1426         InFlagDecled = true;
1427       } else
1428         emitCode("InFlag = " + RootName +
1429                ".getOperand(" + utostr(OpNo) + ");");
1430     }
1431   }
1432 };
1433
1434 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1435 /// stream to match the pattern, and generate the code for the match if it
1436 /// succeeds.  Returns true if the pattern is not guaranteed to match.
1437 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1438                   std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1439                                            std::set<std::string> &GeneratedDecl,
1440                                         std::vector<std::string> &TargetOpcodes,
1441                                             std::vector<std::string> &TargetVTs,
1442                                             bool &OutputIsVariadic,
1443                                             unsigned &NumInputRootOps) {
1444   OutputIsVariadic = false;
1445   NumInputRootOps = 0;
1446
1447   PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
1448                              Pattern.getSrcPattern(), Pattern.getDstPattern(),
1449                              GeneratedCode, GeneratedDecl,
1450                              TargetOpcodes, TargetVTs,
1451                              OutputIsVariadic, NumInputRootOps);
1452
1453   // Emit the matcher, capturing named arguments in VariableMap.
1454   bool FoundChain = false;
1455   Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1456
1457   // TP - Get *SOME* tree pattern, we don't care which.
1458   TreePattern &TP = *CGP.pf_begin()->second;
1459   
1460   // At this point, we know that we structurally match the pattern, but the
1461   // types of the nodes may not match.  Figure out the fewest number of type 
1462   // comparisons we need to emit.  For example, if there is only one integer
1463   // type supported by a target, there should be no type comparisons at all for
1464   // integer patterns!
1465   //
1466   // To figure out the fewest number of type checks needed, clone the pattern,
1467   // remove the types, then perform type inference on the pattern as a whole.
1468   // If there are unresolved types, emit an explicit check for those types,
1469   // apply the type to the tree, then rerun type inference.  Iterate until all
1470   // types are resolved.
1471   //
1472   TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1473   RemoveAllTypes(Pat);
1474   
1475   do {
1476     // Resolve/propagate as many types as possible.
1477     try {
1478       bool MadeChange = true;
1479       while (MadeChange)
1480         MadeChange = Pat->ApplyTypeConstraints(TP,
1481                                                true/*Ignore reg constraints*/);
1482     } catch (...) {
1483       assert(0 && "Error: could not find consistent types for something we"
1484              " already decided was ok!");
1485       abort();
1486     }
1487
1488     // Insert a check for an unresolved type and add it to the tree.  If we find
1489     // an unresolved type to add a check for, this returns true and we iterate,
1490     // otherwise we are done.
1491   } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1492
1493   Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1494                          false, false, false, true);
1495   delete Pat;
1496 }
1497
1498 /// EraseCodeLine - Erase one code line from all of the patterns.  If removing
1499 /// a line causes any of them to be empty, remove them and return true when
1500 /// done.
1501 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*, 
1502                           std::vector<std::pair<unsigned, std::string> > > >
1503                           &Patterns) {
1504   bool ErasedPatterns = false;
1505   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1506     Patterns[i].second.pop_back();
1507     if (Patterns[i].second.empty()) {
1508       Patterns.erase(Patterns.begin()+i);
1509       --i; --e;
1510       ErasedPatterns = true;
1511     }
1512   }
1513   return ErasedPatterns;
1514 }
1515
1516 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1517 /// code together between the patterns.
1518 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*, 
1519                               std::vector<std::pair<unsigned, std::string> > > >
1520                                   &Patterns, unsigned Indent,
1521                                   raw_ostream &OS) {
1522   typedef std::pair<unsigned, std::string> CodeLine;
1523   typedef std::vector<CodeLine> CodeList;
1524   typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1525   
1526   if (Patterns.empty()) return;
1527   
1528   // Figure out how many patterns share the next code line.  Explicitly copy
1529   // FirstCodeLine so that we don't invalidate a reference when changing
1530   // Patterns.
1531   const CodeLine FirstCodeLine = Patterns.back().second.back();
1532   unsigned LastMatch = Patterns.size()-1;
1533   while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1534     --LastMatch;
1535   
1536   // If not all patterns share this line, split the list into two pieces.  The
1537   // first chunk will use this line, the second chunk won't.
1538   if (LastMatch != 0) {
1539     PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1540     PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1541     
1542     // FIXME: Emit braces?
1543     if (Shared.size() == 1) {
1544       const PatternToMatch &Pattern = *Shared.back().first;
1545       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1546       Pattern.getSrcPattern()->print(OS);
1547       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1548       Pattern.getDstPattern()->print(OS);
1549       OS << "\n";
1550       unsigned AddedComplexity = Pattern.getAddedComplexity();
1551       OS << std::string(Indent, ' ') << "// Pattern complexity = "
1552          << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1553          << "  cost = "
1554          << getResultPatternCost(Pattern.getDstPattern(), CGP)
1555          << "  size = "
1556          << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1557     }
1558     if (FirstCodeLine.first != 1) {
1559       OS << std::string(Indent, ' ') << "{\n";
1560       Indent += 2;
1561     }
1562     EmitPatterns(Shared, Indent, OS);
1563     if (FirstCodeLine.first != 1) {
1564       Indent -= 2;
1565       OS << std::string(Indent, ' ') << "}\n";
1566     }
1567     
1568     if (Other.size() == 1) {
1569       const PatternToMatch &Pattern = *Other.back().first;
1570       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1571       Pattern.getSrcPattern()->print(OS);
1572       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1573       Pattern.getDstPattern()->print(OS);
1574       OS << "\n";
1575       unsigned AddedComplexity = Pattern.getAddedComplexity();
1576       OS << std::string(Indent, ' ') << "// Pattern complexity = "
1577          << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1578          << "  cost = "
1579          << getResultPatternCost(Pattern.getDstPattern(), CGP)
1580          << "  size = "
1581          << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1582     }
1583     EmitPatterns(Other, Indent, OS);
1584     return;
1585   }
1586   
1587   // Remove this code from all of the patterns that share it.
1588   bool ErasedPatterns = EraseCodeLine(Patterns);
1589   
1590   bool isPredicate = FirstCodeLine.first == 1;
1591   
1592   // Otherwise, every pattern in the list has this line.  Emit it.
1593   if (!isPredicate) {
1594     // Normal code.
1595     OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1596   } else {
1597     OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1598     
1599     // If the next code line is another predicate, and if all of the pattern
1600     // in this group share the same next line, emit it inline now.  Do this
1601     // until we run out of common predicates.
1602     while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1603       // Check that all of the patterns in Patterns end with the same predicate.
1604       bool AllEndWithSamePredicate = true;
1605       for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1606         if (Patterns[i].second.back() != Patterns.back().second.back()) {
1607           AllEndWithSamePredicate = false;
1608           break;
1609         }
1610       // If all of the predicates aren't the same, we can't share them.
1611       if (!AllEndWithSamePredicate) break;
1612       
1613       // Otherwise we can.  Emit it shared now.
1614       OS << " &&\n" << std::string(Indent+4, ' ')
1615          << Patterns.back().second.back().second;
1616       ErasedPatterns = EraseCodeLine(Patterns);
1617     }
1618     
1619     OS << ") {\n";
1620     Indent += 2;
1621   }
1622   
1623   EmitPatterns(Patterns, Indent, OS);
1624   
1625   if (isPredicate)
1626     OS << std::string(Indent-2, ' ') << "}\n";
1627 }
1628
1629 static std::string getLegalCName(std::string OpName) {
1630   std::string::size_type pos = OpName.find("::");
1631   if (pos != std::string::npos)
1632     OpName.replace(pos, 2, "_");
1633   return OpName;
1634 }
1635
1636 void DAGISelEmitter::EmitInstructionSelector(raw_ostream &OS) {
1637   const CodeGenTarget &Target = CGP.getTargetInfo();
1638   
1639   // Get the namespace to insert instructions into.
1640   std::string InstNS = Target.getInstNamespace();
1641   if (!InstNS.empty()) InstNS += "::";
1642   
1643   // Group the patterns by their top-level opcodes.
1644   std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1645   // All unique target node emission functions.
1646   std::map<std::string, unsigned> EmitFunctions;
1647   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1648        E = CGP.ptm_end(); I != E; ++I) {
1649     const PatternToMatch &Pattern = *I;
1650
1651     TreePatternNode *Node = Pattern.getSrcPattern();
1652     if (!Node->isLeaf()) {
1653       PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1654         push_back(&Pattern);
1655     } else {
1656       const ComplexPattern *CP;
1657       if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1658         PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1659           push_back(&Pattern);
1660       } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1661         std::vector<Record*> OpNodes = CP->getRootNodes();
1662         for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1663           PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1664             .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1665                     &Pattern);
1666         }
1667       } else {
1668         errs() << "Unrecognized opcode '";
1669         Node->dump();
1670         errs() << "' on tree pattern '";
1671         errs() << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1672         exit(1);
1673       }
1674     }
1675   }
1676
1677   // For each opcode, there might be multiple select functions, one per
1678   // ValueType of the node (or its first operand if it doesn't produce a
1679   // non-chain result.
1680   std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1681
1682   // Emit one Select_* method for each top-level opcode.  We do this instead of
1683   // emitting one giant switch statement to support compilers where this will
1684   // result in the recursive functions taking less stack space.
1685   for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1686          PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1687        PBOI != E; ++PBOI) {
1688     const std::string &OpName = PBOI->first;
1689     std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1690     assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1691
1692     // Split them into groups by type.
1693     std::map<MVT::SimpleValueType,
1694              std::vector<const PatternToMatch*> > PatternsByType;
1695     for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1696       const PatternToMatch *Pat = PatternsOfOp[i];
1697       TreePatternNode *SrcPat = Pat->getSrcPattern();
1698       PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
1699     }
1700
1701     for (std::map<MVT::SimpleValueType,
1702                   std::vector<const PatternToMatch*> >::iterator
1703            II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1704          ++II) {
1705       MVT::SimpleValueType OpVT = II->first;
1706       std::vector<const PatternToMatch*> &Patterns = II->second;
1707       typedef std::pair<unsigned, std::string> CodeLine;
1708       typedef std::vector<CodeLine> CodeList;
1709       typedef CodeList::iterator CodeListI;
1710     
1711       std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1712       std::vector<std::vector<std::string> > PatternOpcodes;
1713       std::vector<std::vector<std::string> > PatternVTs;
1714       std::vector<std::set<std::string> > PatternDecls;
1715       std::vector<bool> OutputIsVariadicFlags;
1716       std::vector<unsigned> NumInputRootOpsCounts;
1717       for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1718         CodeList GeneratedCode;
1719         std::set<std::string> GeneratedDecl;
1720         std::vector<std::string> TargetOpcodes;
1721         std::vector<std::string> TargetVTs;
1722         bool OutputIsVariadic;
1723         unsigned NumInputRootOps;
1724         GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1725                                TargetOpcodes, TargetVTs,
1726                                OutputIsVariadic, NumInputRootOps);
1727         CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1728         PatternDecls.push_back(GeneratedDecl);
1729         PatternOpcodes.push_back(TargetOpcodes);
1730         PatternVTs.push_back(TargetVTs);
1731         OutputIsVariadicFlags.push_back(OutputIsVariadic);
1732         NumInputRootOpsCounts.push_back(NumInputRootOps);
1733       }
1734     
1735       // Factor target node emission code (emitted by EmitResultCode) into
1736       // separate functions. Uniquing and share them among all instruction
1737       // selection routines.
1738       for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1739         CodeList &GeneratedCode = CodeForPatterns[i].second;
1740         std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1741         std::vector<std::string> &TargetVTs = PatternVTs[i];
1742         std::set<std::string> Decls = PatternDecls[i];
1743         bool OutputIsVariadic = OutputIsVariadicFlags[i];
1744         unsigned NumInputRootOps = NumInputRootOpsCounts[i];
1745         std::vector<std::string> AddedInits;
1746         int CodeSize = (int)GeneratedCode.size();
1747         int LastPred = -1;
1748         for (int j = CodeSize-1; j >= 0; --j) {
1749           if (LastPred == -1 && GeneratedCode[j].first == 1)
1750             LastPred = j;
1751           else if (LastPred != -1 && GeneratedCode[j].first == 2)
1752             AddedInits.push_back(GeneratedCode[j].second);
1753         }
1754
1755         std::string CalleeCode = "(const SDValue &N";
1756         std::string CallerCode = "(N";
1757         for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1758           CalleeCode += ", unsigned Opc" + utostr(j);
1759           CallerCode += ", " + TargetOpcodes[j];
1760         }
1761         for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1762           CalleeCode += ", MVT::SimpleValueType VT" + utostr(j);
1763           CallerCode += ", " + TargetVTs[j];
1764         }
1765         for (std::set<std::string>::iterator
1766                I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1767           std::string Name = *I;
1768           CalleeCode += ", SDValue &" + Name;
1769           CallerCode += ", " + Name;
1770         }
1771
1772         if (OutputIsVariadic) {
1773           CalleeCode += ", unsigned NumInputRootOps";
1774           CallerCode += ", " + utostr(NumInputRootOps);
1775         }
1776
1777         CallerCode += ");";
1778         CalleeCode += ") {\n";
1779
1780         for (std::vector<std::string>::const_reverse_iterator
1781                I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1782           CalleeCode += "  " + *I + "\n";
1783
1784         for (int j = LastPred+1; j < CodeSize; ++j)
1785           CalleeCode += "  " + GeneratedCode[j].second + "\n";
1786         for (int j = LastPred+1; j < CodeSize; ++j)
1787           GeneratedCode.pop_back();
1788         CalleeCode += "}\n";
1789
1790         // Uniquing the emission routines.
1791         unsigned EmitFuncNum;
1792         std::map<std::string, unsigned>::iterator EFI =
1793           EmitFunctions.find(CalleeCode);
1794         if (EFI != EmitFunctions.end()) {
1795           EmitFuncNum = EFI->second;
1796         } else {
1797           EmitFuncNum = EmitFunctions.size();
1798           EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1799           // Prevent emission routines from being inlined to reduce selection
1800           // routines stack frame sizes.
1801           OS << "DISABLE_INLINE ";
1802           OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1803         }
1804
1805         // Replace the emission code within selection routines with calls to the
1806         // emission functions.
1807         if (GenDebug) {
1808           GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N.getNode(), \"red\");"));
1809         }
1810         CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) + CallerCode;
1811         GeneratedCode.push_back(std::make_pair(3, CallerCode));
1812         if (GenDebug) {
1813           GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
1814           GeneratedCode.push_back(std::make_pair(0, "  CurDAG->setSubgraphColor(Result, \"yellow\");"));
1815           GeneratedCode.push_back(std::make_pair(0, "  CurDAG->setSubgraphColor(Result, \"black\");"));
1816           GeneratedCode.push_back(std::make_pair(0, "}"));
1817           //GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N.getNode(), \"black\");"));
1818         }
1819         GeneratedCode.push_back(std::make_pair(0, "return Result;"));
1820       }
1821
1822       // Print function.
1823       std::string OpVTStr;
1824       if (OpVT == MVT::iPTR) {
1825         OpVTStr = "_iPTR";
1826       } else if (OpVT == MVT::iPTRAny) {
1827         OpVTStr = "_iPTRAny";
1828       } else if (OpVT == MVT::isVoid) {
1829         // Nodes with a void result actually have a first result type of either
1830         // Other (a chain) or Flag.  Since there is no one-to-one mapping from
1831         // void to this case, we handle it specially here.
1832       } else {
1833         OpVTStr = "_" + getEnumName(OpVT).substr(5);  // Skip 'MVT::'
1834       }
1835       std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1836         OpcodeVTMap.find(OpName);
1837       if (OpVTI == OpcodeVTMap.end()) {
1838         std::vector<std::string> VTSet;
1839         VTSet.push_back(OpVTStr);
1840         OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1841       } else
1842         OpVTI->second.push_back(OpVTStr);
1843
1844       // We want to emit all of the matching code now.  However, we want to emit
1845       // the matches in order of minimal cost.  Sort the patterns so the least
1846       // cost one is at the start.
1847       std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1848                        PatternSortingPredicate(CGP));
1849
1850       // Scan the code to see if all of the patterns are reachable and if it is
1851       // possible that the last one might not match.
1852       bool mightNotMatch = true;
1853       for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1854         CodeList &GeneratedCode = CodeForPatterns[i].second;
1855         mightNotMatch = false;
1856
1857         for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1858           if (GeneratedCode[j].first == 1) { // predicate.
1859             mightNotMatch = true;
1860             break;
1861           }
1862         }
1863       
1864         // If this pattern definitely matches, and if it isn't the last one, the
1865         // patterns after it CANNOT ever match.  Error out.
1866         if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1867           errs() << "Pattern '";
1868           CodeForPatterns[i].first->getSrcPattern()->print(errs());
1869           errs() << "' is impossible to select!\n";
1870           exit(1);
1871         }
1872       }
1873
1874       // Loop through and reverse all of the CodeList vectors, as we will be
1875       // accessing them from their logical front, but accessing the end of a
1876       // vector is more efficient.
1877       for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1878         CodeList &GeneratedCode = CodeForPatterns[i].second;
1879         std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1880       }
1881     
1882       // Next, reverse the list of patterns itself for the same reason.
1883       std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1884     
1885       OS << "SDNode *Select_" << getLegalCName(OpName)
1886          << OpVTStr << "(const SDValue &N) {\n";    
1887
1888       // Emit all of the patterns now, grouped together to share code.
1889       EmitPatterns(CodeForPatterns, 2, OS);
1890     
1891       // If the last pattern has predicates (which could fail) emit code to
1892       // catch the case where nothing handles a pattern.
1893       if (mightNotMatch) {
1894         OS << "\n";
1895         if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1896             OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1897             OpName != "ISD::INTRINSIC_VOID")
1898           OS << "  CannotYetSelect(N);\n";
1899         else
1900           OS << "  CannotYetSelectIntrinsic(N);\n";
1901
1902         OS << "  return NULL;\n";
1903       }
1904       OS << "}\n\n";
1905     }
1906   }
1907   
1908   OS << "// The main instruction selector code.\n"
1909      << "SDNode *SelectCode(SDValue N) {\n"
1910      << "  MVT::SimpleValueType NVT = N.getNode()->getValueType(0).getSimpleVT().SimpleTy;\n"
1911      << "  switch (N.getOpcode()) {\n"
1912      << "  default:\n"
1913      << "    assert(!N.isMachineOpcode() && \"Node already selected!\");\n"
1914      << "    break;\n"
1915      << "  case ISD::EntryToken:       // These nodes remain the same.\n"
1916      << "  case ISD::BasicBlock:\n"
1917      << "  case ISD::Register:\n"
1918      << "  case ISD::HANDLENODE:\n"
1919      << "  case ISD::TargetConstant:\n"
1920      << "  case ISD::TargetConstantFP:\n"
1921      << "  case ISD::TargetConstantPool:\n"
1922      << "  case ISD::TargetFrameIndex:\n"
1923      << "  case ISD::TargetExternalSymbol:\n"
1924      << "  case ISD::TargetBlockAddress:\n"
1925      << "  case ISD::TargetJumpTable:\n"
1926      << "  case ISD::TargetGlobalTLSAddress:\n"
1927      << "  case ISD::TargetGlobalAddress:\n"
1928      << "  case ISD::TokenFactor:\n"
1929      << "  case ISD::CopyFromReg:\n"
1930      << "  case ISD::CopyToReg: {\n"
1931      << "    return NULL;\n"
1932      << "  }\n"
1933      << "  case ISD::AssertSext:\n"
1934      << "  case ISD::AssertZext: {\n"
1935      << "    ReplaceUses(N, N.getOperand(0));\n"
1936      << "    return NULL;\n"
1937      << "  }\n"
1938      << "  case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1939      << "  case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
1940      << "  case ISD::UNDEF: return Select_UNDEF(N);\n";
1941
1942   // Loop over all of the case statements, emiting a call to each method we
1943   // emitted above.
1944   for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1945          PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1946        PBOI != E; ++PBOI) {
1947     const std::string &OpName = PBOI->first;
1948     // Potentially multiple versions of select for this opcode. One for each
1949     // ValueType of the node (or its first true operand if it doesn't produce a
1950     // result.
1951     std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1952       OpcodeVTMap.find(OpName);
1953     std::vector<std::string> &OpVTs = OpVTI->second;
1954     OS << "  case " << OpName << ": {\n";
1955     // If we have only one variant and it's the default, elide the
1956     // switch.  Marginally faster, and makes MSVC happier.
1957     if (OpVTs.size()==1 && OpVTs[0].empty()) {
1958       OS << "    return Select_" << getLegalCName(OpName) << "(N);\n";
1959       OS << "    break;\n";
1960       OS << "  }\n";
1961       continue;
1962     }
1963     // Keep track of whether we see a pattern that has an iPtr result.
1964     bool HasPtrPattern = false;
1965     bool HasDefaultPattern = false;
1966       
1967     OS << "    switch (NVT) {\n";
1968     for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1969       std::string &VTStr = OpVTs[i];
1970       if (VTStr.empty()) {
1971         HasDefaultPattern = true;
1972         continue;
1973       }
1974
1975       // If this is a match on iPTR: don't emit it directly, we need special
1976       // code.
1977       if (VTStr == "_iPTR") {
1978         HasPtrPattern = true;
1979         continue;
1980       }
1981       OS << "    case MVT::" << VTStr.substr(1) << ":\n"
1982          << "      return Select_" << getLegalCName(OpName)
1983          << VTStr << "(N);\n";
1984     }
1985     OS << "    default:\n";
1986       
1987     // If there is an iPTR result version of this pattern, emit it here.
1988     if (HasPtrPattern) {
1989       OS << "      if (TLI.getPointerTy() == NVT)\n";
1990       OS << "        return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1991     }
1992     if (HasDefaultPattern) {
1993       OS << "      return Select_" << getLegalCName(OpName) << "(N);\n";
1994     }
1995     OS << "      break;\n";
1996     OS << "    }\n";
1997     OS << "    break;\n";
1998     OS << "  }\n";
1999   }
2000
2001   OS << "  } // end of big switch.\n\n"
2002      << "  if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2003      << "      N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2004      << "      N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
2005      << "    CannotYetSelect(N);\n"
2006      << "  } else {\n"
2007      << "    CannotYetSelectIntrinsic(N);\n"
2008      << "  }\n"
2009      << "  return NULL;\n"
2010      << "}\n\n";
2011 }
2012
2013 void DAGISelEmitter::run(raw_ostream &OS) {
2014   EmitSourceFileHeader("DAG Instruction Selector for the " +
2015                        CGP.getTargetInfo().getName() + " target", OS);
2016   
2017   OS << "// *** NOTE: This file is #included into the middle of the target\n"
2018      << "// *** instruction selector class.  These functions are really "
2019      << "methods.\n\n";
2020
2021   OS << "// Include standard, target-independent definitions and methods used\n"
2022      << "// by the instruction selector.\n";
2023   OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
2024   
2025   EmitNodeTransforms(OS);
2026   EmitPredicateFunctions(OS);
2027   
2028   DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n");
2029   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2030        I != E; ++I) {
2031     DEBUG(errs() << "PATTERN: ";   I->getSrcPattern()->dump());
2032     DEBUG(errs() << "\nRESULT:  "; I->getDstPattern()->dump());
2033     DEBUG(errs() << "\n");
2034   }
2035   
2036   // At this point, we have full information about the 'Patterns' we need to
2037   // parse, both implicitly from instructions as well as from explicit pattern
2038   // definitions.  Emit the resultant instruction selector.
2039   EmitInstructionSelector(OS);  
2040   
2041 }