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